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,400
|
coordinatetools.py
|
psychopy_psychopy/psychopy/tools/coordinatetools.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).
"""Functions and classes related to coordinate system conversion
"""
import numpy
from numpy import radians
def cart2pol(x, y, units='deg'):
"""Convert from cartesian to polar coordinates.
:usage:
theta, radius = cart2pol(x, y, units='deg')
units refers to the units (rad or deg) for theta that should be returned
"""
radius = numpy.hypot(x, y)
theta = numpy.arctan2(y, x)
if units in ('deg', 'degs'):
theta = theta * 180 / numpy.pi
return theta, radius
def pol2cart(theta, radius, units='deg'):
"""Convert from polar to cartesian coordinates.
usage::
x,y = pol2cart(theta, radius, units='deg')
"""
if units in ('deg', 'degs'):
theta = theta * numpy.pi / 180.0
xx = radius * numpy.cos(theta)
yy = radius * numpy.sin(theta)
return xx, yy
def cart2sph(z, y, x):
"""Convert from cartesian coordinates (x,y,z) to spherical (elevation,
azimuth, radius). Output is in degrees.
usage:
array3xN[el,az,rad] = cart2sph(array3xN[x,y,z])
OR
elevation, azimuth, radius = cart2sph(x,y,z)
If working in DKL space, z = Luminance, y = S and x = LM
"""
width = len(z)
elevation = numpy.empty([width, width])
radius = numpy.empty([width, width])
azimuth = numpy.empty([width, width])
radius = numpy.sqrt(x**2 + y**2 + z**2)
azimuth = numpy.arctan2(y, x)
# Calculating the elevation from x,y up
elevation = numpy.arctan2(z, numpy.sqrt(x**2 + y**2))
# convert azimuth and elevation angles into degrees
azimuth *= 180.0 / numpy.pi
elevation *= 180.0 / numpy.pi
sphere = numpy.array([elevation, azimuth, radius])
sphere = numpy.rollaxis(sphere, 0, 3)
return sphere
def sph2cart(*args):
"""Convert from spherical coordinates (elevation, azimuth, radius)
to cartesian (x,y,z).
usage:
array3xN[x,y,z] = sph2cart(array3xN[el,az,rad])
OR
x,y,z = sph2cart(elev, azim, radius)
"""
if len(args) == 1: # received an Nx3 array
elev = args[0][0, :]
azim = args[0][1, :]
radius = args[0][2, :]
returnAsArray = True
elif len(args) == 3:
elev = args[0]
azim = args[1]
radius = args[2]
returnAsArray = False
z = radius * numpy.sin(radians(elev))
x = radius * numpy.cos(radians(elev)) * numpy.cos(radians(azim))
y = radius * numpy.cos(radians(elev)) * numpy.sin(radians(azim))
if returnAsArray:
return numpy.asarray([x, y, z])
else:
return x, y, z
| 2,808
|
Python
|
.py
| 78
| 30.25641
| 79
| 0.627589
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,401
|
versionchooser.py
|
psychopy_psychopy/psychopy/tools/versionchooser.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).
"""PsychoPy Version Chooser to specify version within experiment scripts.
"""
import os
import sys
import re
import subprocess # for git commandline invocation
from collections import OrderedDict
from subprocess import CalledProcessError
import psychopy # for currently loaded version
from psychopy import prefs
# the following will all have been imported so import here and reload later
from psychopy import logging, tools, web, constants, preferences, __version__
from packaging.version import Version
from importlib import reload
from packaging.version import Version, InvalidVersion, VERSION_PATTERN
USERDIR = prefs.paths['userPrefsDir']
VER_SUBDIR = 'versions'
VERSIONSDIR = os.path.join(USERDIR, VER_SUBDIR)
# cache because checking github for remote version tags can be slow
_localVersionsCache = []
_remoteVersionsCache = []
# define ranges of PsychoPy versions which support each Python version
versionMap = OrderedDict({
Version('2.7'): (Version("0.0"), Version("2020.2.0")),
Version('3.6'): (Version("1.9"), Version("2022.1.0")),
Version('3.8'): (Version("2022.1.0"), None),
Version('3.10'): (Version("2023.2.0"), None),
})
# fill out intermediate versions
for n in range(13):
v = Version(f"3.{n}")
av = max([key for key in versionMap if key <= v])
versionMap[v] = versionMap[av]
# parse current psychopy version
psychopyVersion = Version(__version__)
def parseVersionSafely(version, fallback=Version("0")):
"""
Wrapper around packaging.version.parse which avoids raising an InvalidVersionError, making it
safer to use on potentially inconsistent version strings.
Checks for valid version string before parsing, then tries:
- With all but numbers, dots and keywords removed
- With all but numbers and dots removed
Finally, if the version number is still invalid, will return whatever is supplied as
`fallback` rather than raising an error.
Parameters
----------
version : str
Version string to parse
fallback : Version
Value to return if version fails to parse
Returns
-------
Version
Parsed version string
"""
# if version is already parsed, return unchanged
if isinstance(version, Version):
return Version
# if not a string, make into a string
if not isinstance(version, str):
version = str(version)
# if version is already valid, do normal parsing
if re.fullmatch(version, VERSION_PATTERN):
return Version(version)
# try stripping all but numbers, dots and keywords
version = "".join(
re.findall(r"\d|\.|a|b|c|rc|alpha|beta|pre|preview|post|rev|r|dev", version)
)
if re.fullmatch(version, VERSION_PATTERN):
return Version(version)
# try stripping all but numbers and dots
version = "".join(
re.findall(r"\d|\.", version)
)
if re.fullmatch(version, VERSION_PATTERN):
return Version(version)
# finally, try just in case and return fallback on fail
try:
return Version(version)
except InvalidVersion:
return fallback
class VersionRange:
def __init__(self, first=None, last=None):
self.first = first
self.last = last
@property
def first(self):
return self._first
@first.setter
def first(self, value):
self._first = value
if self._first is not None:
self._first = Version(self._first)
@property
def last(self):
return self._last
@last.setter
def last(self, value):
self._last = value
if self._last is not None:
self._last = Version(self._last)
def __contains__(self, item):
# enforce Version type
if isinstance(item, str):
item = Version(item)
# if not less than or greater than, assume contains
lt = self > item
gt = self < item
return not any((lt, gt))
def __eq__(self, other):
return other in self
def __lt__(self, other):
# if no first version, nothing is less than
if self.last is None:
return False
# enforce Version type
if isinstance(other, str):
other = Version(other)
# otherwise compare to first version
return self.last < other
def __le__(self, other):
return self < other or other == self
def __gt__(self, other):
# if no last version, nothing is greater than
if self.first is None:
return False
# enforce Version type
if isinstance(other, str):
other = Version(other)
# otherwise compare to first version
return self.first > other
def __ge__(self, other):
return self > other or other in self
def __str__(self):
first = self.first
if first is None:
first = "up"
last = self.last
if last is None:
last = "latest"
return _translate("{} to {}").format(first, last)
# ideally want localization for error messages
# but don't want to have the lib/ depend on app/, drat
# from psychopy.localization import _translate # ideal
def _translate(string):
"""placeholder (non)function
"""
return string
def getPsychoJSVersionStr(currentVersion, preferredVersion=''):
"""Get the PsychoJS version string for a given PsychoPy version
taking into account:
- the current/requested version
- the fact that early PsychoJS versions did not include minor version
- PsychoJS versions do not use rc1 or dev1 suffixes"""
if preferredVersion == '':
useVerStr = currentVersion
elif preferredVersion == 'latest':
useVerStr = latestVersion()
else:
useVerStr = fullVersion(preferredVersion)
# do we shorten minor versions ('3.4.2' to '3.4')?
# only from 3.2 onwards
if (Version('3.2')) <= Version(useVerStr) < Version('2021') \
and len(useVerStr.split('.')) > 2:
# e.g. 2020.2 not 2021.2.5
useVerStr = '.'.join(useVerStr.split('.')[:2])
elif len(useVerStr.split('.')) > 3:
# e.g. 2021.1.0 not 2021.1.0.dev3
useVerStr = '.'.join(useVerStr.split('.')[:3])
# PsychoJS doesn't have additional rc1 or dev1 releases
for versionSuffix in ["rc", "dev", "post", "a", "b"]:
if versionSuffix in useVerStr:
useVerStr = useVerStr.split(versionSuffix)[0]
return useVerStr
def useVersion(requestedVersion):
"""Manage paths and checkout psychopy libraries for requested versions
of PsychoPy.
requestedVersion :
A string with the requested version of PsychoPy to be used.
Can be major.minor.patch, e.g., '1.83.01', or a partial version,
such as '1.81', or even '1'; uses the most
recent version within that series.
'latest' means the most recent release having a tag on github.
returns:
Returns the current (new) version if it was successfully loaded.
Raises a RuntimeError if git is needed and not present, or if
other PsychoPy modules have already been loaded. Raises a
subprocess CalledProcessError if an invalid git tag/version was
checked out.
Usage (at the top of an experiment script):
from psychopy import useVersion
useVersion('1.80')
from psychopy import visual, event, ...
See also:
ensureMinimal()
"""
requestedVersion = str(requestedVersion)
# Sanity Checks
imported = _psychopyComponentsImported()
if imported:
msg = _translate("Please request a version before importing any "
"PsychoPy modules. (Found: {})")
raise RuntimeError(msg.format(imported))
# make sure PsychoPy and Python versions match
ensurePythonCompatibility(requestedVersion)
# Get a proper full-version tag from a partial tag:
reqdMajorMinorPatch = fullVersion(requestedVersion)
logging.exp('Requested: useVersion({}) = {}'.format(requestedVersion,
reqdMajorMinorPatch))
if not reqdMajorMinorPatch:
msg = _translate('Unknown version `{}`')
raise ValueError(msg.format(requestedVersion))
if not os.path.isdir(VERSIONSDIR):
_clone(requestedVersion) # Allow the versions subdirectory to be built
if psychopy.__version__ != reqdMajorMinorPatch:
# Switching required, so make sure `git` is available.
if not _gitPresent():
msg = _translate("Please install git; needed by useVersion()")
raise RuntimeError(msg)
# Setup Requested Version
_switchToVersion(reqdMajorMinorPatch)
# Reload!
reload(psychopy)
reload(preferences)
reload(constants)
reload(logging)
reload(web)
if _versionTuple(reqdMajorMinorPatch) >= (1, 80):
reload(tools) # because this file is within tools
# TODO check for other submodules that have already been imported
logging.exp('Version now set to: {}'.format(psychopy.__version__))
return psychopy.__version__
def ensurePythonCompatibility(requestedVersion):
"""
Ensure that the requested version of PsychoPy is compatible with the currently running version of Python, raising
an EnvironmentError if not.
Parameters
----------
requestedVersion : str
PsychoPy version being requested (e.g. "2023.2.0")
"""
requestedVersion = Version(requestedVersion)
# get Python version
pyVersion = Version(".".join(
[str(sys.version_info.major), str(sys.version_info.minor)]
))
# get first and last PsychoPy version to support it
firstVersion, lastVersion = versionMap.get(pyVersion, (None, None))
# check supported
_msg = _translate(
"Requested PsychoPy version {requested} does not support installed Python version {py}. The {mode} version "
"of PsychoPy to support {py} was version {key}.\n"
"\n"
"Try either choosing a different version of PsychoPy or installing a different version of Python - some "
"standalone PsychoPy releases include installers for multiple versions."
).format(requested=requestedVersion, py=pyVersion, mode="{mode}", key="{key}")
if firstVersion is not None and firstVersion > requestedVersion:
# if Python version is too new for PsychoPy...
raise EnvironmentError(_msg.format(mode="first", key=firstVersion))
if lastVersion is not None and lastVersion < requestedVersion:
# if PsychoPy version is too new for Python...
raise EnvironmentError(_msg.format(mode="last", key=lastVersion))
def ensureMinimal(requiredVersion):
"""Raise a RuntimeError if the current version < `requiredVersion`.
See also: useVersion()
"""
if _versionTuple(psychopy.__version__) < _versionTuple(requiredVersion):
msg = _translate('Required minimal version `{}` not met ({}).')
raise RuntimeError(msg.format(requiredVersion, psychopy.__version__))
return psychopy.__version__
def _versionTuple(versionStr):
"""Returns a tuple of int's (1, 81, 3) from a string version '1.81.03'
Tuples allow safe version comparisons (unlike strings).
"""
try:
v = (versionStr.strip('.') + '.0.0.0').split('.')[:3]
except (AttributeError, ValueError):
raise ValueError('Bad version string: `{}`'.format(versionStr))
return int(v[0]), int(v[1]), int(v[2])
def _switchToVersion(requestedVersion):
"""Checkout (or clone then checkout) the requested version, set sys.path
so that the new version will be found when import is called. Upon exit,
the checked out version remains checked out, but the sys.path reverts.
NB When installed with pip/easy_install PsychoPy will live in
a site-packages directory, which should *not* be removed as it may
contain other relevant and needed packages.
"""
if not os.path.exists(prefs.paths['userPrefsDir']):
os.mkdir(prefs.paths['userPrefsDir'])
try:
if os.path.exists(VERSIONSDIR):
_checkout(requestedVersion)
else:
_clone(requestedVersion)
except (CalledProcessError, OSError) as e:
if 'did not match any file(s) known to git' in str(e):
msg = _translate("'{}' is not a valid PsychoPy version.")
logging.error(msg.format(requestedVersion))
raise RuntimeError(msg)
else:
raise
# make sure the checked-out version comes first on the python path:
sys.path = [VERSIONSDIR] + sys.path
logging.exp('Prepended `{}` to sys.path'.format(VERSIONSDIR))
def versionOptions(local=True):
"""Available major.minor versions suitable for a drop-down list.
local=True is fast to search (local only);
False is slower and variable duration (queries github)
Returns major.minor versions e.g. 1.83, major e.g., 1., and 'latest'.
To get patch level versions, use availableVersions().
"""
majorMinor = sorted(
list({'.'.join(v.split('.')[:2])
for v in availableVersions(local=local)}),
key=Version,
reverse=True)
major = sorted(list({v.split('.')[0] for v in majorMinor}), key=Version, reverse=True)
special = ['latest']
return special + major + majorMinor
def _localVersions(forceCheck=False):
global _localVersionsCache
if forceCheck or not _localVersionsCache:
if not os.path.isdir(VERSIONSDIR):
return [psychopy.__version__]
else:
cmd = 'git tag'
tagInfo = subprocess.check_output(cmd.split(), cwd=VERSIONSDIR,
env=constants.ENVIRON).decode('UTF-8')
allTags = tagInfo.splitlines()
_localVersionsCache = sorted(allTags, key=Version, reverse=True)
return _localVersionsCache
def _remoteVersions(forceCheck=False):
global _remoteVersionsCache
if forceCheck or not _remoteVersionsCache:
try:
cmd = 'git ls-remote --tags https://github.com/psychopy/versions'
tagInfo = subprocess.check_output(cmd.split(),
env=constants.ENVIRON,
stderr=subprocess.PIPE)
except (CalledProcessError, OSError):
pass
else:
allTags = [line.split('refs/tags/')[1]
for line in tagInfo.decode().splitlines()
if '^{}' not in line]
# ensure most recent (i.e., highest) first
_remoteVersionsCache = sorted(allTags, key=Version, reverse=True)
return _remoteVersionsCache
def _versionFilter(versions, wxVersion):
"""Returns all versions that are compatible with the Python and WX running PsychoPy
Parameters
----------
versions: list
All available (valid) selections for the version to be chosen
Returns
-------
list
All valid selections for the version to be chosen that are compatible with Python version used
"""
# msg = _translate("Filtering versions of PsychoPy only compatible with Python 3.")
# logging.info(msg)
versions = [ver for ver in versions
if ver == 'latest'
or Version(ver) >= Version('1.90')
and len(ver) > 1]
# Get WX Compatibility
compatibleWX = '4.0'
if wxVersion is not None and Version(wxVersion) >= Version(compatibleWX):
# msg = _translate("wx version: {}. Filtering versions of "
# "PsychoPy only compatible with wx >= version {}".format(wxVersion,
# compatibleWX))
# logging.info(msg)
return [ver for ver in versions
if ver == 'latest'
or Version(ver) > Version('1.85.04')
and len(ver) > 1]
return versions
def availableVersions(local=True, forceCheck=False):
"""Return all available (valid) selections for the version to be chosen.
Use local=False to obtain those only available via download
(i.e., not yet local but could be).
Everything returned has the form Major.minor.patchLevel, as strings.
"""
try:
if local:
return _localVersions(forceCheck)
else:
return sorted(
list(set([psychopy.__version__] + _localVersions(forceCheck) + _remoteVersions(
forceCheck))),
key=Version,
reverse=True)
except subprocess.CalledProcessError:
return []
def fullVersion(partial):
"""Expands a special name or a partial tag to the highest patch level
in that series, e.g., '1.81' -> '1.81.03'; '1.' -> '1.83.01'
'latest' -> '1.83.01' (whatever is most recent). Returns '' if no match.
Idea: 'dev' could mean 'upstream master'.
"""
# expects availableVersions() return a reverse-sorted list
if partial in ('', 'latest', None):
return latestVersion()
for tag in availableVersions(local=False):
if tag.startswith(partial):
return tag
return ''
def latestVersion():
"""Returns the most recent version available on github
(or locally if can't access github)
"""
return availableVersions()[0]
def currentTag():
"""Returns the current tag name from the version repository
"""
cmd = 'git describe --always --tag'.split()
tag = subprocess.check_output(cmd, cwd=VERSIONSDIR,
env=constants.ENVIRON).decode('UTF-8').split('-')[0]
return tag
def _checkout(requestedVersion):
"""Look for a Maj.min.patch requested version, download (fetch) if needed.
"""
# Check tag of repo
if currentTag() == requestedVersion:
return requestedVersion
# See if the tag already exists in repos
if requestedVersion not in _localVersions(forceCheck=True):
# Grab new tags
msg = _translate("Couldn't find version {} locally. Trying github...")
logging.info(msg.format(requestedVersion))
out, stdout, stderr = _call_process(f"git fetch github --tags")
# check error code
if out.returncode != 0:
logging.error(stderr)
raise ChildProcessError(
'Error: process exited with code {}, check log for '
'output.'.format(out.returncode))
# is requested here now? forceCheck to refresh cache
if requestedVersion not in _localVersions(forceCheck=True):
msg = _translate("{} is not currently available.")
logging.error(msg.format(requestedVersion))
return ''
# Checkout the requested tag
out, stdout, stderr = _call_process(f"git reset --hard") # in case of any accidental local changes
out, stdout, stderr = _call_process(f"git checkout {requestedVersion}") #
# check error code
if out.returncode != 0:
logging.error(stderr)
raise ChildProcessError(
'Error: process exited with code {}, check log for '
'output.'.format(out.returncode))
logging.exp('Success: ' + ' '.join(f"git checkout {requestedVersion}"))
return requestedVersion
def _clone(requestedVersion):
"""Download (clone) all versions, then checkout the requested version.
"""
assert not os.path.exists(VERSIONSDIR), 'use `git fetch` not `git clone`'
print(_translate('Downloading the PsychoPy Library from Github '
'(may take a while)'))
cmd = ('git clone -o github https://github.com/psychopy/versions ' +
VER_SUBDIR)
print(cmd)
subprocess.check_output(cmd.split(), cwd=USERDIR,
env=constants.ENVIRON).decode('UTF-8')
return _checkout(requestedVersion)
def _gitPresent():
"""Check for git on command-line, return bool.
"""
try:
gitvers = subprocess.check_output('git --version'.split(),
stderr=subprocess.PIPE,
env=constants.ENVIRON).decode('UTF-8')
except (CalledProcessError, OSError):
gitvers = ''
return bool(gitvers.startswith('git version'))
def _psychopyComponentsImported():
return [name for name in globals() if name in psychopy.__all__]
def _call_process(cmd, log=True):
"""Convenience call to open subprocess, and pipe stdout to debug"""
if type(cmd) in [str, bytes]:
cmd = cmd.split()
out = subprocess.Popen(
cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=VERSIONSDIR,
env=constants.ENVIRON)
stdout, stderr = out.communicate()
if log:
logging.debug(stdout)
return out, stdout, stderr
| 21,097
|
Python
|
.py
| 496
| 34.842742
| 117
| 0.647931
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,402
|
imagetools.py
|
psychopy_psychopy/psychopy/tools/imagetools.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).
"""Functions and classes related to image handling"""
try:
from PIL import Image
except ImportError:
import Image
import numpy
from psychopy.tools.typetools import float_uint8
def array2image(a):
"""Takes an array and returns an image object (PIL)."""
# fredrik lundh, october 1998
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
if a.dtype.kind in ['u', 'I', 'B']:
mode = "L"
elif a.dtype.kind in [numpy.float32, 'f']:
mode = "F"
else:
raise ValueError("unsupported image mode")
im = Image.frombytes(mode, (a.shape[1], a.shape[0]), a.tobytes())
return im
def image2array(im):
"""Takes an image object (PIL) and returns a numpy array.
"""
# fredrik lundh, october 1998
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
if im.mode not in ("L", "F"):
raise ValueError("can only convert single-layer images")
imdata = im.tobytes()
if im.mode == "L":
a = numpy.frombuffer(imdata, numpy.uint8)
else:
a = numpy.frombuffer(imdata, numpy.float32)
a.shape = im.size[1], im.size[0]
return a
def makeImageAuto(inarray):
"""Combines float_uint8 and image2array operations ie. scales a numeric
array from -1:1 to 0:255 and converts to PIL image format.
"""
return image2array(float_uint8(inarray))
| 1,625
|
Python
|
.py
| 49
| 28.408163
| 79
| 0.660256
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,403
|
pkgtools.py
|
psychopy_psychopy/psychopy/tools/pkgtools.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).
"""Tools for working with packages within the Python environment.
"""
__all__ = [
'getUserPackagesPath',
'getDistributions',
'addDistribution',
'installPackage',
'uninstallPackage',
'getInstalledPackages',
'getPackageMetadata',
'getPypiInfo',
'isInstalled',
'refreshPackages'
]
import subprocess as sp
from psychopy.preferences import prefs
from psychopy.localization import _translate
import psychopy.logging as logging
import importlib, importlib.metadata, importlib.resources
import sys
import os
import os.path
import requests
import shutil
import site
# On import we want to configure the user site-packages dir and add it to the
# import path.
# set user site-packages dir
if os.environ.get('PSYCHOPYNOPACKAGES', '0') == '1':
site.ENABLE_USER_SITE = True
site.USER_SITE = str(prefs.paths['userPackages'])
site.USER_BASE = None
logging.debug(
'User site-packages dir set to: %s' % site.getusersitepackages())
# add paths from main plugins/packages (installed by plugins manager)
site.addsitedir(prefs.paths['userPackages']) # user site-packages
site.addsitedir(prefs.paths['userInclude']) # user include
site.addsitedir(prefs.paths['packages']) # base package dir
if site.USER_SITE not in sys.path:
site.addsitedir(site.getusersitepackages())
# cache list of packages to speed up checks
_installedPackageCache = []
_installedPackageNamesCache = []
# reference the user packages path
USER_PACKAGES_PATH = str(prefs.paths['userPackages'])
class PluginRequiredError(Exception):
pass
class PluginStub:
"""
Class to handle classes which have moved out to plugins.
Example
-------
```
class NoiseStim(PluginStub, plugin="psychopy-visionscience", doclink="https://psychopy.github.io/psychopy-visionscience/builder/components/NoiseStimComponent/):
```
"""
def __init_subclass__(cls, plugin, doclink="https://plugins.psychopy.org/directory.html"):
"""
Subclassing PluginStub will create documentation pointing to the new documentation for the replacement class.
"""
# store ref to plugin and docs link
cls.plugin = plugin
cls.doclink = doclink
# create doc string point to new location
cls.__doc__ = (
"`{mro}` is now located within the `{plugin}` plugin. You can find the documentation for it `here <{doclink}>`_."
).format(
mro=cls.__module__,
plugin=plugin,
doclink=doclink
)
def __init__(self, *args, **kwargs):
"""
When initialised, rather than creating an object, will log an error.
"""
raise PluginRequiredError((
"Support for `{mro}` is not available this session. Please install "
"`{plugin}` and restart the session to enable support."
).format(
mro=type(self).__module__,
plugin=self.plugin,
))
def refreshPackages():
"""Refresh the packaging system.
This needs to be called after adding and removing packages, or making any
changes to `sys.path`. Functions `installPackages` and `uninstallPackages`
calls this everytime.
"""
global _installedPackageCache
global _installedPackageNamesCache
_installedPackageCache.clear()
_installedPackageNamesCache.clear()
# iterate through installed packages in the user folder
for dist in importlib.metadata.distributions(path=sys.path + [USER_PACKAGES_PATH]):
# get name if in 3.8
if sys.version_info.major == 3:
if sys.version_info.minor <= 9:
distName = dist.metadata['name']
else:
distName = dist.name
else:
raise VersionError(
"PsychoPy only supports Python 3.8 and above. "
"Please upgrade your Python installation.")
# mark as installed
_installedPackageCache.append(
(distName, dist.version)
)
_installedPackageNamesCache.append(
distName
)
def getUserPackagesPath():
"""Get the path to the user's PsychoPy package directory.
This is the directory that plugin and extension packages are installed to
which is added to `sys.path` when `psychopy` is imported.
Returns
-------
str
Path to user's package directory.
"""
return prefs.paths['packages']
def getDistributions():
"""Get a list of active distributions in the current environment.
Returns
-------
list
List of paths where active distributions are located. These paths
refer to locations where packages containing importable modules and
plugins can be found.
"""
logging.error(
"`pkgtools.getDistributions` is now deprecated as packages are detected via "
"`importlib.metadata`, which doesn't need a separate working set from the system path. "
"Please use `sys.path` instead."
)
return sys.path
def addDistribution(distPath):
"""Add a distribution to the current environment.
This function can be used to add a distribution to the present environment
which contains Python packages that have importable modules or plugins.
Parameters
----------
distPath : str
Path to distribution. May be either a path for a directory or archive
file (e.g. ZIP).
"""
logging.error(
"`pkgtools.addDistribution` is now deprecated as packages are detected via "
"`importlib.metadata`, which doesn't need a separate working set from the system path. "
"Please use `sys.path.append` instead."
)
if distPath not in sys.path:
sys.path.append(distPath)
def installPackage(
package,
target=None,
upgrade=False,
forceReinstall=False,
noDeps=False,
awaited=True,
outputCallback=None,
terminateCallback=None,
extra=None,
):
"""Install a package using the default package management system.
This is intended to be used only by PsychoPy itself for installing plugins
and packages through the builtin package manager.
Parameters
----------
package : str
Package name (e.g., `'psychopy-connect'`, `'scipy'`, etc.) with version
if needed. You may also specify URLs to Git repositories and such.
target : str or None
Location to install packages to directly to. If `None`, the user's
package directory is set at the prefix and the package is installed
there. If a `target` is specified, the package top-level directory
must be added to `sys.path` manually.
upgrade : bool
Upgrade the specified package to the newest available version.
forceReinstall : bool
If `True`, the package and all it's dependencies will be reinstalled if
they are present in the current distribution.
noDeps : bool
Don't install dependencies if `True`.
awaited : bool
If False, then use an asynchronous install process - this function will return right away
and the plugin install will happen in a different thread.
outputCallback : function
Function to be called when any output text is received from the process performing the
install. Not used if awaited=True.
terminateCallback : function
Function to be called when installation is finished. Not used if awaited=True.
extra : dict
Extra information to be supplied to the install thread when installing asynchronously.
Not used if awaited=True.
Returns
-------
tuple or psychopy.app.jobs.Job
If `awaited=True`:
`True` if the package installed without errors. If `False`, check
'stderr' for more information. The package may still have installed
correctly, but it doesn't work. Second value contains standard output
and error from the subprocess.
If `awaited=False`:
Returns the job (thread) which is running the install.
"""
# convert extra to dict
if extra is None:
extra = {}
# construct the pip command and execute as a subprocess
cmd = [sys.executable, "-m", "pip", "install", package]
# optional args
if target is None: # default to user packages dir
# check if we are in a virtual environment, if so, dont use --user
if hasattr(sys, 'real_prefix') or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
# we are in a venv
logging.warning(
"You are installing a package inside a virtual environment. "
"The package will be installed in the user site-packages "
"directory."
)
else:
cmd.append('--user')
else:
# check the directory exists before installing
if target is not None and not os.path.exists(target):
raise NotADirectoryError(
'Cannot install package "{}" to "{}", directory does not '
'exist.'.format(package, target))
cmd.append('--target')
cmd.append(target)
if upgrade:
cmd.append('--upgrade')
if forceReinstall:
cmd.append('--force-reinstall')
if noDeps:
cmd.append('--no-deps')
cmd.append('--prefer-binary') # use binary wheels if available
cmd.append('--no-input') # do not prompt, we cannot accept input
cmd.append('--no-color') # no color for console, not supported
cmd.append('--no-warn-conflicts') # silence non-fatal errors
cmd.append('--disable-pip-version-check') # do not check for pip updates
# get the environment for the subprocess
env = os.environ.copy()
# if unawaited, try to get jobs handler
if not awaited:
try:
from psychopy.app import jobs
except ModuleNotFoundError:
logging.warn(_translate(
"Could not install package {} asynchronously as psychopy.app.jobs is not found. "
"Defaulting to synchronous install."
).format(package))
awaited = True
if awaited:
# if synchronous, just use regular command line
proc = sp.Popen(
cmd,
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=False,
universal_newlines=True,
env=env
)
# run
stdout, stderr = proc.communicate()
# print output
sys.stdout.write(stdout)
sys.stderr.write(stderr)
# refresh packages once done
refreshPackages()
return isInstalled(package), {'cmd': cmd, 'stdout': stdout, 'stderr': stderr}
else:
# otherwise, use a job (which can provide live feedback)
proc = jobs.Job(
parent=None,
command=cmd,
inputCallback=outputCallback,
errorCallback=outputCallback,
terminateCallback=terminateCallback,
extra=extra,
)
proc.start(env=env)
return proc
def _getUserPackageTopLevels():
"""Get the top-level directories listed in package metadata installed to
the user's PsychoPy directory.
Returns
-------
dict
Mapping of project names and top-level packages associated with it which
are present in the user's PsychoPy packages directory.
"""
# get all directories
userPackageDir = getUserPackagesPath()
userPackageDirs = os.listdir(userPackageDir)
foundTopLevelDirs = dict()
for foundDir in userPackageDirs:
if not foundDir.endswith('.dist-info'):
continue
topLevelPath = os.path.join(userPackageDir, foundDir, 'top_level.txt')
if not os.path.isfile(topLevelPath):
continue # file not present
with open(topLevelPath, 'r') as tl:
packageTopLevelDirs = []
for line in tl.readlines():
line = line.strip()
pkgDir = os.path.join(userPackageDir, line)
if not os.path.isdir(pkgDir):
continue
packageTopLevelDirs.append(pkgDir)
foundTopLevelDirs[foundDir] = packageTopLevelDirs
return foundTopLevelDirs
def _isUserPackage(package):
"""Determine if the specified package in installed to the user's PsychoPy
package directory.
Parameters
----------
package : str
Project name of the package (e.g. `psychopy-crs`) to check.
Returns
-------
bool
`True` if the package is present in the user's PsychoPy directory.
"""
# get packages in the user path
userPackages = []
for dist in importlib.metadata.distributions(path=[USER_PACKAGES_PATH]):
# substitute name if using 3.8
if sys.version.startswith("3.8"):
distName = dist.metadata['name']
else:
distName = dist.name
# get name
userPackages.append(distName)
return package in userPackages
def _uninstallUserPackage(package):
"""Uninstall packages in PsychoPy package directory.
This function will remove packages from the user's PsychoPy directory since
we can't do so using 'pip', yet. This reads the metadata associated with
the package and attempts to remove the packages.
Parameters
----------
package : str
Project name of the package (e.g. `psychopy-crs`) to uninstall.
Returns
-------
bool
`True` if the package has been uninstalled successfully. Second value
contains standard output and error from the subprocess.
"""
# todo - check if we imported the package and warn that we're uninstalling
# something we're actively using.
# string to use as stdout
stdout = ""
# take note of this function being run as if it was a command
cmd = "python psychopy.tools.pkgtools._uninstallUserPackage(package)"
userPackagePath = getUserPackagesPath()
msg = 'Attempting to uninstall user package `{}` from `{}`.'.format(
package, userPackagePath)
logging.info(msg)
stdout += msg + "\n"
# get distribution object
thisPkg = importlib.metadata.distribution(package)
# iterate through its files
for file in thisPkg.files:
# get absolute path (not relative to package dir)
absPath = thisPkg.locate_file(file)
# skip pycache
if absPath.stem == "__pycache__":
continue
# delete file
if absPath.is_file():
try:
absPath.unlink()
except PermissionError as err:
stdout += _translate(
"Could not remove {absPath}, reason: {err}".format(absPath=absPath, err=err)
)
# skip pycache
if absPath.parent.stem == "__pycache__":
continue
# delete folder if empty
if absPath.parent.is_dir() and not [f for f in absPath.parent.glob("*")]:
# delete file
try:
absPath.parent.unlink()
except PermissionError as err:
stdout += _translate(
"Could not remove {absPath}, reason: {err}".format(absPath=absPath, err=err)
)
# log success
msg = 'Uninstalled package `{}`.'.format(package)
logging.info(msg)
stdout += msg + "\n"
# return the return code and a dict of information from the console
return True, {
"cmd": cmd,
"stdout": stdout,
"stderr": ""
}
def uninstallPackage(package):
"""Uninstall a package from the current distribution.
Parameters
----------
package : str
Package name (e.g., `'psychopy-connect'`, `'scipy'`, etc.) with version
if needed. You may also specify URLs to Git repositories and such.
Returns
-------
tuple
`True` if the package removed without errors. If `False`, check 'stderr'
for more information. The package may still have uninstalled correctly,
but some other issues may have arose during the process.
Notes
-----
* The `--yes` flag is appended to the pip command. No confirmation will be
requested if the package already exists.
"""
if _isUserPackage(package): # delete 'manually' if in package dir
return (_uninstallUserPackage(package),
{"cmd": '', "stdout": '', "stderr": ''})
else: # use the following if in the main package dir
# construct the pip command and execute as a subprocess
cmd = [sys.executable, "-m", "pip", "uninstall", package, "--yes",
'--no-input', '--no-color']
# setup the environment to use the user's site-packages
env = os.environ.copy()
# run command in subprocess
output = sp.Popen(
cmd,
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=False,
env=env,
universal_newlines=True)
stdout, stderr = output.communicate() # blocks until process exits
sys.stdout.write(stdout)
sys.stderr.write(stderr)
# if any error, return code should be False
retcode = bool(stderr)
# Return the return code and a dict of information from the console
return retcode, {"cmd": cmd, "stdout": stdout, "stderr": stderr}
def getInstallState(package):
"""
Get a code indicating the installed state of a given package.
Returns
-------
str
"s": Installed to system environment
"u": Installed to user space
"n": Not installed
str or None
Version number installed, or None if not installed
"""
# If given None, return None
if package is None:
return None, None
if isInstalled(package):
# If installed, get version from metadata
metadata = getPackageMetadata(package)
version = metadata.get('Version', None)
# Determine whether installed to system or user
if _isUserPackage(package):
state = "u"
else:
state = "s"
else:
# If not installed, we know the state and version
state = "n"
version = None
return state, version
def getInstalledPackages():
"""Get a list of installed packages and their versions.
Returns
-------
list
List of installed packages and their versions i.e. `('PsychoPy',
'2021.3.1')`.
"""
# this is like calling `pip freeze` and parsing the output, but faster!
installedPackages = []
for dist in importlib.metadata.distributions(path=[USER_PACKAGES_PATH]):
# substitute name if using 3.8
if sys.version.startswith("3.8"):
distName = dist.metadata['name']
else:
distName = dist.name
# get name and version
installedPackages.append(
(distName, dist.version)
)
return installedPackages
def isInstalled(packageName):
"""Check if a package is presently installed and reachable.
Returns
-------
bool
`True` if the specified package is installed.
"""
# installed packages are given as keys in the resulting dicts
return packageName in _installedPackageNamesCache
def getPackageMetadata(packageName):
"""Get the metadata for a specified package.
Parameters
----------
packageName : str
Project name of package to get metadata from.
Returns
-------
dict or None
Dictionary of metadata fields. If `None` is returned, the package isn't
present in the current distribution.
"""
import email.parser
try:
dist = importlib.metadata.distribution(packageName)
except importlib.metadata.PackageNotFoundError:
return # do nothing
metadict = dict(dist.metadata)
return metadict
def getPypiInfo(packageName, silence=False):
try:
data = requests.get(
f"https://pypi.python.org/pypi/{packageName}/json"
).json()
except (requests.ConnectionError, requests.JSONDecodeError) as err:
import wx
dlg = wx.MessageDialog(None, message=_translate(
"Could not get info for package {}. Reason:\n"
"\n"
"{}"
).format(packageName, err), style=wx.ICON_ERROR)
if not silence:
dlg.ShowModal()
return
if 'info' not in data:
# handle case where the data cannot be retrived
return {
'name': packageName,
'author': 'Unknown',
'authorEmail': 'Unknown',
'license': 'Unknown',
'summary': '',
'desc': 'Failed to get package info from PyPI.',
'releases': [],
}
else:
return {
'name': data['info'].get('Name', packageName),
'author': data['info'].get('author', 'Unknown'),
'authorEmail': data['info'].get('author_email', 'Unknown'),
'license': data['info'].get('license', 'Unknown'),
'summary': data['info'].get('summary', ''),
'desc': data['info'].get('description', ''),
'releases': list(data['releases']),
}
if __name__ == "__main__":
pass
| 21,547
|
Python
|
.py
| 565
| 30.277876
| 164
| 0.637815
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,404
|
typetools.py
|
psychopy_psychopy/psychopy/tools/typetools.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).
"""Functions and classes related to variable type conversion
"""
import numpy
def float_uint8(inarray):
"""Converts arrays, lists, tuples and floats ranging -1:1
into an array of Uint8s ranging 0:255
>>> float_uint8(-1)
0
>>> float_uint8(0)
128
"""
retVal = numpy.around(255 * (0.5 + 0.5 * numpy.asarray(inarray)))
return retVal.astype(numpy.uint8)
def float_uint16(inarray):
"""Converts arrays, lists, tuples and floats ranging -1:1
into an array of Uint16s ranging 0:2^16
>>> float_uint16(-1)
0
>>> float_uint16(0)
32768
"""
i16max = 2**16 - 1
retVal = numpy.around(i16max * (1.0 + numpy.asarray(inarray)) / 2.0)
return retVal.astype(numpy.uint16)
def uint8_float(inarray):
"""Converts arrays, lists, tuples and UINTs ranging 0:255
into an array of floats ranging -1:1
>>> uint8_float(0)
-1.0
>>> uint8_float(128)
0.0
"""
return numpy.asarray(inarray, 'f')/127.5 - 1
| 1,219
|
Python
|
.py
| 38
| 27.868421
| 79
| 0.664953
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,405
|
rifttools.py
|
psychopy_psychopy/psychopy/tools/rifttools.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tools for the use with the :py:class:`~psychopy.visual.rift.Rift` class.
This module exposes additional useful classes and functions from PsychXR without
needing to explicitly import the PsychXR library into your project. If PsychXR
is not available on your system, class objects will be `None`.
Copyright (C) 2019 - Matthew D. Cutone, The Centre for Vision Research, Toronto,
Ontario, Canada
"""
# 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).
__all__ = ['LibOVRPose',
'LibOVRPoseState',
'LibOVRBounds',
'LibOVRHapticsBuffer',
'isHmdConnected',
'isOculusServiceRunning']
_HAS_PSYCHXR_ = True
try:
import psychxr.libovr as libovr
except ImportError:
_HAS_PSYCHXR_ = False
LibOVRPose = libovr.LibOVRPose if _HAS_PSYCHXR_ else None
LibOVRPoseState = libovr.LibOVRPoseState if _HAS_PSYCHXR_ else None
LibOVRBounds = libovr.LibOVRBounds if _HAS_PSYCHXR_ else None
LibOVRHapticsBuffer = libovr.LibOVRHapticsBuffer if _HAS_PSYCHXR_ else None
def isHmdConnected(timeout=0):
"""Check if an HMD is connected.
Parameters
----------
timeout : int
Timeout in milliseconds.
Returns
-------
bool
`True` if an HMD is connected.
"""
if _HAS_PSYCHXR_:
return libovr.isHmdConnected(timeout)
return False
def isOculusServiceRunning(timeout=0):
"""Check if the Oculus(tm) service is currently running.
Parameters
----------
timeout : int
Timeout in milliseconds.
Returns
-------
bool
`True` if the service is loaded and running.
"""
if _HAS_PSYCHXR_:
return libovr.isOculusServiceRunning(timeout)
return False
| 1,885
|
Python
|
.py
| 55
| 29.418182
| 80
| 0.70094
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,406
|
linebreak.py
|
psychopy_psychopy/psychopy/tools/linebreak.py
|
#!/usr/bin/env python
# coding: utf-8
"""
Split string in accordance with UAX#14 Unicode line breaking.
Code is based on uniseg 0.7.1 (https://pypi.org/project/uniseg/)
"""
import sys
import re
import pathlib
__all__ = [
'get_breakable_points',
'break_units',
]
from builtins import ord as _ord
if sys.maxunicode < 0x10000:
# narrow unicode build
def ord(c, index=None):
if isinstance(c, str):
return _ord(c[index or 0])
# if not isinstance(c, unicode):
# raise TypeError('must be unicode, not %s' % type(c).__name__)
i = index or 0
len_s = len(c)-i
if len_s:
value = hi = _ord(c[i])
i += 1
if 0xd800 <= hi < 0xdc00:
if len_s > 1:
lo = _ord(c[i])
i += 1
if 0xdc00 <= lo < 0xe000:
value = (hi-0xd800)*0x400+(lo-0xdc00)+0x10000
if index is not None or i == len_s:
return value
raise TypeError('need a single Unicode code point as parameter')
rx_codepoints = re.compile(r'[\ud800-\udbff][\udc00-\udfff]|.', re.DOTALL)
def code_point(s, index=0):
L = rx_codepoints.findall(s)
return L[index]
def code_points(s):
return rx_codepoints.findall(s)
else:
# wide unicode build
def ord(c, index=None):
return _ord(c if index is None else c[index])
def code_point(s, index=0):
return s[index or 0]
def code_points(s):
return list(s)
def _read_uax14_table():
"""Reads in 'LineBreak.txt' as a dictionary of codes
Reading and parsing the file takes roughly 70ms (macbook pro 2022)
LineBreak.txt comes from from https://www.unicode.org/reports/tr14/"""
# read in the LineBreak spec file for UAX14 (takes ~70ms)
with open(pathlib.Path(__file__).parent / 'LineBreak.txt') as f:
lb_table = {}
for row in f.readlines():
# remove comments
code = row.split('#')[0].strip()
if code: # was it ONLY comments?
# could be range (02E0..02E4;AL) or single (02DF;BB)
chars, this_lb = code.split(';')
if '..' in chars:
# range of vals
start, stop = [int(val, base=16) for val in chars.split('..')]
for charcode in range(start, stop + 1):
lb_table[charcode] = this_lb
else:
# single val
lb_table[int(chars, base=16)] = this_lb
return lb_table
line_break_table = _read_uax14_table()
BK = 'BK' # Mandatory Break
CR = 'CR' # Carriage Return
LF = 'LF' # Line Feed
CM = 'CM' # Combining Mark
NL = 'NL' # Next Line
SG = 'SG' # Surrogate
WJ = 'WJ' # Word Joiner
ZW = 'ZW' # Zero Width Space
GL = 'GL' # Non-breaking ("Glue")
SP = 'SP' # Space
B2 = 'B2' # Break Opportunity Before and After
BA = 'BA' # Break After
BB = 'BB' # Break Before
HY = 'HY' # Hyphen
CB = 'CB' # Contingent Break Opportunity
CL = 'CL' # Close Punctuation
CP = 'CP' # Close Parenthesis
EX = 'EX' # Exclamation/Interrogation
IN = 'IN' # Inseparable
NS = 'NS' # Nonstarter
OP = 'OP' # Open Punctuation
QU = 'QU' # Quotation
IS = 'IS' # Infix Numeric Separator
NU = 'NU' # Numeric
PO = 'PO' # Postfix Numeric
PR = 'PR' # Prefix Numeric
SY = 'SY' # Symbols Allowing Break After
AI = 'AI' # Ambiguous (Alphabetic or Ideographic)
AL = 'AL' # Alphabetic
CJ = 'CJ' # Conditional Japanese Starter
H2 = 'H2' # Hangul LV Syllable
H3 = 'H3' # Hangul LVT Syllable
HL = 'HL' # Hebrew Letter
ID = 'ID' # Ideographic
JL = 'JL' # Hangul L Jamo
JV = 'JV' # Hangul V Jamo
JT = 'JT' # Hangul T Jamo
RI = 'RI' # Regional Indicator
SA = 'SA' # Complex Context Dependent (South East Asian)
XX = 'XX' # Unknown
def line_break(c, index=0):
code = ord(code_point(c, index))
if code in line_break_table:
return line_break_table[code]
return 'Other'
def break_units(s, breakables):
"""
Split a sequence at given breakpoint. This returns a generator object.
So do `list(break_units(s, breakables))` to get the result as a list.
:Parameters:
s:
A string (or sequence) to be split.
breakables:
A sequence of 0/1 of the same length of s. 1 represents that
the input sequence is breakable at that point.
See also get_breakable_points().
"""
i = 0
for j, bk in enumerate(breakables):
if bk:
if j:
yield s[i:j]
i = j
if s:
yield s[i:]
def _preprocess_boundaries(s):
prev_prop = None
i = 0
for c in code_points(s):
prop = line_break(c)
if prop in (BK, CR, LF, SP, NL, ZW):
yield (i, prop)
prev_prop = None
elif prop == CM:
if prev_prop is None:
yield (i, prop)
prev_prop = prop
else:
yield (i, prop)
prev_prop = prop
i += len(c)
def get_breakable_points(s):
"""
Returns a generator object that yields 1 if the next character is
breakable, otherwise yields 0.
Do `list(get_breakable_points(s))` to get a list of breakable points.
:Parameters:
s:
Sentence to be parsed.
"""
if not s:
return
primitive_boundaries = list(_preprocess_boundaries(s))
prev_prev_lb = None
prev_lb = None
for i, (pos, lb) in enumerate(primitive_boundaries):
next_pos, __ = (primitive_boundaries[i+1]
if i<len(primitive_boundaries)-1 else (len(s), None))
if lb == AI:
lb = AL
if lb == CJ:
lb = NS
if lb in (CM, XX, SA):
lb = AL
# LB4
if pos == 0:
do_break = False
elif prev_lb == BK:
do_break = True
# LB5
elif prev_lb in (CR, LF, NL):
do_break = not (prev_lb == CR and lb == LF)
# LB6
elif lb in (BK, CR, LF, NL):
do_break = False
# LB7
elif lb in (SP, ZW):
do_break = False
# LB8
elif ((prev_prev_lb == ZW and prev_lb == SP) or (prev_lb == ZW)):
do_break = True
# LB11
elif lb == WJ or prev_lb == WJ:
do_break = False
# LB12
elif prev_lb == GL:
do_break = False
# LB12a
elif prev_lb not in (SP, BA, HY) and lb == GL:
do_break = False
# LB13
elif lb in (CL, CP, EX, IS, SY):
do_break = False
# LB14
elif (prev_prev_lb == OP and prev_lb == SP) or prev_lb == OP:
do_break = False
# LB15
elif ((prev_prev_lb == QU and prev_lb == SP and lb == OP)
or (prev_lb == QU and lb == OP)):
do_break = False
# LB16
elif ((prev_prev_lb in (CL, CP) and prev_lb == SP and lb == NS)
or (prev_lb in (CL, CP) and lb == NS)):
do_break = False
# LB17
elif ((prev_prev_lb == B2 and prev_lb == SP and lb == B2)
or (prev_lb == B2 and lb == B2)):
do_break = False
# LB18
elif prev_lb == SP:
do_break = True
# LB19
elif lb == QU or prev_lb == QU:
do_break = False
# LB20
elif lb == CB or prev_lb == CB:
do_break = True
# LB21
elif lb in (BA, HY, NS) or prev_lb == BB:
do_break = False
# LB22
elif prev_lb in (AL, HL, ID, IN, NU) and lb == IN:
do_break = False
# LB23
elif ((prev_lb == ID and lb == PO)
or (prev_lb in (AL, HL) and lb == NU)
or (prev_lb == NU and lb in (AL, HL))):
do_break = False
# LB24
elif ((prev_lb == PR and lb == ID)
or (prev_lb == PR and lb in (AL, HL))
or (prev_lb == PO and lb in (AL, HL))):
do_break = False
# LB25
elif ((prev_lb == CL and lb == PO)
or (prev_lb == CP and lb == PO)
or (prev_lb == CL and lb == PR)
or (prev_lb == CP and lb == PR)
or (prev_lb == NU and lb == PO)
or (prev_lb == NU and lb == PR)
or (prev_lb == PO and lb == OP)
or (prev_lb == PO and lb == NU)
or (prev_lb == PR and lb == OP)
or (prev_lb == PR and lb == NU)
or (prev_lb == HY and lb == NU)
or (prev_lb == IS and lb == NU)
or (prev_lb == NU and lb == NU)
or (prev_lb == SY and lb == NU)):
do_break = False
# LB26
elif ((prev_lb == JL and lb in (JL, JV, H2, H3))
or (prev_lb in (JV, H2) and lb in (JV, JT))
or (prev_lb in (JT, H3) and lb == JT)):
do_break = False
# LB27
elif ((prev_lb in (JL, JV, JT, H2, H3) and lb in (IN, PO))
or (prev_lb == PR and lb in (JL, JV, JT, H2, H3))):
do_break = False
# LB28
elif prev_lb in (AL, HL) and lb in (AL, HL):
do_break = False
# LB29
elif prev_lb == IS and lb in (AL, HL):
do_break = False
# LB30
elif ((prev_lb in (AL, HL, NU) and lb == OP)
or (prev_lb == CP and lb in (AL, HL, NU))):
do_break = False
# LB30a
elif prev_lb == lb == RI:
do_break = False
else:
do_break = True
for j in range(next_pos-pos):
yield int(j==0 and do_break)
prev_prev_lb = prev_lb
prev_lb = lb
| 9,888
|
Python
|
.py
| 289
| 25.110727
| 82
| 0.507057
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,407
|
audiotools.py
|
psychopy_psychopy/psychopy/tools/audiotools.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tools for working with audio data.
This module provides routines for saving/loading and manipulating audio samples.
"""
__all__ = [
'array2wav',
'wav2array',
'sinetone',
'squaretone',
'sawtone',
'whiteNoise',
'audioBufferSize',
'sampleRateQualityLevels',
'SAMPLE_RATE_8kHz', 'SAMPLE_RATE_TELCOM_QUALITY',
'SAMPLE_RATE_16kHz', 'SAMPLE_RATE_VOIP_QUALITY', 'SAMPLE_RATE_VOICE_QUALITY',
'SAMPLE_RATE_22p05kHz', 'SAMPLE_RATE_AM_RADIO_QUALITY',
'SAMPLE_RATE_32kHz', 'SAMPLE_RATE_FM_RADIO_QUALITY',
'SAMPLE_RATE_44p1kHz', 'SAMPLE_RATE_CD_QUALITY',
'SAMPLE_RATE_48kHz', 'SAMPLE_RATE_DVD_QUALITY',
'SAMPLE_RATE_96kHz',
'SAMPLE_RATE_192kHz',
'AUDIO_SUPPORTED_CODECS',
'knownNoteNames', 'stepsFromA'
]
# 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 os
import numpy as np
from scipy.io import wavfile
from scipy import signal
# pydub is needed for saving and loading MP3 files among others
# _has_pydub = True
# try:
# import pydub
# except (ImportError, ModuleNotFoundError):
# _has_pydub = False
# note names mapped to steps from A, used in Sound stimulus and Component
stepsFromA = {
'C': -9,
'Csh': -8, 'C#': -8,
'Dfl': -8, 'D♭': -8,
'D': -7,
'Dsh': -6, 'D#': -6,
'Efl': -6, 'E♭': -6,
'E': -5,
'F': -4,
'Fsh': -3, 'F#': -3,
'Gfl': -3, 'G♭': -3,
'G': -2,
'Gsh': -1, 'G#': -1,
'Afl': -1, 'A♭': -1,
'A': +0,
'Ash': +1, 'A#': +1,
'Bfl': +1, 'B♭': +1,
'B': +2,
'Bsh': +2, 'B#': +2}
knownNoteNames = sorted(stepsFromA.keys())
# Constants for common sample rates. Some are aliased to give the programmer an
# idea to the quality they would expect from each. It is recommended to only use
# these values since most hardware supports them for recording and playback.
#
SAMPLE_RATE_8kHz = SAMPLE_RATE_TELCOM_QUALITY = 8000
SAMPLE_RATE_16kHz = SAMPLE_RATE_VOIP_QUALITY = SAMPLE_RATE_VOICE_QUALITY = 16000
SAMPLE_RATE_22p05kHz = SAMPLE_RATE_AM_RADIO_QUALITY = 22050
SAMPLE_RATE_32kHz = SAMPLE_RATE_FM_RADIO_QUALITY = 32000 # wireless headphones
SAMPLE_RATE_44p1kHz = SAMPLE_RATE_CD_QUALITY = 44100
SAMPLE_RATE_48kHz = SAMPLE_RATE_DVD_QUALITY = 48000
SAMPLE_RATE_96kHz = 96000
SAMPLE_RATE_192kHz = 192000 # high-def
# needed for converting float to int16, not exported by __all__
MAX_16BITS_SIGNED = 1 << 15
# Quality levels as strings and values. Used internally by the PsychoPy UI for
# dropdowns and preferences. Persons using PsychoPy as a library would typically
# use constants `SAMPLE_RATE_*` instead of looking up values in here.
#
# For voice recording applications, the recommended sample rate is `Voice`
# (16kHz) and should appear as the default option in preferences and UI
# dropdowns.
#
sampleRateQualityLevels = {
0: (SAMPLE_RATE_8kHz, 'Telephone/Two-way radio (8kHz)'),
1: (SAMPLE_RATE_16kHz, 'Voice (16kHz)'), # <<< recommended for voice
2: (SAMPLE_RATE_44p1kHz, 'CD Audio (44.1kHz)'),
3: (SAMPLE_RATE_48kHz, 'DVD Audio (48kHz)'), # <<< usually system default
4: (SAMPLE_RATE_96kHz, 'High-Def (96kHz)'),
5: (SAMPLE_RATE_192kHz, 'Ultra High-Def (192kHz)')
}
# supported formats for loading and saving audio samples to file
try:
import soundfile as sf
AUDIO_SUPPORTED_CODECS = [s.lower() for s in sf.available_formats().keys()]
except ImportError:
AUDIO_SUPPORTED_CODECS = []
def array2wav(filename, samples, freq=48000):
"""Write audio samples stored in an array to WAV file.
Parameters
----------
filename : str
File name for the output.
samples : ArrayLike
Nx1 or Nx2 array of audio samples with values ranging between -1 and 1.
freq : int or float
Sampling frequency used to capture the audio samples in Hertz (Hz).
Default is 48kHz (specified as `48000`) which is considered DVD quality
audio.
"""
# rescale
clipData = np.asarray(samples * (MAX_16BITS_SIGNED - 1), dtype=np.int16)
# write out file
wavfile.write(filename, freq, clipData)
def wav2array(filename, normalize=True):
"""Read a WAV file and write samples to an array.
Parameters
----------
filename : str
File name for WAV file to read.
normalize : bool
Convert samples to floating point format with values ranging between
-1 and 1. If `False`, values will be kept in `int16` format. Default is
`True` since normalized floating-point is the typical format for audio
samples in PsychoPy.
Returns
-------
samples : ArrayLike
Nx1 or Nx2 array of samples.
freq : int
Sampling frequency for playback specified by the audio file.
"""
fullpath = os.path.abspath(filename) # get the full path
if not os.path.isfile(fullpath): # check if the file exists
raise FileNotFoundError(
"Cannot find WAV file `{}` to open.".format(filename))
# read the file
freq, samples = wavfile.read(filename, mmap=False)
# transpose samples
samples = samples[:, np.newaxis]
# check if we need to normalize things
if normalize:
samples = np.asarray(
samples / (MAX_16BITS_SIGNED - 1), dtype=np.float32)
return samples, int(freq)
def sinetone(duration, freqHz, gain=0.8, sampleRateHz=SAMPLE_RATE_48kHz):
"""Generate audio samples for a tone with a sine waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
gain : float
Gain factor ranging between 0.0 and 1.0.
sampleRateHz : int
Samples rate of the audio for playback.
Returns
-------
ndarray
Nx1 array containing samples for the tone (single channel).
"""
assert 0.0 <= gain <= 1.0 # check if gain range is valid
nsamp = sampleRateHz * duration
samples = np.arange(nsamp, dtype=np.float32)
samples[:] = 2 * np.pi * samples[:] * freqHz / sampleRateHz
samples[:] = np.sin(samples)
if gain != 1.0:
samples *= gain
return samples.reshape(-1, 1)
def squaretone(duration, freqHz, dutyCycle=0.5, gain=0.8,
sampleRateHz=SAMPLE_RATE_48kHz):
"""Generate audio samples for a tone with a square waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
dutyCycle : float
Duty cycle between 0.0 and 1.0.
gain : float
Gain factor ranging between 0.0 and 1.0.
sampleRateHz : int
Samples rate of the audio for playback.
Returns
-------
ndarray
Nx1 array containing samples for the tone (single channel).
"""
assert 0.0 <= gain <= 1.0 # check if gain range is valid
nsamp = sampleRateHz * duration
samples = np.arange(nsamp, dtype=np.float32)
samples[:] = 2 * np.pi * samples[:] * freqHz / sampleRateHz
samples[:] = signal.square(samples, duty=dutyCycle)
if gain != 1.0:
samples *= gain
return samples.reshape(-1, 1)
def sawtone(duration, freqHz, peak=0.5, gain=0.8,
sampleRateHz=SAMPLE_RATE_48kHz):
"""Generate audio samples for a tone with a sawtooth waveform.
Parameters
----------
duration : float or int
Length of the sound in seconds.
freqHz : float or int
Frequency of the tone in Hertz (Hz). Note that this differs from the
`sampleRateHz`.
peak : float
Location of the peak between 0.0 and 1.0. If the peak is at 0.5, the
resulting wave will be triangular. A value of 1.0 will cause the peak to
be located at the very end of a cycle.
gain : float
Gain factor ranging between 0.0 and 1.0.
sampleRateHz : int
Samples rate of the audio for playback.
Returns
-------
ndarray
Nx1 array containing samples for the tone (single channel).
"""
assert 0.0 <= gain <= 1.0 # check if gain range is valid
nsamp = sampleRateHz * duration
samples = np.arange(nsamp, dtype=np.float32)
samples[:] = 2 * np.pi * samples[:] * freqHz / sampleRateHz
samples[:] = signal.sawtooth(samples, width=peak)
if gain != 1.0:
samples *= gain
return samples.reshape(-1, 1)
def whiteNoise(duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz):
"""Generate gaussian white noise.
Parameters
----------
duration : float or int
Length of the sound in seconds.
sampleRateHz : int
Samples rate of the audio for playback.
Returns
-------
ndarray
Nx1 array containing samples for the sound.
"""
samples = np.random.randn(int(duration * sampleRateHz)).reshape(-1, 1)
# clip range
samples = samples.clip(-1, 1)
return samples
def audioBufferSize(duration=1.0, freq=SAMPLE_RATE_48kHz):
"""Estimate the memory footprint of an audio clip of given duration. Assumes
that data is stored in 32-bit floating point format.
This can be used to determine how large of a buffer is needed to store
enough samples for `durations` seconds of audio using the specified
frequency (`freq`).
Parameters
----------
duration : float
Length of the clip in seconds.
freq : int
Sampling frequency in Hz.
Returns
-------
int
Estimated number of bytes.
"""
# Right now we are just computing for single precision floats, we can expand
# this to other types in the future.
sizef32 = 32 # duh
return int(duration * freq * sizef32)
def audioMaxDuration(bufferSize=1536000, freq=SAMPLE_RATE_48kHz):
"""
Work out the max duration of audio able to be recorded given the buffer size (kb) and frequency (Hz).
Parameters
----------
bufferSize : int, float
Size of the buffer in bytes
freq : int
Sampling frequency in Hz.
Returns
-------
float
Estimated max duration
"""
sizef32 = 32 # duh
return bufferSize / (sizef32 * freq)
if __name__ == "__main__":
pass
| 10,452
|
Python
|
.py
| 285
| 31.4
| 105
| 0.661146
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,408
|
arraytools.py
|
psychopy_psychopy/psychopy/tools/arraytools.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).
"""Functions and classes related to array handling
"""
__all__ = ["createXYs",
"extendArr",
"makeRadialMatrix",
"ratioRange",
"shuffleArray",
"val2array",
"array2pointer",
"createLumPattern"]
import numpy
import ctypes
class IndexDict(dict):
"""
A dict which allows for keys to be accessed by index as well as by key. Can be initialised
from a dict, or from a set of keyword arguments.
Example
-------
```
data = IndexDict({
'someKey': "abc",
'someOtherKey': "def",
'anotherOne': "ghi",
1: "jkl",
})
# using a numeric index will return the value for the key at that position
print(data[0]) # prints: abc
# ...unless that number is already a key
print(data[1]) # prints: jkl
```
"""
def __init__(self, arr=None, **kwargs):
# initialise dict
dict.__init__(self)
# if given no dict, use a blank one
if arr is None:
arr = {}
# if given a dict, update kwargs with it
kwargs.update(arr)
# set every key
for key, value in kwargs.items():
dict.__setitem__(self, key, value)
def __getitem__(self, key):
# if key is a valid numeric index not present as a normal key, get matching key
if isinstance(key, int) and key < len(self) and key not in self:
return list(self.values())[key]
# index like normal
return dict.__getitem__(self, key)
def __setitem__(self, key, value):
# if key is a valid numeric index not present as a normal key, get matching key
if isinstance(key, int) and key < len(self) and key not in self:
key = list(self.keys())[key]
# set like normal
return dict.__setitem__(self, key, value)
def createXYs(x, y=None):
"""Create an Nx2 array of XY values including all combinations of the
x and y values provided.
>>> createXYs(x=[1, 2, 3], y=[4, 5, 6])
array([[1, 4],
[2, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
[2, 6],
[3, 6]])
>>> createXYs(x=[1, 2, 3]) # assumes y == x
array([[1, 1],
[2, 1],
[3, 1],
[1, 2],
[2, 2],
[3, 2],
[1, 3],
[2, 3],
[3, 3]])
"""
if y is None:
y = x
xs = numpy.resize(x, len(x) * len(y)) # [1,2,3, 1,2,3, 1,2,3]
ys = numpy.repeat(y, len(x)) # [1,1,1 ,2,2,2, 3,3,3]
return numpy.vstack([xs, ys]).transpose()
def extendArr(inArray, newSize):
"""Takes a numpy array and returns it padded with zeros
to the necessary size
>>> extendArr([1, 2, 3], 5)
array([1, 2, 3, 0, 0])
"""
if type(inArray) in [tuple, list]:
inArray = numpy.asarray(inArray)
newArr = numpy.zeros(newSize, inArray.dtype)
# create a string to eval (see comment below)
indString = ''
for thisDim in inArray.shape:
indString += '0:' + str(thisDim) + ','
indString = indString[0:-1] # remove the final comma
# e.g.
# newArr[0:4, 0:3] = inArray
exec("newArr[" + indString + "] = inArray")
return newArr
def makeRadialMatrix(matrixSize, center=(0.0, 0.0), radius=1.0):
"""DEPRECATED: please use psychopy.filters.makeRadialMatrix instead
"""
from psychopy.visual import filters
return filters.makeRadialMatrix(matrixSize, center, radius)
def ratioRange(start, nSteps=None, stop=None,
stepRatio=None, stepdB=None, stepLogUnits=None):
"""Creates a array where each step is a constant ratio
rather than a constant addition.
Specify *start* and any 2 of, *nSteps*, *stop*, *stepRatio*,
*stepdB*, *stepLogUnits*
>>> ratioRange(1,nSteps=4,stop=8)
array([ 1., 2., 4., 8.])
>>> ratioRange(1,nSteps=4,stepRatio=2)
array([ 1., 2., 4., 8.])
>>> ratioRange(1,stop=8,stepRatio=2)
array([ 1., 2., 4., 8.])
"""
badRange = "Can't calculate ratio ranges on negatives or zero"
if start <= 0:
raise RuntimeError(badRange)
if stepdB is not None:
stepRatio = 10.0 ** (stepdB / 20.0) # dB = 20*log10(ratio)
if stepLogUnits is not None:
stepRatio = 10.0 ** stepLogUnits # logUnit = log10(ratio)
if stepRatio is not None and nSteps is not None:
factors = stepRatio ** numpy.arange(nSteps, dtype='d')
output = start * factors
elif nSteps is not None and stop is not None:
if stop <= 0:
raise RuntimeError(badRange)
lgStart = numpy.log10(start)
lgStop = numpy.log10(stop)
lgStep = (lgStop - lgStart) / (nSteps - 1)
lgArray = numpy.arange(lgStart, lgStop + lgStep, lgStep)
# if the above is a badly rounded float it may have one extra entry
if len(lgArray) > nSteps:
lgArray = lgArray[:-1]
output = 10 ** lgArray
elif stepRatio is not None and stop is not None:
thisVal = float(start)
outList = []
while thisVal < stop:
outList.append(thisVal)
thisVal *= stepRatio
output = numpy.asarray(outList)
else:
# if any of the conditions above are not satisfied, throw this error.
raise ValueError('Invalid input parameters.')
return output
def shuffleArray(inArray, shuffleAxis=-1, seed=None):
"""DEPRECATED: use `numpy.random.shuffle`
"""
# arrAsList = shuffle(list(inArray))
# return numpy.array(arrAsList)
rng = numpy.random.default_rng(seed=seed)
inArray = numpy.array(inArray, 'O') # convert to array if necess
# create a random array of the same shape
rndArray = rng.random(inArray.shape)
# and get the arguments that would sort it
newIndices = numpy.argsort(rndArray, shuffleAxis)
# return the array with the sorted random indices
return numpy.take(inArray, newIndices)
def val2array(value, withNone=True, withScalar=True, length=2):
"""Helper function: converts different input to a numpy array.
Raises informative error messages if input is invalid.
withNone: True/False. should 'None' be passed?
withScalar: True/False. is a scalar an accepted input?
Will be converted to array of this scalar
length: False / 2 / 3. Number of elements input should have or be
converted to. Might be False (do not accept arrays or convert to such)
"""
if value is None:
if withNone:
return None
else:
raise ValueError('Invalid parameter. None is not accepted as '
'value.')
value = numpy.array(value, float)
if numpy.product(value.shape) == 1:
if withScalar:
# e.g. 5 becomes array([5.0, 5.0, 5.0]) for length=3
return numpy.repeat(value, length)
else:
msg = ('Invalid parameter. Single numbers are not accepted. '
'Should be tuple/list/array of length %s')
raise ValueError(msg % str(length))
elif value.shape[-1] == length:
return numpy.array(value, float)
else:
msg = 'Invalid parameter. Should be length %s but got length %s.'
raise ValueError(msg % (str(length), str(len(value))))
def array2pointer(arr, dtype=None):
"""Convert a Numpy array to a `ctypes` pointer.
Arrays are checked if they are contiguous before conversion, if not, they
will be converted to contiguous arrays.
Parameters
----------
arr : ndarray
N-dimensions array to convert, should be contiguous (C-ordered).
dtype : str or dtype, optional
Data type for the array pointer. If the data type of the array does not
match `dtype`, it will be converted to `dtype` prior to using it. If
`None` is specified, the data type for the pointer will be implied from
the input array type.
Returns
-------
ctypes.POINTER
Pointer to the first value of the array.
"""
dtype = arr.dtype if dtype is None else numpy.dtype(dtype).type
# convert to ctypes, also we ensure the array is contiguous
return numpy.ascontiguousarray(arr, dtype=dtype).ctypes.data_as(
ctypes.POINTER(numpy.ctypeslib.as_ctypes_type(dtype)))
def snapto(values, points):
"""
Snap values in array x to their closest equivalent in an array of target values, returning an array of the closest value in `points` to each value in `x`.
Parameters
----------
values : list, tuple or numpy.ndarray
Array of values to be snapped to `points`
points : list, tuple or numpy.ndarray
Array of values to be snapped to
Returns
-------
snapped
Array of values, each corresponds to a value in `x` and is the closest value in `points`.
Examples
--------
Snap labels on a Slider to the x positions of each tick::
labelPositions = [-1, -2/3, -1/3, 1/3, 2/3, 1]
tickPositions = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1]
snappedLabelPositions = snapto(x=labelPositions, points=tickPositions)
assert snappedLabelPositions = [-1, -0.6, -0.4, 0.4, 0.6, 1]
"""
# Force values to 1d numpy arrays, though keep track of original shape of x
ogShape = numpy.asarray(values).shape
values = numpy.asarray(values).reshape((1, -1))
points = numpy.asarray(points).reshape((1, -1))
# Get sort order of values and points
valuesi = numpy.argsort(values[0])
pointsi = numpy.argsort(points[0])
# Shift values indices to sit evenly within points indices
valuesi -= min(pointsi)
valuesi = valuesi / max(valuesi) * max(pointsi)
valuesi = valuesi.round().astype(int)
# Get indices of points corresponding to each x value
i = pointsi[valuesi]
# Get corresponding points
snapped1d = points[0, i]
# Reshape to original shape of x
snapped = snapped1d.reshape(ogShape)
return snapped
def createLumPattern(patternType, res, texParams=None, maskParams=None):
"""Create a luminance (single channel) defined pattern.
Parameters
----------
patternType : str or None
Pattern to generate. Value may be one of: 'sin', 'sqr', 'saw', 'tri',
'sinXsin', 'sqrXsqr', 'circle', 'gauss', 'cross', 'radRamp' or
'raisedCos'. If `None`, 'none', 'None' or 'color' are specified, an
array of ones will be returned with `size==(res, res)`.
res : int
Resolution for the texture in texels.
texParams : dict or None
Additional parameters to control texture generation. Not currently used
but may in the future. These can be settings like duty-cycle, etc.
Passing valid values to this parameter do nothing yet.
maskParams : dict or None
Additional parameters to control how the texture's mask is applied.
Returns
-------
ndarray
Array of normalized intensity values containing the desired pattern
specified by `mode`.
Examples
--------
Create a gaussian bump luminance map with resolution 1024x1024 and standard
deviation of 0.5::
res = 1024
maskParams = {'sd': 0.5}
intensity = createLumPattern('gauss', res, None, maskParams)
"""
# This code was originally in `TextureMixin._createTexture`, but moved here
# to clean up that class and to provide a reusable way of generating these
# textures.
# Check and sanitize parameters passed to this function before generating
# anything with them.
if res <= 0:
raise ValueError('invalid value for parameter `res`, must be >0')
# parameters to control texture generation, unused but roughed in for now
allTexParams = {}
if isinstance(texParams, dict): # specified, override defaults if so
allTexParams.update(texParams)
elif texParams is None: # if not specified, use empty dict
pass # nop for now, change to `allTexParams = {}` when needed
else:
raise TypeError('parameter `texParams` must be type `dict` or `None`')
# mask parameters for additional parameters to control how maks are applied
allMaskParams = {'fringeWidth': 0.2, 'sd': 3}
if isinstance(maskParams, dict): # specified, override defaults if so
allMaskParams.update(maskParams)
elif maskParams is None: # if not specified, use empty dict
allMaskParams = {}
else:
raise TypeError('parameter `maskParams` must be type `dict` or `None`')
# correct `makeRadialMatrix` from filters, duplicated her to avoid importing
# all of visual to test this function out
def _makeRadialMatrix(matrixSize, center=(0.0, 0.0), radius=1.0):
if type(radius) in [int, float]:
radius = [radius, radius]
# NB need to add one step length because
yy, xx = numpy.mgrid[0:matrixSize, 0:matrixSize]
xx = ((1.0 - 2.0 / matrixSize * xx) + center[0]) / radius[0]
yy = ((1.0 - 2.0 / matrixSize * yy) + center[1]) / radius[1]
rad = numpy.sqrt(numpy.power(xx, 2) + numpy.power(yy, 2))
return rad
# here is where we generate textures
pi = numpy.pi
if patternType in (None, "none", "None", "color"):
res = 1
intensity = numpy.ones([res, res], numpy.float32)
elif patternType == "sin":
# NB 1j*res is a special mgrid notation
onePeriodX, onePeriodY = numpy.mgrid[0:res, 0:2 * pi:1j * res]
intensity = numpy.sin(onePeriodY - pi / 2)
elif patternType == "sqr": # square wave (symmetric duty cycle)
# NB 1j*res is a special mgrid notation
onePeriodX, onePeriodY = numpy.mgrid[0:res, 0:2 * pi:1j * res]
sinusoid = numpy.sin(onePeriodY - pi / 2)
intensity = numpy.where(sinusoid > 0, 1, -1)
elif patternType == "saw":
intensity = \
numpy.linspace(-1.0, 1.0, res, endpoint=True) * numpy.ones([res, 1])
elif patternType == "tri":
# -1:3 means the middle is at +1
intens = numpy.linspace(-1.0, 3.0, res, endpoint=True)
# remove from 3 to get back down to -1
intens[res // 2 + 1:] = 2.0 - intens[res // 2 + 1:]
intensity = intens * numpy.ones([res, 1]) # make 2D
elif patternType == "sinXsin":
# NB 1j*res is a special mgrid notation
onePeriodX, onePeriodY = numpy.mgrid[0:2 * pi:1j * res,
0:2 * pi:1j * res]
intensity = \
numpy.sin(onePeriodX - pi / 2) * numpy.sin(onePeriodY - pi / 2)
elif patternType == "sqrXsqr":
# NB 1j*res is a special mgrid notation
onePeriodX, onePeriodY = numpy.mgrid[0:2 * pi:1j * res,
0:2 * pi:1j * res]
sinusoid = \
numpy.sin(onePeriodX - pi / 2) * numpy.sin(onePeriodY - pi / 2)
intensity = numpy.where(sinusoid > 0, 1, -1)
elif patternType == "circle":
rad = _makeRadialMatrix(res)
intensity = (rad <= 1) * 2 - 1
elif patternType == "gauss":
rad = _makeRadialMatrix(res)
# 3sd.s by the edge of the stimulus
try:
maskStdev = allMaskParams['sd']
except KeyError:
raise ValueError(
"Mask parameter 'sd' not provided but is required by "
"`mode='gauss'`")
invVar = (1.0 / maskStdev) ** 2.0
intensity = numpy.exp(-rad ** 2.0 / (2.0 * invVar)) * 2 - 1
elif patternType == "cross":
X, Y = numpy.mgrid[-1:1:1j * res, -1:1:1j * res]
tfNegCross = (((X < -0.2) & (Y < -0.2)) |
((X < -0.2) & (Y > 0.2)) |
((X > 0.2) & (Y < -0.2)) |
((X > 0.2) & (Y > 0.2)))
# tfNegCross == True at places where the cross is transparent,
# i.e. the four corners
intensity = numpy.where(tfNegCross, -1, 1)
elif patternType == "radRamp": # a radial ramp
rad = _makeRadialMatrix(res)
intensity = 1 - 2 * rad
# clip off the corners (circular)
intensity = numpy.where(rad < -1, intensity, -1)
elif patternType == "raisedCos": # A raised cosine
hammingLen = 1000 # affects the 'granularity' of the raised cos
rad = _makeRadialMatrix(res)
intensity = numpy.zeros_like(rad)
intensity[numpy.where(rad < 1)] = 1
maskFringeWidth = allMaskParams['fringeWidth']
raisedCosIdx = numpy.where(
[numpy.logical_and(rad <= 1, rad >= 1 - maskFringeWidth)])[1:]
# Make a raised_cos (half a hamming window):
raisedCos = numpy.hamming(hammingLen)[:hammingLen // 2]
raisedCos -= numpy.min(raisedCos)
raisedCos /= numpy.max(raisedCos)
# Measure the distance from the edge - this is your index into the
# hamming window:
dFromEdge = numpy.abs(
(1 - maskFringeWidth) - rad[raisedCosIdx])
dFromEdge /= numpy.max(dFromEdge)
dFromEdge *= numpy.round(hammingLen / 2)
# This is the indices into the hamming (larger for small distances
# from the edge!):
portionIdx = (-1 * dFromEdge).astype(int)
# Apply the raised cos to this portion:
intensity[raisedCosIdx] = raisedCos[portionIdx]
# Scale it into the interval -1:1:
intensity = intensity - 0.5
intensity /= numpy.max(intensity)
# Sometimes there are some remaining artifacts from this process,
# get rid of them:
artifactIdx = numpy.where(
numpy.logical_and(intensity == -1, rad < 0.99))
intensity[artifactIdx] = 1
artifactIdx = numpy.where(
numpy.logical_and(intensity == 1, rad > 0.99))
intensity[artifactIdx] = 0
else:
raise ValueError("invalid keyword or value for parameter `patternType`")
return intensity
class AliasDict(dict):
"""
Similar to a dict, but with the option to alias certain keys such that they always have the same value.
"""
def __getitem__(self, k):
# if key is aliased, use its alias
if k in self.aliases:
k = self.aliases[k]
# get as normal
return dict.__getitem__(self, k)
def __setitem__(self, k, v):
# if key is aliased, set its alias
if k in self.aliases:
k = self.aliases[k]
# set as normal
return dict.__setitem__(self, k, v)
set = __setitem__
def __contains__(self, item):
# return True to "in" queries if item is in aliases
return dict.__contains__(self, item) or item in self.aliases
@property
def aliases(self):
"""
Dict mapping name aliases to the key they are an alias for
"""
# if not set yet, set as blank dict
if not hasattr(self, "_aliases"):
self._aliases = {}
return self._aliases
@aliases.setter
def aliases(self, value: dict):
self._aliases = value
def alias(self, key, alias):
"""
Add an alias for a key in this dict. Setting/getting one key will set/get the other.
Parameters
----------
key : str
Key to alias
alias : str
Name to alias key with
"""
# assign alias
self.aliases[alias] = key
if __name__ == "__main__":
pass
| 19,609
|
Python
|
.py
| 470
| 33.938298
| 158
| 0.610399
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,409
|
unittools.py
|
psychopy_psychopy/psychopy/tools/unittools.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).
"""Functions and classes related to unit conversion"""
# This module is not used by psychopy; retained for backwards compatibility
# for user-scripts.
# pylint: disable=W0611
# W0611 = Unused import %s
from numpy import radians, degrees
| 470
|
Python
|
.py
| 11
| 41.272727
| 79
| 0.764317
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,410
|
attributetools.py
|
psychopy_psychopy/psychopy/tools/attributetools.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).
"""Functions and classes related to attribute handling
"""
import numpy
import inspect
from psychopy import logging
from functools import partialmethod
from psychopy.tools.stringtools import CaseSwitcher
class attributeSetter:
"""Makes functions appear as attributes. Takes care of autologging.
"""
def __init__(self, func, doc=None):
self.func = func
if doc is not None:
self.__doc__ = doc
else:
self.__doc__ = func.__doc__
def __set__(self, obj, value):
newValue = self.func(obj, value)
# log=None defaults to obj.autoLog:
logAttrib(obj, log=None, attrib=self.func.__name__,
value=value)
# Useful for inspection/debugging. Keeps track of all settings of
# attributes.
'''
import traceback
origin = traceback.extract_stack()[-2]
# print('%s.%s = %s (line %i)' %(obj.__class__.__name__,
# self.func.__name__, value.__repr__(), origin[1])) # short
# print('%s.%s = %s (%s in %s, line %i' %(obj.__class__.__name__,
# self.func.__name__, value.__repr__(),
# origin[1], origin[0].split('/')[-1],
# origin[1], origin[3].__repr__()))) # long
'''
return newValue
def serialize(self):
"""
If an attributeSetter is received by serializer as an attribute, return the default value or
None
"""
defaults = inspect.getargspec(self.func).defaults
if defaults:
return defaults[0]
else:
return None
def __repr__(self):
return repr(self.__getattribute__)
def setAttribute(self, attrib, value, log=None,
operation=False, stealth=False):
"""This function is useful to direct the old set* functions to the
@attributeSetter.
It has the same functionality but supports logging control as well, making
it useful for cross-@attributeSetter calls as well with log=False.
Typical usage: e.g. in setSize(self, value, operation, log=None) do::
def setSize(self, value, operation, log=None):
# call attributeSetter:
setAttribute(self, 'size', value, log, operation)
Sets an object property (scalar or numpy array), optionally with
an operation given in a string. If operation is None or '', value
is multiplied with old to keep shape.
If `stealth` is True, then use self.__dict[key] = value and avoid
calling attributeSetters. If `stealth` is False, use `setattr()`.
`autoLog` controls the value of autoLog during this `setattr()`.
History: introduced in version 1.79 to avoid exec-calls.
Even though it looks complex, it is very fast :-)
"""
# if log is None, use autoLog
if log is None:
log = getattr(self, "autoLog", False)
# Change the value of "value" if there is an operation. Even if it is '',
# which indicates that this value could potentially be subjected to an
# operation.
if operation is not False:
try:
oldValue = getattr(self, attrib)
except AttributeError:
# attribute is not set yet. Set it to None to skip
# operation and just set value.
oldValue = None
# Apply operation except for the case when new or old value
# are None or string-like
if (value is not None and type(value)!=str
and oldValue is not None and type(oldValue)!=str):
value = numpy.array(value, float)
# Calculate new value using operation
if operation in ('', None):
if (value.shape == () and
not isinstance(oldValue, attributeSetter)): # scalar
# Preserves dimensions in case oldValue is array-like.
value = oldValue * 0 + value
elif operation == '+':
value = oldValue + value
elif operation == '*':
value = oldValue * value
elif operation == '-':
value = oldValue - value
elif operation == '/':
value = oldValue / value
elif operation == '**':
value = oldValue ** value
elif operation == '%':
value = oldValue % value
else:
msg = ('Unsupported value "%s" for operation when '
'setting %s in %s')
vals = (operation, attrib, self.__class__.__name__)
raise ValueError(msg % vals)
elif operation not in ('', None):
msg = ('operation %s invalid for %s (old value) and %s '
'(operation value)')
vals = (operation.__repr__(), oldValue, value)
raise TypeError(msg % vals)
# Ok, operation or not, change the attribute in self without callback to
# attributeSetters
if stealth:
self.__dict__[attrib] = value # without logging as well
else:
# Trick to control logging of attributeSetter. Set logging in
# self.autoLog
autoLogOrig = self.autoLog # save original value
# set to desired logging. log=None defaults to autoLog
self.__dict__['autoLog'] = log or autoLogOrig and log is None
# set attribute, calling attributeSetter if it exists
setattr(self, attrib, value)
# hack: if attrib was 'autoLog', do not set it back to original value!
if attrib != 'autoLog':
# return autoLog to original
self.__dict__['autoLog'] = autoLogOrig
def logAttrib(obj, log, attrib, value=None):
"""Logs a change of a visual attribute on the next window.flip.
If value=None, it will take the value of self.attrib.
"""
# Default to autoLog if log isn't set explicitly
if log or log is None and obj.autoLog == True:
if value is None:
value = getattr(obj, attrib)
# for numpy arrays bigger than 2x2 repr is slow (up to 1ms) so just
# say it was an array
if isinstance(value, numpy.ndarray) and (value.ndim > 2 or value.size > 2):
valStr = repr(type(value))
else:
valStr = value.__repr__()
message = "%s: %s = %s" % (obj.name, attrib, valStr)
try:
obj.win.logOnFlip(message, level=logging.EXP, obj=obj)
except AttributeError:
# the "win" attribute only exists if sync-to-visual (e.g. stimuli)
logging.log(message, level=logging.EXP, obj=obj)
class AttributeGetSetMixin:
"""
For all attributeSetter and property/setter methods, makes a get and set method whose names are the attribute name,
in PascalCase, preceeded by "set" or "get"
"""
def __init_subclass__(cls, **kwargs):
# iterate through methods
for name in dir(cls):
# get function
func = getattr(cls, name)
# ignore any which aren't attributeSetters
if not isinstance(func, (attributeSetter, property)):
continue
# work out getter method name
getterName = "get" + CaseSwitcher.camel2pascal(name)
# ignore any which already have a getter method
if not hasattr(cls, getterName):
# create a pre-populated caller for getattr
meth = partialmethod(getattr, name)
# assign setter method
setattr(cls, getterName, meth)
# any non-settable properties are now done
if isinstance(func, property) and func.fset is None:
continue
# work out setter method name
setterName = "set" + CaseSwitcher.camel2pascal(name)
# ignore any which already have a setter method
if not hasattr(cls, setterName):
# create a pre-populated caller for setAttribute
meth = partialmethod(setAttribute, name)
# assign setter method
setattr(cls, setterName, meth)
# return class
return cls
| 8,360
|
Python
|
.py
| 186
| 34.973118
| 119
| 0.595528
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,411
|
filetools.py
|
psychopy_psychopy/psychopy/tools/filetools.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).
"""Functions and classes related to file and directory handling
"""
import os
import shutil
import subprocess
import sys
import atexit
import codecs
import numpy as np
import json
import json_tricks
try:
import cPickle as pickle
except ImportError:
import pickle
from psychopy import logging
from psychopy.tools.fileerrortools import handleFileCollision
from pathlib import Path
def _synonymiseExtensions(assets):
"""
Synonymise filetypes which refer to the same media types.
Parameters
==========
assets : dict
Dict of {name: path} pairs
Returns
==========
dict
Same dict which was passed in, but any names ending in a recognised extension
will have variants with the same stem but different (and synonymous) extensions,
pointing to the same path. For example:
{"default.png": "default.png"}
becomes
{"default.png": "default.png", "default.jpg": "default.png", "default.jpeg": "default.png"}
"""
# Alias filetypes
newAssets = {}
for key, val in assets.items():
# Skip if no ext
if "." not in key:
continue
# Get stem and ext
stem, ext = key.split(".")
# Synonymise image types
imgTypes = ("png", "jpg", "jpeg")
if ext in imgTypes:
for thisExt in imgTypes:
newAssets[stem + "." + thisExt] = val
# Synonymise movie types
movTypes = ("mp4", "mov", "mkv", "avi", "wmv")
if ext in movTypes:
for thisExt in movTypes:
newAssets[stem + "." + thisExt] = val
# Synonymise audio types
sndTypes = ("mp3", "wav")
if ext in sndTypes:
for thisExt in sndTypes:
newAssets[stem + "." + thisExt] = val
return newAssets
# Names accepted by stimulus classes & the filename of the default stimulus to use
defaultStimRoot = Path(__file__).parent.parent / "assets"
defaultStim = {
# Image stimuli
"default.png": "default.png",
# Movie stimuli
"default.mp4": "default.mp4",
# Sound stimuli
"default.mp3": "default.mp3",
# Credit card image
"creditCard.png": "creditCard.png",
"CreditCard.png": "creditCard.png",
"creditcard.png": "creditCard.png",
# USB image
"USB.png": "USB.png",
"usb.png": "USB.png",
# USB-C image
"USB-C.png": "USB-C.png",
"USB_C.png": "USB-C.png",
"USBC.png": "USB-C.png",
"usb-c.png": "USB-C.png",
"usb_c.png": "USB-C.png",
"usbc.png": "USB-C.png",
}
defaultStim = _synonymiseExtensions(defaultStim)
def toFile(filename, data):
"""Save data (of any sort) as a pickle file.
simple wrapper of the cPickle module in core python
"""
f = open(filename, 'wb')
pickle.dump(data, f)
f.close()
def fromFile(filename, encoding='utf-8-sig'):
"""Load data from a psydat, pickle or JSON file.
Parameters
----------
encoding : str
The encoding to use when reading a JSON file. This parameter will be
ignored for any other file type.
"""
filename = pathToString(filename)
if filename.endswith('.psydat'):
with open(filename, 'rb') as f:
try:
contents = pickle.load(f)
except UnicodeDecodeError:
f.seek(0) # reset to start of file to try again
contents = pickle.load(f, encoding='latin1') # python 2 data files
# if loading an experiment file make sure we don't save further
# copies using __del__
if hasattr(contents, 'abort'):
contents.abort()
return contents
elif filename.endswith('pickle'):
with open(filename, 'rb') as f:
contents = pickle.load(f)
return contents
elif filename.endswith('.json'):
with codecs.open(filename, 'r', encoding=encoding) as f:
contents = json_tricks.load(f)
# Restore RNG if we load a TrialHandler2 object.
# We also need to remove the 'temporary' ._rng_state attribute that
# was saved with it.
from psychopy.data import TrialHandler2
if isinstance(contents, TrialHandler2):
contents._rng = np.random.default_rng()
contents._rng.bit_generator.state = contents._rng_state
del contents._rng_state
return contents
# QuestPlus.
if sys.version_info.major == 3 and sys.version_info.minor >= 6:
from psychopy.data.staircase import QuestPlusHandler
from questplus import QuestPlus
if isinstance(contents, QuestPlusHandler):
# Restore the questplus.QuestPlus object.
contents._qp = QuestPlus.from_json(contents._qp_json)
del contents._qp_json
return contents
# If we haven't returned anything by now, the loaded object is neither
# a TrialHandler2 nor a QuestPlus instance. Return it unchanged.
return contents
else:
msg = "Don't know how to handle this file type, aborting."
raise ValueError(msg)
def mergeFolder(src, dst, pattern=None):
"""Merge a folder into another.
Existing files in `dst` folder with the same name will be
overwritten. Non-existent files/folders will be created.
"""
# dstdir must exist first
srcnames = os.listdir(src)
for name in srcnames:
srcfname = os.path.join(src, name)
dstfname = os.path.join(dst, name)
if os.path.isdir(srcfname):
if not os.path.isdir(dstfname):
os.makedirs(dstfname)
mergeFolder(srcfname, dstfname)
else:
try:
# copy without metadata:
shutil.copyfile(srcfname, dstfname)
except IOError as why:
print(why)
def openOutputFile(fileName=None, append=False, fileCollisionMethod='rename',
encoding='utf-8-sig'):
"""Open an output file (or standard output) for writing.
:Parameters:
fileName : None, 'stdout', or str
The desired output file name. If `None` or `stdout`, return
`sys.stdout`. Any other string will be considered a filename.
append : bool, optional
If ``True``, append data to an existing file; otherwise, overwrite
it with new data.
Defaults to ``True``, i.e. appending.
fileCollisionMethod : string, optional
How to handle filename collisions. Valid values are `'rename'`,
`'overwrite'`, and `'fail'`.
This parameter is ignored if ``append`` is set to ``True``.
Defaults to `rename`.
encoding : string, optional
The encoding to use when writing the file. This parameter will be
ignored if `append` is `False` and `fileName` ends with `.psydat`
or `.npy` (i.e. if a binary file is to be written).
Defaults to ``'utf-8'``.
:Returns:
f : file
A writable file handle.
"""
fileName = pathToString(fileName)
if (fileName is None) or (fileName == 'stdout'):
return sys.stdout
if append:
mode = 'a'
else:
if fileName.endswith(('.psydat', '.npy')):
mode = 'wb'
else:
mode = 'w'
# Rename the output file if a file of that name already exists
# and it should not be appended.
if os.path.exists(fileName) and not append:
fileName = handleFileCollision(
fileName,
fileCollisionMethod=fileCollisionMethod)
# Do not use encoding when writing a binary file.
if 'b' in mode:
encoding = None
if os.path.exists(fileName) and mode in ['w', 'wb']:
logging.info('Data file %s will be overwritten' % fileName)
# The file will always be opened in binary writing mode,
# see https://docs.python.org/2/library/codecs.html#codecs.open
f = codecs.open(fileName, mode=mode, encoding=encoding)
return f
def genDelimiter(fileName):
"""Return a delimiter based on a filename.
:Parameters:
fileName : string
The output file name.
:Returns:
delim : string
A delimiter picked based on the supplied filename. This will be
``,`` if the filename extension is ``.csv``, and a tabulator
character otherwise.
"""
fileName = pathToString(fileName)
if fileName.endswith(('.csv', '.CSV')):
delim = ','
else:
delim = '\t'
return delim
def genFilenameFromDelimiter(filename, delim):
# If no known filename extension was specified, derive a one from the
# delimiter.
filename = pathToString(filename)
if not filename.endswith(('.dlm', '.DLM', '.tsv', '.TSV', '.txt',
'.TXT', '.csv', '.CSV', '.psydat', '.npy',
'.json')):
if delim == ',':
filename += '.csv'
elif delim == '\t':
filename += '.tsv'
else:
filename += '.txt'
return filename
def constructLegacyFilename(filename):
# make path object from filename
filename = Path(filename)
# construct legacy variant name
legacyName = filename.parent / (filename.stem + "_legacy" + filename.suffix)
return legacyName
class DictStorage(dict):
"""Helper class based on dictionary with storage to json
"""
def __init__(self, filename, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.filename = filename
self.load()
self._deleted = False
atexit.register(self.__del__)
def load(self, filename=None):
"""Load all tokens from a given filename
(defaults to ~/.PsychoPy3/pavlovia.json)
"""
if filename is None:
filename = self.filename
if os.path.isfile(filename):
with open(filename, 'r') as f:
try:
self.update(json.load(f))
except ValueError:
logging.error("Tried to load %s but it wasn't valid "
"JSON format"
%filename)
def save(self, filename=None):
"""Save all tokens from a given filename
(defaults to the filename given to the class but can be overridden)
"""
if filename is None:
filename = self.filename
# make sure the folder exists
folder = os.path.split(filename)[0]
if not os.path.isdir(folder):
os.makedirs(folder)
# save the file as json
with open(filename, 'wb') as f:
json_str = json.dumps(self, indent=2, sort_keys=True)
f.write(bytes(json_str, 'UTF-8'))
def __del__(self):
if not self._deleted:
self.save()
self._deleted = True
class KnownProjects(DictStorage):
def save(self, filename=None):
"""Purge unnecessary projects (without a local root) and save"""
toPurge = []
for projname in self:
proj = self[projname]
if not proj['localRoot']:
toPurge.append(projname)
for projname in toPurge:
del self[projname]
DictStorage.save(self, filename)
def pathToString(filepath):
"""
Coerces pathlib Path objects to a string (only python version 3.6+)
any other objects passed to this function will be returned as is.
This WILL NOT work with on Python 3.4, 3.5 since the __fspath__ under
method did not exist in those versions, however psychopy does not support
these versions of python anyways.
:Parameters:
filepath : str or pathlib.Path
file system path that needs to be coerced into a string to
use by Psychopy's internals
:Returns:
filepath : str or same as input object
file system path coerced into a string type
"""
if hasattr(filepath, "__fspath__"):
return filepath.__fspath__()
return filepath
def openInExplorer(path):
"""
Open a given director path in current operating system's file explorer.
"""
# Choose a command according to OS
if sys.platform in ['win32']:
comm = "explorer"
elif sys.platform in ['darwin']:
comm = "open"
elif sys.platform in ['linux', 'linux2']:
comm = "dolphin"
# Use command to open folder
ret = subprocess.call(" ".join([comm, path]), shell=True)
return ret
| 12,719
|
Python
|
.py
| 339
| 29.410029
| 99
| 0.613904
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,412
|
util.py
|
psychopy_psychopy/psychopy/gui/util.py
|
from psychopy.data.utils import parsePipeSyntax
def makeDisplayParams(expInfo, sortKeys=True, labels=None, tooltips=None, fixed=None, order=None):
# copy dict so nothing we do here affects it
expInfo = expInfo.copy()
# default blank dict for labels and tooltips
if labels is None:
labels = {}
if tooltips is None:
tooltips = {}
# make sure fixed is a list
if isinstance(fixed, str):
fixed = [fixed]
# get keys as a list
keys = list(expInfo)
# sort alphabetically if requested
if sortKeys:
keys.sort()
# arrays for config and regular params
sortedParams = []
unsortedParams = []
sortedConfig = []
unsortedConfig = []
# iterate through keys
for key in keys:
# parse key
label, flags = parsePipeSyntax(key)
# if given a label, use it
if key in labels:
label = labels[key]
# if given a tooltip, use it
tip = ""
if key in tooltips:
tip = tooltips[key]
# work out index from flags
i = None
for flag in flags:
if flag.isnumeric():
i = int(flag)
# if given, manually set order should override flags
if order is not None and key in order:
i = order.index(key)
# work out fixed
if "fix" not in flags and fixed is not None and key in fixed:
flags.append("fix")
# construct display param
param = {
'key': key,
'label': label,
'tip': tip,
'value': expInfo[key],
'flags': flags,
'index': i,
}
# decide which list to add to
if "cfg" in flags and i is not None:
sortedConfig.append(param)
elif "cfg" in flags:
unsortedConfig.append(param)
elif i is not None:
sortedParams.append(param)
else:
unsortedParams.append(param)
# sort the sorted params/config by index
sortedParams.sort(key=lambda x: x['index'])
sortedConfig.sort(key=lambda x: x['index'])
# return all params and configs
if len(sortedConfig + unsortedConfig):
# return with readmore line if there are configs
return sortedParams + unsortedParams + ["---"] + sortedConfig + unsortedConfig
else:
# return without if there aren't
return sortedParams + unsortedParams
| 2,447
|
Python
|
.py
| 72
| 25.513889
| 98
| 0.593342
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,413
|
__init__.py
|
psychopy_psychopy/psychopy/gui/__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).
"""
Graphical user interface elements for experiments.
This lib will attempt to use PyQt (4 or 5) if possible and will revert to
using wxPython if PyQt is not found.
"""
import sys
from .. import constants
# check if wx has been imported. If so, import here too and check for app
if 'wx' in sys.modules:
import wx
wxApp = wx.GetApp()
else:
wxApp = None
# then setup prefs for
haveQt = False # until we confirm otherwise
if wxApp is None: # i.e. don't try this if wx is already running
# set order for attempts on PyQt5/PyQt6
importOrder = ['PyQt6', 'PyQt5']
# then check each in turn
for libname in importOrder:
try:
exec("import {}".format(libname))
haveQt = libname
break
except ImportError:
pass
# now we know what we can import let's import the rest
if haveQt:
from .qtgui import *
else:
try:
from .wxgui import *
except ImportError:
print("Neither wxPython nor PyQt could be imported "
"so gui is not available")
| 1,290
|
Python
|
.py
| 40
| 27.725
| 79
| 0.680611
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,414
|
qtgui.py
|
psychopy_psychopy/psychopy/gui/qtgui.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# To build simple dialogues etc. (requires pyqt4)
#
# 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 importlib
from psychopy import logging, data
from psychopy.tools.arraytools import IndexDict
from . import util
haveQt = False # until we confirm otherwise
importOrder = ['PyQt6', 'PyQt5']
for libname in importOrder:
try:
importlib.import_module(f"{libname}.QtCore")
haveQt = libname
logging.debug(f"psychopy.gui is using {haveQt}")
break
except ModuleNotFoundError:
pass
if not haveQt:
# do the main import again not in a try...except to recreate error
import PyQt6
elif haveQt == 'PyQt6':
from PyQt6 import QtWidgets
from PyQt6 import QtGui
from PyQt6.QtCore import Qt
elif haveQt == 'PyQt5':
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from psychopy import logging
import numpy as np
import os
import sys
import json
from psychopy.localization import _translate
qtapp = QtWidgets.QApplication.instance()
def ensureQtApp():
global qtapp
# make sure there's a QApplication prior to showing a gui, e.g., for expInfo
# dialog
if qtapp is None:
qtapp = QtWidgets.QApplication(sys.argv)
qtapp.setStyle('Fusion') # use this to avoid annoying PyQt bug with OK being greyed-out
wasMouseVisible = True
class ReadmoreCtrl(QtWidgets.QLabel):
"""
A linked label which shows/hides a set of control on click.
"""
def __init__(self, parent, label=""):
QtWidgets.QLabel.__init__(self, parent)
# set initial state and label
self.state = False
self.label = label
self.updateLabel()
# array to store linked ctrls
self.linkedCtrls = []
# bind onclick
self.setOpenExternalLinks(False)
self.linkActivated.connect(self.onToggle)
def updateLabel(self):
"""
Update label so that e.g. arrow matches current state.
"""
# reset label to its own value to refresh
self.setLabel(self.label)
def setLabel(self, label=""):
"""
Set the label of this ctrl (will append arrow and necessary HTML for a link)
"""
# store label root
self.label = label
# choose an arrow according to state
if self.state:
arrow = "▾"
else:
arrow = "▸"
# construct text to set
text = f"<a href='.' style='color: black; text-decoration: none;'>{arrow} {label}</a>"
# set label text
self.setText(text)
def onToggle(self, evt=None):
"""
Toggle visibility of linked ctrls. Called on press.
"""
# toggle state
self.state = not self.state
# show/hide linked ctrls according to state
for ctrl in self.linkedCtrls:
if self.state:
ctrl.show()
else:
ctrl.hide()
# update label
self.updateLabel()
# resize dlg
self.parent().adjustSize()
def linkCtrl(self, ctrl):
"""
Connect a ctrl to this ReadmoreCtrl such that it's shown/hidden on toggle.
"""
# add to array of linked ctrls
self.linkedCtrls.append(ctrl)
# show/hide according to own state
if self.state:
ctrl.show()
else:
ctrl.hide()
# resize dlg
self.parent().adjustSize()
class Dlg(QtWidgets.QDialog):
"""A simple dialogue box. You can add text or input boxes
(sequentially) and then retrieve the values.
see also the function *dlgFromDict* for an **even simpler** version
**Example**
.. code-block:: python
from psychopy import gui
myDlg = gui.Dlg(title="JWP's experiment")
myDlg.addText('Subject info')
myDlg.addField('Name:')
myDlg.addField('Age:', 21)
myDlg.addText('Experiment Info')
myDlg.addField('Grating Ori:',45)
myDlg.addField('Group:', choices=["Test", "Control"])
ok_data = myDlg.show() # show dialog and wait for OK or Cancel
if myDlg.OK: # or if ok_data is not None
print(ok_data)
else:
print('user cancelled')
"""
def __init__(self, title=_translate('PsychoPy Dialog'),
pos=None, size=None, style=None,
labelButtonOK=_translate(" OK "),
labelButtonCancel=_translate(" Cancel "),
screen=-1, alwaysOnTop=False):
ensureQtApp()
QtWidgets.QDialog.__init__(self, None)
self.inputFields = []
self.inputFieldTypes = {}
self.inputFieldNames = []
self.data = IndexDict()
self.irow = 0
self.pos = pos
# QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
# set always stay on top
if alwaysOnTop:
self.setWindowFlags(Qt.WindowType.WindowStaysOnTopHint)
# add buttons for OK and Cancel
buttons = QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel
self.buttonBox = QtWidgets.QDialogButtonBox(buttons, parent=self)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# store references to OK and CANCEL buttons
self.okBtn = self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Ok)
self.cancelBtn = self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Cancel)
if style:
raise RuntimeWarning("Dlg does not currently support the "
"style kwarg.")
self.size = size
if haveQt in ['PyQt5', 'PyQt6']:
nScreens = len(qtapp.screens())
else:
nScreens = QtWidgets.QDesktopWidget().screenCount()
self.screen = -1 if screen >= nScreens else screen
# self.labelButtonOK = labelButtonOK
# self.labelButtonCancel = labelButtonCancel
self.layout = QtWidgets.QGridLayout()
self.layout.setSpacing(10)
self.layout.setColumnMinimumWidth(1, 250)
# add placeholder for readmore control sizer
self.readmore = None
# add message about required fields (shown/hidden by validate)
msg = _translate("Fields marked with an asterisk (*) are required.")
self.requiredMsg = QtWidgets.QLabel(text=msg, parent=self)
self.layout.addWidget(self.requiredMsg, 0, 0, 1, -1)
self.irow += 1
self.setLayout(self.layout)
self.setWindowTitle(title)
def addText(self, text, color='', isFieldLabel=False):
textLabel = QtWidgets.QLabel(text, parent=self)
if len(color):
textLabel.setStyleSheet("color: {0};".format(color))
if isFieldLabel is True:
self.layout.addWidget(textLabel, self.irow, 0, 1, 1)
else:
self.layout.addWidget(textLabel, self.irow, 0, 1, 2)
self.irow += 1
return textLabel
def addField(self, key, initial='', color='', choices=None, tip='',
required=False, enabled=True, label=None):
"""Adds a (labelled) input field to the dialogue box,
optional text color and tooltip.
If 'initial' is a bool, a checkbox will be created.
If 'choices' is a list or tuple, a dropdown selector is created.
Otherwise, a text line entry box is created.
Returns a handle to the field (but not to the label).
"""
# if not given a label, use key (sans-pipe syntax)
if label is None:
label, _ = util.parsePipeSyntax(key)
self.inputFieldNames.append(label)
if choices:
self.inputFieldTypes[label] = str
else:
self.inputFieldTypes[label] = type(initial)
if type(initial) == np.ndarray:
initial = initial.tolist()
# create label
inputLabel = self.addText(label, color, isFieldLabel=True)
# create input control
if type(initial) == bool and not choices:
self.data[key] = initial
inputBox = QtWidgets.QCheckBox(parent=self)
inputBox.setChecked(initial)
def handleCheckboxChange(new_state):
self.data[key] = inputBox.isChecked()
msg = "handleCheckboxChange: inputFieldName={0}, checked={1}"
logging.debug(msg.format(label, self.data[key]))
inputBox.stateChanged.connect(handleCheckboxChange)
elif not choices:
self.data[key] = initial
inputBox = QtWidgets.QLineEdit(str(initial), parent=self)
def handleLineEditChange(new_text):
ix = self.inputFields.index(inputBox)
name = self.inputFieldNames[ix]
thisType = self.inputFieldTypes[name]
try:
if thisType in (str, bytes):
self.data[key] = str(new_text)
elif thisType == tuple:
jtext = "[" + str(new_text) + "]"
self.data[key] = json.loads(jtext)[0]
elif thisType == list:
jtext = "[" + str(new_text) + "]"
self.data[key] = json.loads(jtext)[0]
elif thisType == float:
self.data[key] = float(new_text)
elif thisType == int:
self.data[key] = int(new_text)
elif thisType == dict:
jtext = "[" + str(new_text) + "]"
self.data[key] = json.loads(jtext)[0]
elif thisType == np.ndarray:
self.data[key] = np.array(
json.loads("[" + str(new_text) + "]")[0])
else:
self.data[key] = new_text
msg = ("Unknown type in handleLineEditChange: "
"inputFieldName={0}, type={1}, value={2}")
logging.warning(msg.format(label, thisType,
self.data[ix]))
msg = ("handleLineEditChange: inputFieldName={0}, "
"type={1}, value={2}")
logging.debug(msg.format(label, thisType, self.data[key]))
except Exception as e:
self.data[key] = str(new_text)
msg = ('Error in handleLineEditChange: inputFieldName='
'{0}, type={1}, value={2}, error={3}')
logging.error(msg.format(label, thisType, self.data[key],
e))
self.validate()
inputBox.textEdited.connect(handleLineEditChange)
else:
inputBox = QtWidgets.QComboBox(parent=self)
choices = list(choices)
for i, option in enumerate(choices):
inputBox.addItem(str(option))
# inputBox.addItems([unicode(option) for option in choices])
inputBox.setItemData(i, (option,))
if (isinstance(initial, (int, int)) and
len(choices) > initial >= 0):
pass
elif initial in choices:
initial = choices.index(initial)
else:
initial = 0
inputBox.setCurrentIndex(initial)
self.data[key] = choices[initial]
def handleCurrentIndexChanged(new_index):
ix = self.inputFields.index(inputBox)
try:
self.data[key] = inputBox.itemData(new_index).toPyObject()[0]
except AttributeError:
self.data[key] = inputBox.itemData(new_index)[0]
msg = ("handleCurrentIndexChanged: inputFieldName={0}, "
"selected={1}, type: {2}")
logging.debug(msg.format(label, self.data[key],
type(self.data[key])))
inputBox.currentIndexChanged.connect(handleCurrentIndexChanged)
# set required (attribute is checked later by validate fcn)
inputBox.required = required
if color is not None and len(color):
inputBox.setPalette(inputLabel.palette())
if tip is not None and len(tip):
inputBox.setToolTip(tip)
inputBox.setEnabled(enabled)
self.layout.addWidget(inputBox, self.irow, 1)
# link to readmore ctrl if we're in one
if self.readmore is not None:
self.readmore.linkCtrl(inputBox)
self.readmore.linkCtrl(inputLabel)
self.inputFields.append(inputBox) # store this to get data back on OK
self.irow += 1
return inputBox
def addFixedField(self, key, label='', initial='', color='', choices=None,
tip=''):
"""Adds a field to the dialog box (like addField) but the field cannot
be edited. e.g. Display experiment version.
"""
return self.addField(
key=key, label=label, initial=initial, color=color, choices=choices, tip=tip,
enabled=False
)
def addReadmoreCtrl(self):
line = ReadmoreCtrl(self, label=_translate("Configuration fields..."))
self.layout.addWidget(line, self.irow, 0, 1, 2)
self.irow += 1
self.enterReadmoreCtrl(line)
return line
def enterReadmoreCtrl(self, ctrl):
self.readmore = ctrl
def exitReadmoreCtrl(self):
self.readmore = None
def display(self):
"""Presents the dialog and waits for the user to press OK or CANCEL.
If user presses OK button, function returns a list containing the
updated values coming from each of the input fields created.
Otherwise, None is returned.
:return: self.data
"""
return self.exec_()
def validate(self):
"""
Make sure that required fields have a value.
"""
# start off assuming valid
valid = True
# start off assuming no required fields
hasRequired = False
# iterate through fields
for field in self.inputFields:
# if field isn't required, skip
if not field.required:
continue
# if we got this far, we have a required field
hasRequired = True
# validation is only relevant for text fields, others have defaults
if not isinstance(field, QtWidgets.QLineEdit):
continue
# check that we have text
if not len(field.text()):
valid = False
# if not valid, disable OK button
self.okBtn.setEnabled(valid)
# show required message if we have any required fields
if hasRequired:
self.requiredMsg.show()
else:
self.requiredMsg.hide()
def show(self):
"""Presents the dialog and waits for the user to press OK or CANCEL.
If user presses OK button, function returns a list containing the
updated values coming from each of the input fields created.
Otherwise, None is returned.
:return: self.data
"""
# NB
#
# ** QDialog already has a show() method. So this method calls
# QDialog.show() and then exec_(). This seems to not cause issues
# but we need to keep an eye out for any in future.
return self.display()
def exec_(self):
"""Presents the dialog and waits for the user to press OK or CANCEL.
If user presses OK button, function returns a list containing the
updated values coming from each of the input fields created.
Otherwise, None is returned.
"""
self.layout.addWidget(self.buttonBox, self.irow, 0, 1, 2)
if self.pos is None:
# Center Dialog on appropriate screen
frameGm = self.frameGeometry()
if self.screen <= 0:
qtscreen = QtGui.QGuiApplication.primaryScreen()
else:
qtscreen = self.screen
centerPoint = qtscreen.availableGeometry().center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
else:
self.move(self.pos[0], self.pos[1])
QtWidgets.QDialog.show(self)
self.raise_()
self.activateWindow()
if self.inputFields:
self.inputFields[0].setFocus()
self.OK = False
if QtWidgets.QDialog.exec(self): # == QtWidgets.QDialog.accepted:
self.OK = True
return self.data
class DlgFromDict(Dlg):
"""Creates a dialogue box that represents a dictionary of values.
Any values changed by the user are change (in-place) by this
dialogue box.
Parameters
----------
dictionary : dict
A dictionary defining the input fields (keys) and pre-filled values
(values) for the user dialog
title : str
The title of the dialog window
labels : dict
A dictionary defining labels (values) to be displayed instead of
key strings (keys) defined in `dictionary`. Not all keys in
`dictionary` need to be contained in labels.
fixed : list
A list of keys for which the values shall be displayed in non-editable
fields
order : list
A list of keys defining the display order of keys in `dictionary`.
If not all keys in `dictionary`` are contained in `order`, those
will appear in random order after all ordered keys.
tip : list
A dictionary assigning tooltips to the keys
screen : int
Screen number where the Dialog is displayed. If -1, the Dialog will
be displayed on the primary screen.
sortKeys : bool
A boolean flag indicating that keys are to be sorted alphabetically.
copyDict : bool
If False, modify `dictionary` in-place. If True, a copy of
the dictionary is created, and the altered version (after
user interaction) can be retrieved from
:attr:~`psychopy.gui.DlgFromDict.dictionary`.
labels : dict
A dictionary defining labels (dict values) to be displayed instead of
key strings (dict keys) defined in `dictionary`. Not all keys in
`dictionary´ need to be contained in labels.
show : bool
Whether to immediately display the dialog upon instantiation.
If False, it can be displayed at a later time by calling
its `show()` method.
e.g.:
::
info = {'Observer':'jwp', 'GratingOri':45,
'ExpVersion': 1.1, 'Group': ['Test', 'Control']}
infoDlg = gui.DlgFromDict(dictionary=info,
title='TestExperiment', fixed=['ExpVersion'])
if infoDlg.OK:
print(info)
else:
print('User Cancelled')
In the code above, the contents of *info* will be updated to the values
returned by the dialogue box.
If the user cancels (rather than pressing OK),
then the dictionary remains unchanged. If you want to check whether
the user hit OK, then check whether DlgFromDict.OK equals
True or False
See GUI.py for a usage demo, including order and tip (tooltip).
"""
def __init__(self, dictionary, title='', fixed=None, order=None,
tip=None, screen=-1, sortKeys=True, copyDict=False,
labels=None, show=True, alwaysOnTop=False):
# Note: As of 2023.2.0, we do not allow sort_keys or copy_dict
Dlg.__init__(self, title, screen=screen, alwaysOnTop=alwaysOnTop)
if copyDict:
self.dictionary = dictionary.copy()
else:
self.dictionary = dictionary
# initialise storage attributes
self._labels = []
self._keys = []
# convert to a list of params
params = util.makeDisplayParams(
self.dictionary,
sortKeys=sortKeys,
labels=labels,
tooltips=tip,
order=order,
fixed=fixed
)
# make ctrls
for param in params:
# if param is the readmore button, add it and continue
if param == "---":
self.addReadmoreCtrl()
continue
# add asterisk to label if needed
if "req" in param['flags'] and "*" not in param['label']:
param['label'] += "*"
# store attributes from this param
self._labels.append(param['label'])
self._keys.append(param['key'])
# make ctrls
if "hid" in param['flags']:
# don't add anything if it's hidden
pass
elif "fix" in param['flags']:
self.addFixedField(
param['key'],
label=param['label'],
initial=param['value'],
tip=param['tip']
)
elif isinstance(param['value'], (list, tuple)):
self.addField(
param['key'],
choices=param['value'],
label=param['label'],
tip=param['tip'],
required="req" in param['flags']
)
else:
self.addField(
param['key'],
initial=param['value'],
label=param['label'],
tip=param['tip'],
required="req" in param['flags']
)
# validate so the required message is shown/hidden as appropriate
self.validate()
if show:
self.show()
def show(self):
"""Display the dialog.
"""
data = self.exec_()
if data is not None:
self.dictionary.update(data)
return self.dictionary
def fileSaveDlg(initFilePath="", initFileName="",
prompt=_translate("Select file to save"),
allowed=None):
"""A simple dialogue allowing write access to the file system.
(Useful in case you collect an hour of data and then try to
save to a non-existent directory!!)
:parameters:
initFilePath: string
default file path on which to open the dialog
initFileName: string
default file name, as suggested file
prompt: string (default "Select file to open")
can be set to custom prompts
allowed: string
a string to specify file filters.
e.g. "Text files (\\*.txt) ;; Image files (\\*.bmp \\*.gif)"
See https://www.riverbankcomputing.com/static/Docs/PyQt4/qfiledialog.html
#getSaveFileName
for further details
If initFilePath or initFileName are empty or invalid then
current path and empty names are used to start search.
If user cancels the None is returned.
"""
if allowed is None:
allowed = ("All files (*.*);;"
"txt (*.txt);;"
"pickled files (*.pickle *.pkl);;"
"shelved files (*.shelf)")
ensureQtApp()
fdir = os.path.join(initFilePath, initFileName)
pathOut = QtWidgets.QFileDialog.getSaveFileName(parent=None, caption=prompt,
directory=fdir, filter=allowed)
if type(pathOut) == tuple: # some versions(?) of PyQt return (files, filter)
pathOut = pathOut[0]
if len(pathOut) == 0:
return None
return str(pathOut) or None
def fileOpenDlg(tryFilePath="",
tryFileName="",
prompt=_translate("Select file to open"),
allowed=None):
"""A simple dialogue allowing read access to the file system.
:parameters:
tryFilePath: string
default file path on which to open the dialog
tryFileName: string
default file name, as suggested file
prompt: string (default "Select file to open")
can be set to custom prompts
allowed: string (available since v1.62.01)
a string to specify file filters.
e.g. "Text files (\\*.txt) ;; Image files (\\*.bmp \\*.gif)"
See https://www.riverbankcomputing.com/static/Docs/PyQt4/qfiledialog.html
#getOpenFileNames
for further details
If tryFilePath or tryFileName are empty or invalid then
current path and empty names are used to start search.
If user cancels, then None is returned.
"""
ensureQtApp()
if allowed is None:
allowed = ("All files (*.*);;"
"PsychoPy Data (*.psydat);;"
"txt (*.txt *.dlm *.csv);;"
"pickled files (*.pickle *.pkl);;"
"shelved files (*.shelf)")
fdir = os.path.join(tryFilePath, tryFileName)
filesToOpen = QtWidgets.QFileDialog.getOpenFileNames(parent=None,
caption=prompt,
directory=fdir,
filter=allowed)
if type(filesToOpen) == tuple: # some versions(?) of PyQt return (files, filter)
filesToOpen = filesToOpen[0]
filesToOpen = [str(fpath) for fpath in filesToOpen
if os.path.exists(fpath)]
if len(filesToOpen) == 0:
return None
return filesToOpen
def infoDlg(title=_translate("Information"), prompt=None):
ensureQtApp()
_pr = _translate("No details provided. ('prompt' value not set).")
QtWidgets.QMessageBox.information(None, title, prompt or _pr)
def warnDlg(title=_translate("Warning"), prompt=None):
ensureQtApp()
_pr = _translate("No details provided. ('prompt' value not set).")
QtWidgets.QMessageBox.warning(None, title, prompt or _pr)
def criticalDlg(title=_translate("Critical"), prompt=None):
ensureQtApp()
_pr = _translate("No details provided. ('prompt' value not set).")
QtWidgets.QMessageBox.critical(None, title, prompt or _pr)
def aboutDlg(title=_translate("About Experiment"), prompt=None):
ensureQtApp()
_pr = _translate("No details provided. ('prompt' value not set).")
QtWidgets.QMessageBox.about(None, title, prompt or _pr)
# Psychopy pyglet window show / hide util functions
def hideWindow(win):
global wasMouseVisible
if win.winHandle._visible is True:
wasMouseVisible = win.mouseVisible
win.setMouseVisible(True, log=False)
win.winHandle.minimize()
def showWindow(win):
global wasMouseVisible
if win.winHandle._visible is False:
win.setMouseVisible(wasMouseVisible, log=False)
win.winHandle.maximize()
win.winHandle.set_visible(True)
win.winHandle.activate()
if __name__ == '__main__':
# Local manual test cases for dialog types....
logging.console.setLevel(logging.DEBUG)
# from psychopy import visual, event
# Create, and hide, a full screen psychopy window
# win = visual.Window([1024, 768],
# fullscr=True,
# allowGUI=False,
# screen=0)
# hideWindow(win)
# Test base Dlg class
dlg = Dlg()
dlg.addText("This is a line of text", color="Red")
dlg.addText("Second line of text")
dlg.addField("A checkbox", initial=True, tip="Here is your checkbox tip!")
dlg.addField("Another checkbox", initial=False, color="Blue")
dlg.addFixedField("ReadOnly checkbox", initial=False, color="Blue",
tip="This field is readonly.")
dlg.addField("A textline", initial="",
tip="Here is your <b>textline</b> tip!")
dlg.addField("A Number:", initial=23, tip="This must be a number.")
dlg.addField("A List:", initial=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
tip="This must be a list.")
dlg.addField("A ndarray:",
initial=np.asarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
tip="This must be a numpy array.")
dlg.addField("Another textline", initial="default text", color="Green")
dlg.addFixedField("ReadOnly textline", initial="default text",
tip="This field is readonly.")
dlg.addField("A dropdown", initial='B', choices=['A', 'B', 'C'],
tip="Here is your <b>dropdown</b> tip!")
dlg.addField("Mixed type dropdown", initial=2,
choices=['A String', 1234567, [12.34, 56.78],
('tuple element 0', 'tuple element 1'),
{'key1': 'val1', 'key2': 23}],
color="Red")
dlg.addField("Yet Another dropdown", choices=[1, 2, 3])
dlg.addFixedField("ReadOnly dropdown", initial=2,
choices=['R1', 'R2', 'R3'],
tip="This field is readonly.")
ok_data = dlg.show()
print(("Dlg ok_data:", ok_data))
# Test Dict Dialog
info = {'Observer*': 'jwp', 'GratingOri': 45,
'ExpVersion': 1.1, 'Group': ['Test', 'Control']}
dictDlg = DlgFromDict(dictionary=info, title='TestExperiment',
labels={'Group': 'Participant Group'},
fixed=['ExpVersion'])
if dictDlg.OK:
print(info)
else:
print('User Cancelled')
# Test File Dialogs
fileToSave = fileSaveDlg(initFileName='__init__.pyc')
print(("fileToSave: [", fileToSave, "]", type(fileToSave)))
fileToOpen = fileOpenDlg()
print(("fileToOpen:", fileToOpen))
# Test Alert Dialogs
infoDlg(prompt="Some not important info for you.")
warnDlg(prompt="Something non critical,\nbut worth mention,\noccurred.")
_pr = "Oh boy, something really bad just happened:<br><b>{0}</b>"
criticalDlg(title="RuntimeError",
prompt=_pr.format(RuntimeError("A made up runtime error")))
aboutDlg(prompt=u"My Experiment v. 1.0"
u"<br>"
u"Written by: Dr. John Doe"
u"<br>"
u"Created using <b>PsychoPy</b> © Copyright 2018, Jonathan Peirce")
# Restore full screen psychopy window
# showWindow(win)
# win.flip()
# from psychopy import event
# event.waitKeys()
| 30,702
|
Python
|
.py
| 714
| 32.04902
| 113
| 0.587961
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,415
|
wxgui.py
|
psychopy_psychopy/psychopy/gui/wxgui.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).
"""To build simple dialogues etc. (requires wxPython)
"""
from psychopy import logging
import wx
import numpy
import os
from psychopy.localization import _translate
from packaging.version import Version
from psychopy.tools.arraytools import IndexDict
OK = wx.ID_OK
thisVer = Version(wx.__version__)
def ensureWxApp():
# make sure there's a wxApp prior to showing a gui, e.g., for expInfo
# dialog
try:
wx.Dialog(None, -1) # not shown; FileDialog gives same exception
return True
except wx._core.PyNoAppError:
if thisVer < Version('2.9'):
return wx.PySimpleApp()
elif thisVer >= Version('4.0') and thisVer < Version('4.1'):
raise Exception(
"wx>=4.0 clashes with pyglet and making it unsafe "
"as a PsychoPy gui helper. Please install PyQt (4 or 5)"
" or wxPython3 instead.")
else:
return wx.App(False)
class Dlg(wx.Dialog):
"""A simple dialogue box. You can add text or input boxes
(sequentially) and then retrieve the values.
see also the function *dlgFromDict* for an **even simpler** version
**Example:** ::
from psychopy import gui
myDlg = gui.Dlg(title="JWP's experiment")
myDlg.addText('Subject info')
myDlg.addField('Name:')
myDlg.addField('Age:', 21)
myDlg.addText('Experiment Info')
myDlg.addField('Grating Ori:',45)
myDlg.addField('Group:', choices=["Test", "Control"])
myDlg.show() # show dialog and wait for OK or Cancel
if myDlg.OK: # then the user pressed OK
thisInfo = myDlg.data
print(thisInfo)
else:
print('user cancelled')
"""
def __init__(self, title=_translate('PsychoPy dialogue'),
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_NO_PARENT,
labelButtonOK=_translate(" OK "),
labelButtonCancel=_translate(" Cancel ")):
style = style | wx.RESIZE_BORDER
global app # avoid recreating for every gui
if pos is None:
pos = wx.DefaultPosition
app = ensureWxApp()
super().__init__(parent=None, id=-1, title=title, style=style, pos=pos)
self.inputFields = []
self.inputFieldTypes = []
self.inputFieldNames = []
self.data = []
# prepare a frame in which to hold objects
self.sizer = wx.BoxSizer(wx.VERTICAL)
# self.addText('') # insert some space at top of dialogue
self.pos = pos
self.labelButtonOK = labelButtonOK
self.labelButtonCancel = labelButtonCancel
def addText(self, text, color=''):
# the horizontal extent can depend on the locale and font in use:
font = self.GetFont()
dc = wx.WindowDC(self)
dc.SetFont(font)
textWidth, textHeight = dc.GetTextExtent(text)
textLength = wx.Size(textWidth + 50, textHeight)
_style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL
myTxt = wx.StaticText(self, -1, label=text, style=_style,
size=textLength)
if len(color):
myTxt.SetForegroundColour(color)
self.sizer.Add(myTxt, 1, wx.ALIGN_CENTER)
def addField(self, label='', initial='', color='', choices=None, tip=''):
"""Adds a (labelled) input field to the dialogue box, optional text
color and tooltip. Returns a handle to the field (but not to the
label). If choices is a list or tuple, it will create a dropdown
selector.
"""
self.inputFieldNames.append(label)
if choices:
self.inputFieldTypes.append(str)
else:
self.inputFieldTypes.append(type(initial))
if type(initial) == numpy.ndarray:
initial = initial.tolist() # convert numpy arrays to lists
container = wx.GridSizer(cols=2, vgap=0, hgap=10)
# create label
font = self.GetFont()
dc = wx.WindowDC(self)
dc.SetFont(font)
labelWidth, labelHeight = dc.GetTextExtent(label)
labelLength = wx.Size(labelWidth + 16, labelHeight)
inputLabel = wx.StaticText(self, -1, label,
size=labelLength,
style=wx.ALIGN_RIGHT)
if len(color):
inputLabel.SetForegroundColour(color)
_style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT
container.Add(inputLabel, 1, _style)
# create input control
if type(initial) == bool:
inputBox = wx.CheckBox(self, -1)
inputBox.SetValue(initial)
elif not choices:
inputWidth, inputHeight = dc.GetTextExtent(str(initial))
inputLength = wx.Size(max(50, inputWidth + 16),
max(25, inputHeight + 8))
inputBox = wx.TextCtrl(self, -1, str(initial),
size=inputLength)
else:
inputBox = wx.Choice(self, -1,
choices=[str(option)
for option in list(choices)])
# Somewhat dirty hack that allows us to treat the choice just like
# an input box when retrieving the data
inputBox.GetValue = inputBox.GetStringSelection
initial = choices.index(initial) if initial in choices else 0
inputBox.SetSelection(initial)
if len(color):
inputBox.SetForegroundColour(color)
if len(tip):
inputBox.SetToolTip(wx.ToolTip(tip))
container.Add(inputBox, 1, wx.ALIGN_CENTER_VERTICAL)
self.sizer.Add(container, 1, wx.ALIGN_CENTER)
self.inputFields.append(inputBox) # store this to get data back on OK
return inputBox
def addFixedField(self, label='', value='', tip=''):
"""Adds a field to the dialogue box (like addField) but the
field cannot be edited. e.g. Display experiment version.
tool-tips are disabled (by wx).
"""
thisField = self.addField(label, value, color='Gray', tip=tip)
# wx disables tooltips too; we pass them in anyway
thisField.Disable()
return thisField
def display(self):
"""Presents the dialog and waits for the user to press OK or CANCEL.
If user presses OK button, function returns a list containing the
updated values coming from each of the input fields created.
Otherwise, None is returned.
:return: self.data
"""
# add buttons for OK and Cancel
buttons = self.CreateStdDialogButtonSizer(flags=wx.OK | wx.CANCEL)
self.sizer.Add(buttons, 1, flag=wx.ALIGN_RIGHT, border=5)
self.SetSizerAndFit(self.sizer)
if self.pos is None:
self.Center()
if self.ShowModal() == wx.ID_OK:
self.data = []
# get data from input fields
for n in range(len(self.inputFields)):
thisName = self.inputFieldNames[n]
thisVal = self.inputFields[n].GetValue()
thisType = self.inputFieldTypes[n]
# try to handle different types of input from strings
logging.debug("%s: %s" % (self.inputFieldNames[n],
str(thisVal)))
if thisType in (tuple, list, float, int):
# probably a tuple or list
exec("self.data.append(" + thisVal + ")") # evaluate it
elif thisType == numpy.ndarray:
exec("self.data.append(numpy.array(" + thisVal + "))")
elif thisType in (str, bool):
self.data.append(thisVal)
else:
logging.warning('unknown type:' + self.inputFieldNames[n])
self.data.append(thisVal)
self.OK = True
else:
self.OK = False
self.Destroy()
if self.OK:
return self.data
def show(self):
"""Presents the dialog and waits for the user to press either
OK or CANCEL.
When they do, dlg.OK will be set to True or False (according to
which button they pressed. If OK==True then dlg.data will be
populated with a list of values coming from each of the input
fields created.
"""
return self.display()
class DlgFromDict(Dlg):
"""Creates a dialogue box that represents a dictionary of values.
Any values changed by the user are change (in-place) by this
dialogue box.
Parameters
----------
sortKeys : bool
Whether the dictionary keys should be ordered alphabetically
for displaying.
copyDict : bool
If False, modify ``dictionary`` in-place. If True, a copy of
the dictionary is created, and the altered version (after
user interaction) can be retrieved from
:attr:~`psychopy.gui.DlgFromDict.dictionary`.
show : bool
Whether to immediately display the dialog upon instantiation.
If False, it can be displayed at a later time by calling
its `show()` method.
e.g.:
::
info = {'Observer':'jwp', 'GratingOri':45,
'ExpVersion': 1.1, 'Group': ['Test', 'Control']}
infoDlg = gui.DlgFromDict(dictionary=info,
title='TestExperiment', fixed=['ExpVersion'])
if infoDlg.OK:
print(info)
else:
print('User Cancelled')
In the code above, the contents of *info* will be updated to the values
returned by the dialogue box.
If the user cancels (rather than pressing OK),
then the dictionary remains unchanged. If you want to check whether
the user hit OK, then check whether DlgFromDict.OK equals
True or False
See GUI.py for a usage demo, including order and tip (tooltip).
"""
def __init__(self, dictionary, title='', fixed=None, order=None, tip=None,
sortKeys=True, copyDict=False, show=True,
sort_keys=None, copy_dict=None):
# We don't explicitly check for None identity
# for backward-compatibility reasons.
if not fixed:
fixed = []
if not order:
order = []
if not tip:
tip = dict()
# app = ensureWxApp() done by Dlg
super().__init__(title)
self.copyDict = copyDict
self.originalDictionary = dictionary
self.dictionary = IndexDict(dictionary)
self._keys = list(self.dictionary.keys())
if sortKeys:
self._keys.sort()
if order:
self._keys = list(order) + list(set(self._keys).difference(set(order)))
types = dict()
for field in self._keys:
types[field] = type(self.dictionary[field])
tooltip = ''
if field in tip:
tooltip = tip[field]
if field in fixed:
self.addFixedField(field, self.dictionary[field], tip=tooltip)
elif type(self.dictionary[field]) in [list, tuple]:
self.addField(field, choices=self.dictionary[field],
tip=tooltip)
else:
self.addField(field, self.dictionary[field], tip=tooltip)
if show:
self.show()
def show(self):
"""Display the dialog.
"""
super().show()
if self.OK:
for n, thisKey in enumerate(self._keys):
self.dictionary[thisKey] = self.data[n]
# if not copying dict, set values in-place
if not self.copyDict:
self.originalDictionary[thisKey] = self.data[thisKey]
return self.dictionary
def fileSaveDlg(initFilePath="", initFileName="",
prompt=_translate("Select file to save"),
allowed=None):
"""A simple dialogue allowing write access to the file system.
(Useful in case you collect an hour of data and then try to
save to a non-existent directory!!)
:parameters:
initFilePath: string
default file path on which to open the dialog
initFileName: string
default file name, as suggested file
prompt: string (default "Select file to open")
can be set to custom prompts
allowed: string
A string to specify file filters.
e.g. "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif"
See https://docs.wxpython.org/wx.FileDialog.html
for further details
If initFilePath or initFileName are empty or invalid then
current path and empty names are used to start search.
If user cancels the None is returned.
"""
if allowed is None:
allowed = "All files (*.*)|*.*"
# "txt (*.txt)|*.txt"
# "pickled files (*.pickle, *.pkl)|*.pickle"
# "shelved files (*.shelf)|*.shelf"
global app # avoid recreating for every gui
app = ensureWxApp()
dlg = wx.FileDialog(None, prompt, initFilePath,
initFileName, allowed, wx.FD_SAVE)
if dlg.ShowModal() == OK:
# get names of images and their directory
outName = dlg.GetFilename()
outPath = dlg.GetDirectory()
dlg.Destroy()
# tmpApp.Destroy() # this causes an error message for some reason
fullPath = os.path.join(outPath, outName)
else:
fullPath = None
return fullPath
def fileOpenDlg(tryFilePath="",
tryFileName="",
prompt=_translate("Select file(s) to open"),
allowed=None):
"""A simple dialogue allowing read access to the file system.
:parameters:
tryFilePath: string
default file path on which to open the dialog
tryFileName: string
default file name, as suggested file
prompt: string (default "Select file to open")
can be set to custom prompts
allowed: string (available since v1.62.01)
a string to specify file filters.
e.g. "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif"
See https://docs.wxpython.org/wx.FileDialog.html
for further details
If tryFilePath or tryFileName are empty or invalid then
current path and empty names are used to start search.
If user cancels, then None is returned.
"""
if allowed is None:
allowed = ("PsychoPy Data (*.psydat)|*.psydat|"
"txt (*.txt,*.dlm,*.csv)|*.txt;*.dlm;*.csv|"
"pickled files (*.pickle, *.pkl)|*.pickle|"
"shelved files (*.shelf)|*.shelf|"
"All files (*.*)|*.*")
global app # avoid recreating for every gui
app = ensureWxApp()
dlg = wx.FileDialog(None, prompt, tryFilePath, tryFileName, allowed,
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE)
if dlg.ShowModal() == OK:
# get names of images and their directory
fullPaths = dlg.GetPaths()
else:
fullPaths = None
dlg.Destroy()
return fullPaths
| 15,521
|
Python
|
.py
| 359
| 32.649025
| 83
| 0.595798
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,416
|
generateSpec.py
|
psychopy_psychopy/psychopy/preferences/generateSpec.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generate .spec files for all OS's based on differences from baseNoArch.spec
# copies & tweaks baseNoArch.spec -> write out as platform specific .spec file
import os
write_mode = 'w'
def generateSpec(baseSpec=None):
startPath = os.getcwd()
if os.path.split(__file__)[0]:
os.chdir(os.path.split(__file__)[0])
if baseSpec is None:
# load the base prefs common to all platforms as a single string:
baseSpec = open('baseNoArch.spec').read()
warning = '''\n\n# !! This file is auto-generated and will be overwritten!!
# Edit baseNoArch.spec (all platforms) or generateSpec.py
# (platform-specific) instead.'''.replace(' ', '')
# Darwin:
darwinSpec = baseSpec.replace('psychopy prefs for ALL PLATFORMS',
'psychopy prefs for Darwin.' + warning)
darwinSpec = darwinSpec.replace("list('portaudio')",
"list('coreaudio', 'portaudio')")
darwinSpec = darwinSpec.replace("allowModuleImports = boolean(default='True')",
'')
darwinSpec = darwinSpec.replace("default='Helvetica'",
"default='Monaco'")
# no parallel port on a mac but user might create for other platform:
macDevPorts = "'0x0378', '0x03BC', '/dev/parport0', '/dev/parport1'"
darwinSpec = darwinSpec.replace("'0x0378', '0x03BC'",
macDevPorts)
# Note: Darwin key-binding prefs should be given as Ctrl+Key here,
# displayed in menus and prefs as Cmd+Key to user
with open('Darwin.spec', write_mode) as f:
f.write(darwinSpec)
# Linux and FreeBSD:
linuxSpec = baseSpec.replace('psychopy prefs for ALL PLATFORMS',
'psychopy prefs for Linux.' + warning)
linuxSpec = linuxSpec.replace('integer(6,24, default=14)',
'integer(6,24, default=12)')
linuxSpec = linuxSpec.replace("default='Helvetica'",
"default='Ubuntu Mono, DejaVu Sans Mono'")
linuxSpec = linuxSpec.replace("allowModuleImports = boolean(default='True')",
'')
linuxSpec = linuxSpec.replace("'0x0378', '0x03BC'", # parallel ports
"'/dev/parport0', '/dev/parport1'")
with open('Linux.spec', write_mode) as f:
f.write(linuxSpec)
freeBSDSpec = linuxSpec.replace('psychopy prefs for Linux.',
'psychopy prefs for FreeBSD.')
freeBSDSpec = freeBSDSpec.replace("default='Ubuntu Mono, DejaVu Sans Mono'",
"default='Palatino Linotype'")
with open('FreeBSD.spec', write_mode) as f:
f.write(freeBSDSpec)
# Windows:
winSpec = baseSpec.replace('psychopy prefs for ALL PLATFORMS',
'psychopy prefs for Windows.' + warning)
winSpec = winSpec.replace("list('portaudio')",
"list('Primary Sound','ASIO','Audigy')")
winSpec = winSpec.replace("default='Helvetica'",
"default='Lucida Console'")
winSpec = winSpec.replace('integer(6,24, default=14)',
'integer(6,24, default=10)')
winSpec = winSpec.replace('Ctrl+Q',
'Alt+F4')
with open('Windows.spec', write_mode) as f:
f.write(winSpec)
os.chdir(startPath)
if __name__ == "__main__":
generateSpec()
| 3,567
|
Python
|
.py
| 68
| 39.823529
| 83
| 0.577122
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,417
|
generateHints.py
|
psychopy_psychopy/psychopy/preferences/generateHints.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Generate hints.py file from .spec files for localization of popup hints
# on the Preference Dialog. Run this script in psychopy/preferences
# directory to generate hints.py. If you don't have write-permission
# to psychopy/preferences, the script outputs contents of hint.py to STDOUT.
import re
import sys
from psychopy import core
write_mode = 'w'
hintsFile = 'hints.py'
comments_all = []
locations_all = []
# list of .spec files to parse.
specfiles = ('baseNoArch.spec', 'Darwin.spec',
'FreeBSD.spec', 'Linux.spec', 'Windows.spec')
# list of sections to parse.
prefsDlgSections = ('[general]', '[app]', '[coder]', '[builder]',
'[hardware]', '[piloting]', '[connections]',
'[keyBindings]')
# regular expression to extract comment text (as in-lined in .spec files)
commentObj = re.compile(r'\#\s*(\S.*$)')
for specfile in specfiles:
fp = open(specfile, 'r')
inPrefsDlgSection = False
comments = []
locations = []
lineNum = 0
currentSection = ''
for line in fp:
lineNum += 1
sline = line.strip()
if sline.startswith('['): # Beginning of a new section
if sline in prefsDlgSections: # Does the section need parsing?
inPrefsDlgSection = True
currentSection = sline[:]
else:
inPrefsDlgSection = False
currentSection = ''
# Despite comment above the section header is not a hint
# of parameter, it is stored comments list. It should be
# removed from comments list.
if len(comments) > 0:
comments.pop()
continue
if inPrefsDlgSection:
if sline.startswith('#'):
m = commentObj.match(sline) # extract comment text from line.
comment = m.group(1)
# Store comment and its location. This check is necessary
# because some parameters share the same hint string.
if not comment in comments:
comments.append(comment)
locations.append([specfile, currentSection, lineNum])
# Merge comments detected from each .spec file.
for i in range(len(comments)):
if comments[i] not in comments_all:
comments_all.append(comments[i])
locations_all.append(locations[i])
# Output hint.py
try:
fp = open(hintsFile, write_mode)
fp.write('#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n')
fp.write('# This file was generated by generateHints.py.\n')
fp.write('# Following strings are used to localize hints in '
'Preference Dialog of \n# the PsychoPy application.\n')
fp.write('# Rebuild this file if comments in *.spec files '
'are modified.\n\n')
fp.write('from psychopy.localization import _translate\n\n')
except Exception:
# If hints.py could not be opend as a writable file, output to STDOUT.
fp = sys.stdout
fp.write('# Warning: could not open hints.py. STDOUT is selected.')
for i in range(len(comments_all)):
# escape backslashes
fp.write('# %s,%s,line%i\n' % tuple(locations_all[i]))
fp.write('_translate("%s")\n\n' % comments_all[i].replace(
'\\', '\\\\').replace('"', '\\"')) # escape double quotation marks
fp.close()
cmd = ['autopep8', hintsFile, '--in-place']
core.shellCall(cmd)
| 3,460
|
Python
|
.py
| 81
| 35.012346
| 78
| 0.622625
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,418
|
__init__.py
|
psychopy_psychopy/psychopy/preferences/__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).
"""Class for loading / saving prefs
"""
from pathlib import Path
from . import preferences as prefsLib
from .generateSpec import generateSpec
Preferences = prefsLib.Preferences
prefs = prefsLib.prefs
# Take note of the folder this module is in
__folder__ = Path(__file__).parent
| 513
|
Python
|
.py
| 14
| 35.214286
| 79
| 0.764706
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,419
|
preferences.py
|
psychopy_psychopy/psychopy/preferences/preferences.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import errno
import os
import sys
import platform
from pathlib import Path
from .. import __version__
from packaging.version import Version
import shutil
try:
import configobj
if (sys.version_info.minor >= 7 and
Version(configobj.__version__) < Version('5.1.0')):
raise ImportError('Installed configobj does not support Python 3.7+')
_haveConfigobj = True
except ImportError:
_haveConfigobj = False
if _haveConfigobj: # Use the "global" installation.
from configobj import ConfigObj
try:
from configobj import validate
except ImportError: # Older versions of configobj
import validate
else: # Use our contrib package if configobj is not installed or too old.
from psychopy.contrib import configobj
from psychopy.contrib.configobj import ConfigObj
from psychopy.contrib.configobj import validate
join = os.path.join
class Preferences:
"""Users can alter preferences from the dialog box in the application,
by editing their user preferences file (which is what the dialog box does)
or, within a script, preferences can be controlled like this::
import psychopy
psychopy.prefs.hardware['audioLib'] = ['ptb', 'pyo','pygame']
print(psychopy.prefs)
# prints the location of the user prefs file and all the current vals
Use the instance of `prefs`, as above, rather than the `Preferences` class
directly if you want to affect the script that's running.
"""
# Names of legacy parameters which are needed for use version
legacy = [
"winType", # 2023.1.0
"audioLib", # 2023.1.0
"audioLatencyMode", # 2023.1.0
]
def __init__(self):
super(Preferences, self).__init__()
self.userPrefsCfg = None # the config object for the preferences
self.prefsSpec = None # specifications for the above
# the config object for the app data (users don't need to see)
self.appDataCfg = None
self.general = None
self.piloting = None
self.coder = None
self.builder = None
self.connections = None
self.paths = {} # this will remain a dictionary
self.keys = {} # does not remain a dictionary
self.getPaths()
self.loadAll()
# setting locale is now handled in psychopy.localization.init
# as called upon import by the app
if self.userPrefsCfg['app']['resetPrefs']:
self.resetPrefs()
def __str__(self):
"""pretty printing the current preferences"""
strOut = "psychopy.prefs <%s>:\n" % (
join(self.paths['userPrefsDir'], 'userPrefs.cfg'))
for sectionName in ['general', 'coder', 'builder', 'connections']:
section = getattr(self, sectionName)
for key, val in list(section.items()):
strOut += " prefs.%s['%s'] = %s\n" % (
sectionName, key, repr(val))
return strOut
def resetPrefs(self):
"""removes userPrefs.cfg, does not touch appData.cfg
"""
userCfg = join(self.paths['userPrefsDir'], 'userPrefs.cfg')
try:
os.unlink(userCfg)
except Exception:
msg = "Could not remove prefs file '%s'; (try doing it manually?)"
print(msg % userCfg)
self.loadAll() # reloads, now getting all from .spec
def getPaths(self):
"""Get the paths to various directories and files used by PsychoPy.
If the paths are not found, they are created. Usually, this is only
necessary on the first run of PsychoPy. However, if the user has
deleted or moved the preferences directory, this method will recreate
those directories.
"""
# on mac __file__ might be a local path, so make it the full path
thisFileAbsPath = os.path.abspath(__file__)
prefSpecDir = os.path.split(thisFileAbsPath)[0]
dirPsychoPy = os.path.split(prefSpecDir)[0]
exePath = sys.executable
# path to Resources (icons etc)
dirApp = join(dirPsychoPy, 'app')
if os.path.isdir(join(dirApp, 'Resources')):
dirResources = join(dirApp, 'Resources')
else:
dirResources = dirApp
self.paths['psychopy'] = dirPsychoPy
self.paths['appDir'] = dirApp
self.paths['appFile'] = join(dirApp, 'PsychoPy.py')
self.paths['demos'] = join(dirPsychoPy, 'demos')
self.paths['resources'] = dirResources
self.paths['assets'] = join(dirPsychoPy, "assets")
self.paths['tests'] = join(dirPsychoPy, 'tests')
# path to libs/frameworks
if 'PsychoPy.app/Contents' in exePath:
self.paths['libs'] = exePath.replace("MacOS/python", "Frameworks")
else:
self.paths['libs'] = '' # we don't know where else to look!
if not Path(self.paths['appDir']).is_dir():
# if there isn't an app folder at all then this is a lib-only psychopy
# so don't try to load app prefs etc
NO_APP = True
if sys.platform == 'win32':
self.paths['prefsSpecFile'] = join(prefSpecDir, 'Windows.spec')
self.paths['userPrefsDir'] = join(os.environ['APPDATA'],
'psychopy3')
else:
self.paths['prefsSpecFile'] = join(prefSpecDir,
platform.system() + '.spec')
self.paths['userPrefsDir'] = join(os.environ['HOME'],
'.psychopy3')
# directory for files created by the app at runtime needed for operation
self.paths['userCacheDir'] = join(self.paths['userPrefsDir'], 'cache')
# paths in user directory to create/check write access
userPrefsPaths = (
'userPrefsDir', # root dir
'themes', # define theme path
'fonts', # find / copy fonts
'packages', # packages and plugins
'configs', # config files for plugins
'cache', # cache for downloaded and other temporary files
)
# build directory structure inside user directory
for userPrefPath in userPrefsPaths:
# define path
if userPrefPath != 'userPrefsDir': # skip creating root, just check
self.paths[userPrefPath] = join(
self.paths['userPrefsDir'],
userPrefPath)
# avoid silent fail-to-launch-app if bad permissions:
try:
os.makedirs(self.paths[userPrefPath])
except OSError as err:
if err.errno != errno.EEXIST:
raise
# root site-packages directory for user-installed packages and add it
userPkgRoot = Path(self.paths['packages'])
# Package paths for custom user site-packages, these should be compliant
# with platform specific conventions.
if sys.platform == 'win32':
pyDirName = "Python" + sys.winver.replace(".", "")
userPackages = userPkgRoot / pyDirName / "site-packages"
userInclude = userPkgRoot / pyDirName / "Include"
userScripts = userPkgRoot / pyDirName / "Scripts"
elif sys.platform == 'darwin' and sys._framework: # macos + framework
pyVersion = sys.version_info
pyDirName = "python{}.{}".format(pyVersion[0], pyVersion[1])
userPackages = userPkgRoot / "lib" / "python" / "site-packages"
userInclude = userPkgRoot / "include" / pyDirName
userScripts = userPkgRoot / "bin"
else: # posix (including linux and macos without framework)
pyVersion = sys.version_info
pyDirName = "python{}.{}".format(pyVersion[0], pyVersion[1])
userPackages = userPkgRoot / "lib" / pyDirName / "site-packages"
userInclude = userPkgRoot / "include" / pyDirName
userScripts = userPkgRoot / "bin"
# populate directory structure for user-installed packages
if not userPackages.is_dir():
userPackages.mkdir(parents=True)
if not userInclude.is_dir():
userInclude.mkdir(parents=True)
if not userScripts.is_dir():
userScripts.mkdir(parents=True)
# add paths from plugins/packages (installed by plugins manager)
self.paths['userPackages'] = userPackages
self.paths['userInclude'] = userInclude
self.paths['userScripts'] = userScripts
# Get dir for base and user themes
baseThemeDir = Path(self.paths['appDir']) / "themes" / "spec"
userThemeDir = Path(self.paths['themes'])
# Check what version user themes were last updated in
if (userThemeDir / "last.ver").is_file():
with open(userThemeDir / "last.ver", "r") as f:
lastVer = Version(f.read())
else:
# if no version available, assume it was the first version to have themes
lastVer = Version("2020.2.0")
# If version has changed since base themes last copied, they need updating
updateThemes = lastVer < Version(__version__)
# Copy base themes to user themes folder if missing or need update
for file in baseThemeDir.glob("*.json"):
if updateThemes or not (Path(self.paths['themes']) / file.name).is_file():
shutil.copyfile(
file,
Path(self.paths['themes']) / file.name
)
def loadAll(self):
"""Load the user prefs and the application data
"""
self._validator = validate.Validator()
# note: self.paths['userPrefsDir'] gets set in loadSitePrefs()
self.paths['appDataFile'] = join(
self.paths['userPrefsDir'], 'appData.cfg')
self.paths['userPrefsFile'] = join(
self.paths['userPrefsDir'], 'userPrefs.cfg')
# If PsychoPy is tucked away by Py2exe in library.zip, the preferences
# file cannot be found. This hack is an attempt to fix this.
libzip = "\\library.zip\\psychopy\\preferences\\"
if libzip in self.paths["prefsSpecFile"]:
self.paths["prefsSpecFile"] = self.paths["prefsSpecFile"].replace(
libzip, "\\resources\\")
self.userPrefsCfg = self.loadUserPrefs()
self.appDataCfg = self.loadAppData()
self.validate()
# simplify namespace
self.general = self.userPrefsCfg['general']
self.app = self.userPrefsCfg['app']
self.coder = self.userPrefsCfg['coder']
self.builder = self.userPrefsCfg['builder']
self.hardware = self.userPrefsCfg['hardware']
self.piloting = self.userPrefsCfg['piloting']
self.connections = self.userPrefsCfg['connections']
self.appData = self.appDataCfg
# keybindings:
self.keys = self.userPrefsCfg['keyBindings']
def loadUserPrefs(self):
"""load user prefs, if any; don't save to a file because doing so
will break easy_install. Saving to files within the psychopy/ is
fine, eg for key-bindings, but outside it (where user prefs will
live) is not allowed by easy_install (security risk)
"""
self.prefsSpec = ConfigObj(self.paths['prefsSpecFile'],
encoding='UTF8', list_values=False)
# check/create path for user prefs
if not os.path.isdir(self.paths['userPrefsDir']):
try:
os.makedirs(self.paths['userPrefsDir'])
except Exception:
msg = ("Preferences.py failed to create folder %s. Settings"
" will be read-only")
print(msg % self.paths['userPrefsDir'])
# then get the configuration file
cfg = ConfigObj(self.paths['userPrefsFile'],
encoding='UTF8', configspec=self.prefsSpec)
# cfg.validate(self._validator, copy=False) # merge then validate
# don't cfg.write(), see explanation above
return cfg
def saveUserPrefs(self):
"""Validate and save the various setting to the appropriate files
(or discard, in some cases)
"""
self.validate()
if not os.path.isdir(self.paths['userPrefsDir']):
os.makedirs(self.paths['userPrefsDir'])
self.userPrefsCfg.write()
def loadAppData(self):
"""Fetch app data config (unless this is a lib-only installation)
"""
appDir = Path(self.paths['appDir'])
if not appDir.is_dir(): # if no app dir this may be just lib install
return {}
# fetch appData too against a config spec
appDataSpec = ConfigObj(join(self.paths['appDir'], 'appData.spec'),
encoding='UTF8', list_values=False)
cfg = ConfigObj(self.paths['appDataFile'],
encoding='UTF8', configspec=appDataSpec)
resultOfValidate = cfg.validate(self._validator,
copy=True,
preserve_errors=True)
self.restoreBadPrefs(cfg, resultOfValidate)
# force favComponent level values to be integers
if 'favComponents' in cfg['builder']:
for key in cfg['builder']['favComponents']:
_compKey = cfg['builder']['favComponents'][key]
cfg['builder']['favComponents'][key] = int(_compKey)
return cfg
def saveAppData(self):
"""Save the various setting to the appropriate files
(or discard, in some cases)
"""
# copy means all settings get saved:
self.appDataCfg.validate(self._validator, copy=True)
if not os.path.isdir(self.paths['userPrefsDir']):
os.makedirs(self.paths['userPrefsDir'])
self.appDataCfg.write()
def validate(self):
"""Validate (user) preferences and reset invalid settings to defaults
"""
result = self.userPrefsCfg.validate(self._validator, copy=True)
self.restoreBadPrefs(self.userPrefsCfg, result)
def restoreBadPrefs(self, cfg, result):
"""result = result of validate
"""
if result == True:
return
vtor = validate.Validator()
for sectionList, key, _ in configobj.flatten_errors(cfg, result):
if key is not None:
_secList = ', '.join(sectionList)
val = cfg.configspec[_secList][key]
cfg[_secList][key] = vtor.get_default_value(val)
else:
msg = "Section [%s] was missing in file '%s'"
print(msg % (', '.join(sectionList), cfg.filename))
prefs = Preferences()
| 14,860
|
Python
|
.py
| 312
| 36.919872
| 86
| 0.607515
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,420
|
hints.py
|
psychopy_psychopy/psychopy/preferences/hints.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file was generated by generateHints.py.
# Following strings are used to localize hints in Preference Dialog of
# the PsychoPy application.
# Rebuild this file if comments in *.spec files are modified.
from psychopy.localization import _translate
# baseNoArch.spec,[general],line25
_translate("the default units for windows and visual stimuli")
# baseNoArch.spec,[general],line27
_translate("full screen is best for accurate timing")
# baseNoArch.spec,[general],line29
_translate("enable subjects to use the mouse and GUIs during experiments")
# baseNoArch.spec,[general],line31
_translate("'version' is for internal usage, not for the user")
# baseNoArch.spec,[general],line33
_translate("Add paths here to your custom Python modules")
# baseNoArch.spec,[general],line35
_translate("path to flac (lossless audio compression) on this operating system")
# baseNoArch.spec,[general],line37
_translate("Shutdown keys, following the pyglet naming scheme.")
# baseNoArch.spec,[general],line39
_translate("Modifier keys for shutdown keys")
# baseNoArch.spec,[general],line41
_translate("What to do if gamma-correction not possible")
# baseNoArch.spec,[general],line43
_translate("Add plugin names here to load when a PsychoPy session starts.")
# baseNoArch.spec,[general],line45
_translate("Google Cloud Platform key, required for the audio transcription using Google Speech Recognition. Specified as a path to a JSON file containing the key data.")
# baseNoArch.spec,[general],line47
_translate("LEGACY: which system to use as a backend for drawing")
# baseNoArch.spec,[general],line50
_translate("display tips when starting PsychoPy")
# baseNoArch.spec,[app],line52
_translate("what windows to display when PsychoPy starts")
# baseNoArch.spec,[app],line54
_translate("reset preferences to defaults on next restart of PsychoPy")
# baseNoArch.spec,[app],line56
_translate("save any unsaved preferences before closing the window")
# baseNoArch.spec,[app],line58
_translate("enable features for debugging PsychoPy itself, including unit-tests")
# baseNoArch.spec,[app],line60
_translate("language to use in menus etc; not all translations are available. Select a value, then restart the app.")
# baseNoArch.spec,[app],line62
_translate(
"Show an error dialog when PsychoPy encounters an unhandled internal error.")
# baseNoArch.spec,[app],line64
_translate("Theme")
# baseNoArch.spec,[app],line66
_translate("Show / hide splash screen")
# baseNoArch.spec,[app],line68
_translate(
"open Coder files as read-only (allows running without accidental changes)")
# baseNoArch.spec,[app],line71
_translate("a list of font names; the first one found on the system will be used")
# baseNoArch.spec,[coder],line73
_translate("Font size (in pts) takes an integer between 6 and 24")
# baseNoArch.spec,[coder],line75
_translate("Spacing between lines")
# baseNoArch.spec,[coder],line79
_translate("Long line edge guide, specify zero to disable")
# baseNoArch.spec,[coder],line83
_translate("Set the source assistant panel to be visible by default")
# baseNoArch.spec,[coder],line85
_translate("Set the output/shell to be visible by default")
# baseNoArch.spec,[coder],line87
_translate(
"Show code completion suggestion and calltips automatically when typing.")
# baseNoArch.spec,[coder],line89
_translate("reload previously opened files after start")
# baseNoArch.spec,[coder],line91
_translate("for coder shell window, which shell to use")
# baseNoArch.spec,[coder],line93
_translate("whether to automatically reload a previously open experiment")
# baseNoArch.spec,[coder],line95
_translate("Default to when writing code components")
# baseNoArch.spec,[coder],line98
_translate(
"if False will create scripts with an 'easier' but more cluttered namespace")
# baseNoArch.spec,[builder],line100
_translate("folder names for custom components; expects a comma-separated list")
# baseNoArch.spec,[builder],line102
_translate("Only show components which work in...")
# baseNoArch.spec,[builder],line104
_translate("a list of components to hide (eg, because you never use them)")
# baseNoArch.spec,[builder],line106
_translate("Abbreviate long component names to maximise timeline space?")
# baseNoArch.spec,[builder],line108
_translate("where the Builder demos are located on this computer (after unpacking)")
# baseNoArch.spec,[builder],line110
_translate(
"name of the folder where subject data should be saved (relative to the script)")
# baseNoArch.spec,[builder],line112
_translate("Panels arrangement: Should Flow be on the top or bottom, and should Components be on the left or right?")
# baseNoArch.spec,[builder],line114
_translate("Display text in a floating window that describes the experiment")
# baseNoArch.spec,[builder],line116
_translate("Upper limit on how many components can be in favorites")
# baseNoArch.spec,[builder],line118
_translate("Ask for confirmation when closing a routine tab.")
# baseNoArch.spec,[builder],line120
_translate("LEGACY: choice of audio library")
# baseNoArch.spec,[builder],line122
_translate(
"LEGACY: latency mode for PsychToolbox audio (3 is good for most applications. See")
# baseNoArch.spec,[builder],line124
_translate("audio driver to use")
# baseNoArch.spec,[builder],line127
_translate("audio device to use (if audioLib allows control)")
# baseNoArch.spec,[hardware],line129
_translate("a list of parallel ports")
# baseNoArch.spec,[hardware],line131
_translate("The name of the Qmix pump configuration to use")
# baseNoArch.spec,[hardware],line133
_translate("Prevent the experiment from being fullscreen when piloting")
# baseNoArch.spec,[hardware],line135
_translate("How much output to include in the log files when piloting ('error' is fewest messages, 'debug' is most)")
# baseNoArch.spec,[hardware],line137
_translate("Show an orange border around the window when in piloting mode")
# baseNoArch.spec,[hardware],line139
_translate("Prevent experiment from enabling rush mode when piloting")
# baseNoArch.spec,[hardware],line142
_translate("the http proxy for usage stats and auto-updating; format is host: port")
# baseNoArch.spec,[piloting],line144
_translate(
"override the above proxy settings with values found in the environment (if possible)")
# baseNoArch.spec,[piloting],line146
_translate("allow PsychoPy to send anonymous usage stats; please allow if possible, it helps PsychoPy's development")
# baseNoArch.spec,[piloting],line148
_translate("allow PsychoPy to check for new features and bug fixes")
# baseNoArch.spec,[piloting],line150
_translate("max time to wait for a connection response")
# baseNoArch.spec,[piloting],line153
_translate("open an existing file")
# baseNoArch.spec,[connections],line155
_translate("start a new experiment or script")
# baseNoArch.spec,[connections],line157
_translate("save a Builder or Coder file")
# baseNoArch.spec,[connections],line159
_translate("save a Builder or Coder file under a new name")
# baseNoArch.spec,[connections],line161
_translate("Coder: print the file")
# baseNoArch.spec,[connections],line163
_translate("close the Builder or Coder window")
# baseNoArch.spec,[connections],line166
_translate("end the application (PsychoPy)")
# baseNoArch.spec,[keyBindings],line168
_translate("open the preferences dialog")
# baseNoArch.spec,[keyBindings],line170
_translate("export Builder experiment to HTML")
# baseNoArch.spec,[keyBindings],line172
_translate("Coder: cut")
# baseNoArch.spec,[keyBindings],line174
_translate("Coder: copy")
# baseNoArch.spec,[keyBindings],line176
_translate("Coder: paste")
# baseNoArch.spec,[keyBindings],line178
_translate("Coder: duplicate")
# baseNoArch.spec,[keyBindings],line180
_translate("Coder: indent code by one level (4 spaces)")
# baseNoArch.spec,[keyBindings],line182
_translate("Coder: reduce indentation by one level (4 spaces)")
# baseNoArch.spec,[keyBindings],line184
_translate("Coder: indent to fit python syntax")
# baseNoArch.spec,[keyBindings],line187
_translate("Coder: find")
# baseNoArch.spec,[keyBindings],line189
_translate("Coder: find again")
# baseNoArch.spec,[keyBindings],line191
_translate("Coder: undo")
# baseNoArch.spec,[keyBindings],line193
_translate("Coder: redo")
# baseNoArch.spec,[keyBindings],line195
_translate("Coder: add a # to the start of the line(s)")
# baseNoArch.spec,[keyBindings],line197
_translate("Coder: remove # from start of line(s)")
# baseNoArch.spec,[keyBindings],line199
_translate("Coder: add or remove # from start of line(s)")
# baseNoArch.spec,[keyBindings],line201
_translate("Coder: fold this block of code")
# baseNoArch.spec,[keyBindings],line203
_translate("Coder: increase font size this block of code")
# baseNoArch.spec,[keyBindings],line205
_translate("Coder: decrease font size this block of code")
# baseNoArch.spec,[keyBindings],line207
_translate("Coder: check for basic syntax errors")
# baseNoArch.spec,[keyBindings],line209
_translate(
"convert a Builder .psyexp script into a python script and open it in the Coder")
# baseNoArch.spec,[keyBindings],line211
_translate("launch a script, Builder or Coder, or run unit-tests")
# baseNoArch.spec,[keyBindings],line213
_translate("attempt to interrupt and halt a running script")
# baseNoArch.spec,[keyBindings],line215
_translate("Coder: show / hide white-space dots")
# baseNoArch.spec,[keyBindings],line217
_translate("Coder: show / hide end of line characters")
# baseNoArch.spec,[keyBindings],line219
_translate("Coder: show / hide indentation level lines")
# baseNoArch.spec,[keyBindings],line222
_translate("Builder: create a new routine")
# baseNoArch.spec,[keyBindings],line224
_translate("Builder: copy an existing routine")
# baseNoArch.spec,[keyBindings],line226
_translate("Builder: paste the copied routine")
# baseNoArch.spec,[keyBindings],line230
_translate("Builder: paste the copied component")
# baseNoArch.spec,[keyBindings],line233
_translate("Builder: find")
# baseNoArch.spec,[keyBindings],line235
_translate("Coder: show / hide the output panel")
# baseNoArch.spec,[keyBindings],line237
_translate("Builder: rename an existing routine")
# baseNoArch.spec,[keyBindings],line240
_translate("switch between windows")
# baseNoArch.spec,[keyBindings],line242
_translate("increase display size in Flow")
# baseNoArch.spec,[keyBindings],line244
_translate("decrease display size in Flow")
# baseNoArch.spec,[keyBindings],line246
_translate("increase display size of Routines")
# baseNoArch.spec,[keyBindings],line248
_translate("decrease display size of Routines")
# baseNoArch.spec,[keyBindings],line250
_translate("show or hide the readme (info) for this experiment if possible")
# baseNoArch.spec,[keyBindings],line252
_translate("Projects: Log in to pavlovia")
# baseNoArch.spec,[keyBindings],line254
_translate("Projects: Log in to OSF")
# baseNoArch.spec,[keyBindings],line256
_translate("Projects: Sync project")
# baseNoArch.spec,[keyBindings],line258
_translate("Projects: Find projects")
# baseNoArch.spec,[keyBindings],line260
_translate("Projects: Open project")
# baseNoArch.spec,[keyBindings],line262
_translate("Projects: Create new project")
| 11,234
|
Python
|
.py
| 237
| 45.78903
| 170
| 0.789416
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,421
|
test_Installation.py
|
psychopy_psychopy/psychopy/tests/test_Installation.py
|
import sys
import pytest
def test_essential_imports():
import wx
import numpy
import scipy
import matplotlib
#import pygame # soft dependency only
import pyglet
import openpyxl
import pandas
def test_extra_imports():
# only Jon needs to run this, so test first if you are him!
import os
if sys.platform=='win32':
import win32api
user=win32api.GetUserName()
else:
import pwd
user = pwd.getpwuid(os.getuid()).pw_name
if user not in ['jwp','lpzjwp']:
pytest.skip('Testing extra imports is only needed for building Standalone distributions')
#OK, it's Jon , so run it
import bidi #for right-left languages
import yaml, msgpack, gevent
import psychopy_ext
import zmq, jinja2, jsonschema
import psychopy_ext, pandas, seaborn
#avbin
import pyglet
import serial
import pyo
#specific hardware libs
import egi_pynetstation
| 958
|
Python
|
.py
| 34
| 22.941176
| 97
| 0.695652
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,422
|
run.py
|
psychopy_psychopy/psychopy/tests/run.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
import subprocess
thisDir,filename = os.path.split(os.path.abspath(__file__))
os.chdir(thisDir)
argv = sys.argv
if argv[0].endswith('run.py'):#that's this script
argv.pop(0) # remove run.py
#create extra args and then append main args to them
#if the user specifies a directory that should come last
extraArgs = []
#if user didn't specify a traceback deetail level then set to be short
overrideTraceBack=True
for thisArg in argv:
if thisArg.startswith('--tb='):
overrideTraceBack=False
if overrideTraceBack:
extraArgs.append('--tb=short')
#always add doctests if not included
if '--doctest-modules' not in argv:
extraArgs.append('--doctest-modules') #doctests
#add coverage if requested
if 'cover' in argv:
argv.remove('cover')
extraArgs.extend(['--cov','psychopy'])
#use the pytest module itself if available
#otherwise use the precompiled pytest script
try:
import pytest
havePytest=True
except ImportError:
havePytest=False
extraArgs.extend(argv)
if havePytest:
command = 'py.test ' + ' '.join(extraArgs)
else:
command = '%s -u runPytest.py ' %(sys.executable)
command = command + ' ' + ' '.join(extraArgs)
print(command)
subprocess.Popen(command, shell=True)
| 1,290
|
Python
|
.py
| 41
| 28.878049
| 70
| 0.737097
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,423
|
utils.py
|
psychopy_psychopy/psychopy/tests/utils.py
|
import sys
from os.path import abspath, basename, dirname, isfile, isdir, join as pjoin
import os.path
from pathlib import Path
import shutil
import numpy as np
import io
from psychopy import logging, colors
from psychopy.tools import systemtools
try:
from PIL import Image
except ImportError:
import Image
import pytest
# boolean indicating whether tests are running in a VM
RUNNING_IN_VM = systemtools.isVM_CI() is not None
# define the path where to find testing data
# so tests could be ran from any location
TESTS_PATH = abspath(dirname(__file__))
TESTS_DATA_PATH = pjoin(TESTS_PATH, 'data')
TESTS_FAILS_PATH = pjoin(TESTS_PATH, 'fails', sys.platform)
TESTS_FONT = pjoin(TESTS_DATA_PATH, 'DejaVuSerif.ttf')
# Make sure all paths exist
if not isdir(TESTS_FAILS_PATH):
os.makedirs(TESTS_FAILS_PATH)
# Some regex shorthand
_q = r"[\"']" # quotes
_lb = r"[\[\(]" # left bracket
_rb = r"[\]\)]" # right bracket
_d = r"\$" # dollar (escaped for re)
_sl = r"\\\\" # back slash
def getFailFilenames(fileName, tag=""):
"""
Create variant of given filename for a failed test
Parameters
==========
fileName : str or Path
Path to original file
tag : str
Optional tag to append to the file stem
Returns
==========
str
Path to the local copy
str
Path to the copy of the exemplar in the fails folder
"""
# Path-ise filename
fileName = Path(fileName)
# Create new stem
if tag:
tag = "_" + tag
stem = fileName.stem + tag
# Construct new filename for local copy
localFileName = pjoin(TESTS_FAILS_PATH, stem + "_local" + fileName.suffix)
# Construct new filename for exemplar copy
exemplarFileName = pjoin(TESTS_FAILS_PATH, fileName.stem + fileName.suffix)
return localFileName, exemplarFileName
def checkSyntax(exp, targets=("PsychoPy", "PsychoJS")):
"""
Check that a given Experiment object writes valid syntax.
Parameters
----------
exp : psychopy.experiment
Experiment to check syntax for
targets : list[str] or tuple[str]
Languages to check syntax in ("PsychoPy" and/or "PsychoJS")
Raises
------
SyntaxError
Will raise a SyntaxError if there's invalid syntax, and will store the broken script in
tests/fails
"""
# only test Python if Component is supposed to work locally
if "PsychoPy" in targets:
# temp file to save scripts to
file = Path(TESTS_FAILS_PATH) / f"test_{exp.name}_syntax_errors_script.py"
# write script
script = exp.writeScript(target="PsychoPy")
# compile (will error if there's syntax errors)
try:
compile(script, str(file), "exec")
except SyntaxError as err:
# save script to fails folder
file.write_text(script, encoding="utf-8")
# raise error
raise err
# only test JS if Component is supposed to work online
if "PsychoJS" in targets:
# temp file to save scripts to
file = Path(TESTS_FAILS_PATH) / f"test_{exp.name}_syntax_errors_script.js"
# write script
script = exp.writeScript(target="PsychoJS")
# parse in esprima and raise any errors
import esprima
try:
esprima.parseModule(script)
except esprima.Error as err:
# save script to fails folder
file.write_text(script, encoding="utf-8")
# raise error
raise SyntaxError(err.message)
def compareScreenshot(fileName, win, tag="", crit=5.0):
"""Compare the current back buffer of the given window with the file
Screenshots are stored and compared against the files under path
kept in TESTS_DATA_PATH. Thus specify relative path to that
directory
"""
#if we start this from a folder below run.py the data folder won't be found
fileName = pjoin(TESTS_DATA_PATH, fileName)
#get the frame from the window
win.getMovieFrame(buffer='back')
frame=win.movieFrames[-1]
win.movieFrames=[]
#if the file exists run a test, if not save the file
if not isfile(fileName):
frame = frame.resize((int(frame.size[0]/2), int(frame.size[1]/2)),
resample=Image.LANCZOS)
frame.save(fileName, optimize=1)
pytest.skip("Created %s" % basename(fileName))
else:
expected = Image.open(fileName)
expDat = np.array(expected.getdata())
imgDat = np.array(frame.getdata())
# for retina displays the frame data is 4x bigger than expected
if win.useRetina and imgDat.shape[0] == expDat.shape[0]*4:
frame = frame.resize(expected.size, resample=Image.LANCZOS)
imgDat = np.array(frame.getdata())
crit += 5 # be more relaxed because of the interpolation
rms = np.std(imgDat-expDat)
localFileName, exemplarFileName = getFailFilenames(fileName, tag=tag)
if rms >= crit/2:
#there was SOME discrepancy
logging.warning('PsychoPyTests: RMS=%.3g at threshold=%3.g'
% (rms, crit))
if not rms<crit: #don't do `if rms>=crit because that doesn't catch rms=nan
# If test fails, save local copy and copy of exemplar to fails folder
frame.save(localFileName, optimize=1)
expected.save(exemplarFileName, optimize=1)
logging.warning('PsychoPyTests: Saving local copy into %s' % localFileName)
assert rms<crit, \
"RMS=%.3g at threshold=%.3g. Local copy in %s" % (rms, crit, localFileName)
def compareTextFiles(pathToActual, pathToCorrect, delim=None,
encoding='utf-8-sig', tolerance=None):
"""Compare the text of two files, ignoring EOL differences,
and save a copy if they differ
State a tolerance, or percentage of errors allowed,
to account for differences in version numbers, datetime, etc
"""
if not os.path.isfile(pathToCorrect):
logging.warning('There was no comparison ("correct") file available, for path "{pathToActual}"\n'
'\t\t\tSaving current file as the comparison: {pathToCorrect}'
.format(pathToActual=pathToActual,
pathToCorrect=pathToCorrect))
shutil.copyfile(pathToActual, pathToCorrect)
raise IOError("File not found") # deliberately raise an error to see the warning message, but also to create file
allowLines = 0
nLinesMatch = True
if delim is None:
if pathToCorrect.endswith('.csv'):
delim=','
elif pathToCorrect.endswith(('.dlm', '.tsv')):
delim='\t'
try:
# we have the necessary file
with io.open(pathToActual, 'r', encoding='utf-8-sig', newline=None) as f:
txtActual = f.readlines()
with io.open(pathToCorrect, 'r', encoding='utf-8-sig', newline=None) as f:
txtCorrect = f.readlines()
if tolerance is not None:
# Set number of lines allowed to fail
allowLines = round((tolerance * len(txtCorrect)) / 100, 0)
# Check number of lines per document for equality
nLinesMatch = len(txtActual) == len(txtCorrect)
assert nLinesMatch
errLines = []
for lineN in range(len(txtActual)):
if delim is None:
lineActual = txtActual[lineN]
lineCorrect = txtCorrect[lineN]
# just compare the entire line
if not lineActual == lineCorrect:
errLines.append({'actual':lineActual, 'correct':lineCorrect})
assert len(errLines) <= allowLines
else: # word by word instead
lineActual=txtActual[lineN].split(delim)
lineCorrect=txtCorrect[lineN].split(delim)
for wordN in range(len(lineActual)):
wordActual=lineActual[wordN]
wordCorrect=lineCorrect[wordN]
try:
wordActual=float(wordActual.lstrip('"[').strip(']"'))
wordCorrect=float(wordCorrect.lstrip('"[').strip(']"'))
# its not a whole well-formed list because .split(delim)
isFloat=True
except Exception:#stick with simple text if not a float value
isFloat=False
pass
if isFloat:
#to a default of 8 dp?
assert np.allclose(wordActual,wordCorrect), "Numeric values at (%i,%i) differ: %f != %f " \
%(lineN, wordN, wordActual, wordCorrect)
else:
if wordActual!=wordCorrect:
print('actual:')
print(repr(txtActual[lineN]))
print(lineActual)
print('expected:')
print(repr(txtCorrect[lineN]))
print(lineCorrect)
assert wordActual==wordCorrect, "Values at (%i,%i) differ: %s != %s " \
%(lineN, wordN, repr(wordActual), repr(wordCorrect))
except AssertionError as err:
pathToLocal, pathToExemplar = getFailFilenames(pathToCorrect)
# Set assertion type
if not nLinesMatch: # Fail if number of lines not equal
msg = "{} has the wrong number of lines".format(pathToActual)
elif len(errLines) < allowLines: # Fail if tolerance reached
msg = 'Number of differences in {failed} exceeds the {tol}% tolerance'.format(failed=pathToActual,
tol=tolerance or 0)
else:
shutil.copyfile(pathToActual, pathToLocal)
shutil.copyfile(pathToCorrect, pathToExemplar)
msg = "txtActual != txtCorr: Saving local copy to {}".format(pathToLocal)
logging.error(msg)
raise AssertionError(err)
def compareXlsxFiles(pathToActual, pathToCorrect):
from openpyxl.reader.excel import load_workbook
# Make sure the file is there
expBook = load_workbook(pathToCorrect)
actBook = load_workbook(pathToActual)
error=None
for wsN, expWS in enumerate(expBook.worksheets):
actWS = actBook.worksheets[wsN]
for key, expVal in list(expWS._cells.items()):
actVal = actWS._cells[key].value
expVal = expVal.value
# intercept lists-of-floats, which might mismatch by rounding error
isListableFloatable = False
if u"{}".format(expVal).startswith('['):
expValList = eval(u"{}".format(expVal))
try:
expVal = np.array(expValList, dtype=float)
actVal = np.array(eval(u"{}".format(actVal)),
dtype=float) # should go through if expVal does...
isListableFloatable = True
except Exception:
pass # non-list+float-able at this point = default
#determine whether there will be errors
try:
# convert to float if possible and compare with a reasonable
# (default) precision
expVal = float(expVal)
isFloatable=True
except Exception:
isFloatable=False
if isListableFloatable:
if not np.allclose(expVal, actVal):
error = "l+f Cell %s: %f != %f" %(key, expVal, actVal)
break
elif isFloatable and abs(expVal-float(actVal))>0.0001:
error = "f Cell %s: %f != %f" %(key, expVal, actVal)
break
elif not isFloatable and expVal!=actVal:
error = "nf Cell %s: %s != %s" %(key, expVal, actVal)
break
if error:
pathToLocal, pathToExemplar = getFailFilenames(pathToCorrect)
shutil.copyfile(pathToActual, pathToLocal)
shutil.copyfile(pathToCorrect, pathToExemplar)
logging.warning("xlsxActual!=xlsxCorr: Saving local copy to %s" % pathToLocal)
raise IOError(error)
def comparePixelColor(screen, color, coord=(0, 0), context="color_comparison"):
ogCoord = coord
# Adjust for retina
coord = tuple(int(c * screen.getContentScaleFactor()) for c in ogCoord)
if hasattr(screen, 'getMovieFrame'): # check it is a Window class (without importing visual in this file)
# If given a window, get frame from window
screen.getMovieFrame(buffer='back')
frame = screen.movieFrames[-1]
screen.movieFrames = []
elif isinstance(screen, str):
# If given a filename, get frame from file
frame = Image.open(screen)
else:
# If given anything else, throw error
raise TypeError("Function comparePixelColor expected first input of type psychopy.visual.Window or str, received %s" % (type(screen)))
frameArr = np.array(frame)
# If given a Color object, convert to rgb255 (this is what PIL uses)
if isinstance(color, colors.Color):
color = color.rgb255
color = np.array(color)
pixCol = frameArr[coord]
# Compare observed color to desired color
closeEnough = True
for i in range(min(pixCol.size, color.size)):
closeEnough = closeEnough and abs(pixCol[i] - color[i]) <= 1 # Allow for 1/255 lenience due to rounding up/down in rgb255
# Assert
cond = all(c for c in color == pixCol) or closeEnough
if not cond:
frame.save(Path(TESTS_FAILS_PATH) / (context + ".png"))
raise AssertionError(f"Pixel color {pixCol} at {ogCoord} (x{screen.getContentScaleFactor()}) not equal to target color {color}")
def forceBool(value, handler=any):
"""
Force a value to a boolean, accounting for the possibility that it is an
array of booleans.
Parameters
----------
value
Value to force
mode : str
Method to apply to values which fail builtin `bool` function, e.g. `any`
or `all` for boolean arrays.
Returns
-------
bool
"""
try:
# attempt to make bool
value = bool(value)
except ValueError:
# if this fails,
value = handler(value)
return value
| 14,464
|
Python
|
.py
| 324
| 34.407407
| 142
| 0.611967
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,424
|
__init__.py
|
psychopy_psychopy/psychopy/tests/__init__.py
|
from psychopy.tools import systemtools
# for skip_under we need pytest but we don't want that to be a requirement for normal use
try:
import pytest
# some pytest decorators for those conditions
skip_under_travis = pytest.mark.skipif(systemtools.isVM_CI() == 'travis',
reason="Cannot run that test under Travis")
skip_under_ghActions = pytest.mark.skipif(systemtools.isVM_CI() == 'github',
reason="Cannot run that test on GitHub Actions")
skip_under_vm = pytest.mark.skipif(bool(systemtools.isVM_CI()),
reason="Cannot run that test on a virtual machine")
except ImportError:
def no_op(fn, reason=None):
return fn
skip_under_travis = no_op
skip_under_ghActions = no_op
skip_under_vm = no_op
def requires_plugin(plugin):
"""
Decorator to skip test if a particular plugin is not installed.
Parameters
----------
plugin : str
Name of plugin which must be installed in other for decorated test to run
Returns
-------
pytest.mark with condition on which to run the test
Examples
--------
```
@requires_plugin("psychopy-visionscience")
def test_EnvelopeGrating():
win = visual.Window()
stim = visual.EnvelopeGrating(win)
stim.draw()
win.flip()
```
"""
from psychopy import plugins
return pytest.mark.skipif(plugin not in plugins.listPlugins(), reason="Cannot run that test on a virtual machine")
| 1,611
|
Python
|
.py
| 40
| 31.2
| 118
| 0.619565
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,425
|
test_codecov.py
|
psychopy_psychopy/psychopy/tests/test_codecov.py
|
import requests
from . import utils
from pathlib import Path
def test_valid_yaml():
"""
Send the codecov YAML file to CodeCov to check that it's valid, meaning we find out in the
test suite if it's invalid rather than finding out when it tries to run.
"""
# ensure data type
headers = {'Content-Type': "application/x-www-form-urlencoded"}
# navigate to codecov file
file = Path(utils.TESTS_PATH).parent.parent / "codecov.yml"
# create bytes object for yaml file
data = open(str(file), "rb")
try:
resp = requests.post("https://codecov.io/validate", headers=headers, data=data, timeout=5)
except TimeoutError:
resp = {}
resp.status_code = 400
resp.text = "Could not connect to Codecov, timed out after 5s"
assert resp.status_code == 200, (
f"`codecov.yaml` is invalid or could not be validated. Message received from Codecov:\n"
f"{resp.text}"
)
| 953
|
Python
|
.py
| 24
| 34.166667
| 98
| 0.674242
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,426
|
test_builder_demos.py
|
psychopy_psychopy/psychopy/tests/test_demos/test_builder_demos.py
|
from pathlib import Path
from psychopy.demos import builder
from psychopy import experiment
from psychopy.experiment.routines import Routine
from psychopy.experiment.components.unknown import UnknownComponent
from psychopy.experiment.routines.unknown import UnknownRoutine
def test_plugin_components_indicated():
"""
Test that all components in Builder demos which come from plugins are marked as being from plugins.
"""
# blank experiment for reading files
exp = experiment.Experiment()
# root Builder demos folder
demosDir = Path(builder.__file__).parent
# for all psyexp files in builder demos folder...
for file in demosDir.glob("**/*.psyexp"):
# load experiment
exp.loadFromXML(str(file))
# get all elements (Components and StandaloneRoutines) in the experiment
emts = []
for rt in exp.routines.values():
if isinstance(rt, Routine):
for comp in rt:
emts.append(comp)
else:
emts.append(rt)
# check that each element is known
for emt in emts:
assert not isinstance(emt, (UnknownComponent, UnknownRoutine)), (
f"Component/Routine `{emt.name}` ({type(emt).__name__}) from `{file.relative_to(demosDir)}` is "
f"not known to PsychoPy and experiment file did not indicate that it's from a plugin."
)
def test_pilot_mode():
"""
Checks that all Builder demos are saved in Pilot mode.
"""
# root Builder demos folder
demosDir = Path(builder.__file__).parent
# for all psyexp files in builder demos folder...
for file in demosDir.glob("**/*.psyexp"):
# load experiment
exp = experiment.Experiment.fromFile(file)
# check piloting mode param
assert exp.settings.params['runMode'] == "0", (
"Builder demos should be saved in Pilot mode, so that they start off piloting when "
"users unpack them. Please change run mode on {}".format(file.name)
)
| 2,058
|
Python
|
.py
| 47
| 35.957447
| 112
| 0.659023
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,427
|
test_environmenttools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_environmenttools.py
|
from psychopy.tools import environmenttools as et
globalVal1 = 1
globalVal2 = 2
globalExec1 = 1
globalExec2 = 2
def testGetFromNames():
# locals set via normal code
localVal1 = 1
localVal2 = 2
assert et.getFromNames(['localVal1', 'localVal2'], locals()) == [1, 2]
# locals set via exec
exec("localExec1 = 1")
exec("localExec2 = 2")
assert et.getFromNames(['localExec1', 'localExec2'], locals()) == [1, 2]
# globals set via normal code
global globalVal1
global globalVal2
assert et.getFromNames(['globalVal1', 'globalVal2'], globals()) == [1, 2]
# globals set via exec
exec("global globalExec1")
exec("global globalExec2")
assert et.getFromNames(['globalExec1', 'globalExec2'], globals()) == [1, 2]
# nonexistant locals
assert et.getFromNames(['nonexistantLocal1', 'nonexistantLocal2'], locals()) == ['nonexistantLocal1', 'nonexistantLocal2']
# nonexistant globals
assert et.getFromNames(['nonexistantGlobal1', 'nonexistantGlobal2'], globals()) == ['nonexistantGlobal1', 'nonexistantGlobal2']
# listlike strings
assert et.getFromNames("localVal1, localVal2", locals()) == [1, 2]
assert et.getFromNames("(localVal1, localVal2)", locals()) == [1, 2]
assert et.getFromNames("[localVal1, localVal2]", locals()) == [1, 2]
assert et.getFromNames("'localVal1', 'localVal2'", locals()) == [1, 2]
assert et.getFromNames('"localVal1", "localVal2"', locals()) == [1, 2]
# single name
assert et.getFromNames("localVal1", locals()) == [1]
def testSetExecEnvironment():
# globals
exec = et.setExecEnvironment(globals())
exec("execEnvGlobalTest = 1")
assert globals()['execEnvGlobalTest'] == 1
# locals
exec = et.setExecEnvironment(locals())
exec("execLocalTest = 1")
assert locals()['execLocalTest'] == 1
| 1,843
|
Python
|
.py
| 43
| 38.302326
| 131
| 0.680625
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,428
|
test_attributetools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_attributetools.py
|
import time
from numpy.random import choice as randchoice
import pandas as pd
import scipy.stats as sp
from psychopy.tests import skip_under_vm
from psychopy import colors
from psychopy.tools.attributetools import attributeSetter, logAttrib
from psychopy.tools.stringtools import CaseSwitcher
pd.options.display.float_format = "{:,.0f}".format
@skip_under_vm
class TestAttributeSetterSpeed:
nCalls = 1000
class _Base:
name = "test"
autoLog = True
def test_basic(self):
class AttributeSetter(self._Base):
@attributeSetter
def test(self, value):
self.__dict__['test'] = value
class PropertySetter(self._Base):
@property
def test(self):
return self._test
@test.setter
def test(self, value):
self._test = value
createTimes = {}
setTimes = {}
getTimes = {}
for cls in (AttributeSetter, PropertySetter):
# Setup timer
createTimes[cls.__name__] = []
setTimes[cls.__name__] = []
getTimes[cls.__name__] = []
last = time.time_ns()
# Create loads of objects
for n in range(self.nCalls):
obj = cls()
createTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Set and read values loads of times on last object
for val in range(self.nCalls):
# Set value
obj.test = val
setTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Get value
gotCol = obj.test
getTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Create total array
totalTimes = pd.DataFrame(createTimes) + pd.DataFrame(setTimes) + pd.DataFrame(getTimes)
# Print results
print("\n")
for key, times in {
'creating objects': createTimes,
'setting attribute': setTimes,
'getting attribute': getTimes,
'performing all operations': totalTimes,
}.items():
# Convert to dataframe using ms
df = pd.DataFrame(times) / self.nCalls
a = df['AttributeSetter']
b = df['PropertySetter']
# Calculate descriptives and do a T-test
T, p = sp.ttest_ind(a, b)
std = (a.std() + b.std()) / 2
diff = a.mean() - b.mean()
# If diff < 0, then attribute setter is faster
if diff < 0:
faster = "AttributeSetter"
slower = "PropertySetter"
else:
faster = "PropertySetter"
slower = "AttributeSetter"
# Print any significant differences
if p < 0.05:
# Construct string to print
out = (
f"{faster} WAS significantly faster than {slower} when {key} "
f"(diff: {abs(diff):.2f}ns, T: {T:.2f}, p: {p:.2f})"
)
else:
# Construct string to print
out = (
f"{faster} WAS NOT significantly faster than {slower} when {key}"
)
print(out)
def test_color_attribs(self):
class AttributeSetter(self._Base):
def __init__(self, colorSpace):
self.colorSpace = colorSpace
@attributeSetter
def colorSpace(self, value):
self.__dict__['colorSpace'] = value
if hasattr(self, "_color"):
self.__dict__['color'] = getattr(self._color, self.colorSpace)
@attributeSetter
def color(self, value):
self._color = colors.Color(value, self.colorSpace)
self.__dict__['color'] = getattr(self._color, self.colorSpace)
class PropertySetter(self._Base):
def __init__(self, colorSpace):
self.colorSpace = colorSpace
@property
def color(self):
if hasattr(self, "_color"):
return getattr(self._color, self.colorSpace)
@color.setter
def color(self, value):
self._color = colors.Color(value, self.colorSpace)
createTimes = {}
firstTimes = {}
spaceTimes = {}
setTimes = {}
getTimes = {}
getSameTimes = {}
for cls in (AttributeSetter, PropertySetter):
# Setup timer
createTimes[cls.__name__] = []
firstTimes[cls.__name__] = []
spaceTimes[cls.__name__] = []
setTimes[cls.__name__] = []
getTimes[cls.__name__] = []
getSameTimes[cls.__name__] = []
last = time.time_ns()
# Create loads of objects
for n in range(self.nCalls):
obj = cls(randchoice(("hsv", "rgb", "rgb255")))
createTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Set initial values
obj.color = "red"
obj.colorSpace = randchoice(("hsv", "rgb", "rgb255"))
gotVal = obj.color
firstTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Set and read values loads of times on last object
for n in range(self.nCalls):
# Set value
obj.color = randchoice(("red", "green", "blue"))
setTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Set color space
obj.colorSpace = randchoice(("hsv", "rgb", "rgb255"))
spaceTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Get value
gotCol = obj.color
getTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Get unchanged value repeatedly, but in different color space than it was set
obj.colorSpace = "hsv"
obj.color = "red"
obj.colorSpace = "rgb1"
last = time.time_ns()
for n in range(self.nCalls):
# Get value
gotCol = obj.color
getSameTimes[cls.__name__].append(time.time_ns() - last)
last = time.time_ns()
# Create total array
totalTimes = pd.DataFrame(createTimes) + pd.DataFrame(firstTimes) + pd.DataFrame(spaceTimes) + pd.DataFrame(setTimes) + pd.DataFrame(getTimes) + pd.DataFrame(getSameTimes)
# Print results
print("\n")
for key, times in {
'creating objects': createTimes,
'setting and getting color on a new object': firstTimes,
'setting color space': spaceTimes,
'setting color': setTimes,
'getting color': getTimes,
'getting same color repeatedly': getSameTimes,
'performing all operations': totalTimes,
}.items():
# Convert to dataframe using ms
df = pd.DataFrame(times) / self.nCalls
a = df['AttributeSetter']
b = df['PropertySetter']
# Calculate descriptives and do a T-test
T, p = sp.ttest_ind(a, b)
std = (a.std() + b.std()) / 2
diff = a.mean() - b.mean()
# If diff < 0, then attribute setter is faster
if diff < 0:
faster = "AttributeSetter"
slower = "PropertySetter"
else:
faster = "PropertySetter"
slower = "AttributeSetter"
# Print any significant differences
if p < 0.05:
# Construct string to print
out = (
f"{faster} WAS significantly faster than {slower} when {key} "
f"(diff: {abs(diff):.2f}ns, T: {T:.2f}, p: {p:.2f})"
)
else:
# Construct string to print
out = (
f"{faster} WAS NOT significantly faster than {slower} when {key}"
)
print(out)
def testGetSetAliases():
from psychopy.visual.circle import Circle
from psychopy.visual.textbox2.textbox2 import TextBox2
from psychopy.visual.button import ButtonStim
from psychopy.visual.movie import MovieStim
from psychopy.sound import Sound
from psychopy.hardware.mouse import Mouse
for cls in (Circle, TextBox2, ButtonStim, MovieStim, Sound, Mouse):
# iterate through methods
for name in dir(cls):
# get function
func = getattr(cls, name)
# ignore any which aren't attributeSetters
if not isinstance(func, (attributeSetter, property)):
continue
# work out getter method name
getterName = "get" + CaseSwitcher.camel2pascal(name)
# ensure that the corresponding get function exists
assert hasattr(cls, getterName), f"Class '{cls.__name__}' has not attribute '{getterName}'"
# any non-settable properties are now done
if isinstance(func, property) and func.fset is None:
continue
# work out setter method name
setterName = "set" + CaseSwitcher.camel2pascal(name)
# ensure that the corresponding set function exists
assert hasattr(cls, setterName), f"Class '{cls.__name__}' has not attribute '{setterName}'"
| 9,774
|
Python
|
.py
| 229
| 29.628821
| 179
| 0.529684
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,429
|
test_viewtools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_viewtools.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.viewtools
"""
from psychopy.tools.viewtools import *
import numpy as np
import pytest
@pytest.mark.viewtools
def test_frustumToProjectionMatrix():
"""Ensure the `computeFrustum` + `perspectiveProjectionMatrix` and
`generalizedPerspectiveProjection` give similar results, therefore testing
them both at the same time.
"""
# random screen parameters
N = 1000
np.random.seed(12345)
scrDims = np.random.uniform(0.01, 10.0, (N, 2,))
viewDists = np.random.uniform(0.025, 10.0, (N,))
eyeOffsets = np.random.uniform(-0.1, 0.1, (N,))
for i in range(N):
scrWidth = scrDims[i, 0]
scrAspect = scrDims[i, 0] / scrDims[i, 1]
viewDist = viewDists[i]
# nearClip some distance between screen and eye
nearClip = np.random.uniform(0.001, viewDist, (1,))
# nearClip some distance beyond screen
fcMin = viewDist + nearClip
farClip = np.random.uniform(fcMin, 1000.0, (1,))
frustum = computeFrustum(
scrWidth,
scrAspect,
viewDist,
eyeOffset=eyeOffsets[i],
nearClip=nearClip,
farClip=farClip)
P = perspectiveProjectionMatrix(*frustum)
# configuration of screen and eyes
x = scrWidth / 2.
y = scrDims[i, 1] / 2.0
z = -viewDist
posBottomLeft = [-x, -y, z]
posBottomRight = [x, -y, z]
posTopLeft = [-x, y, z]
posEye = [eyeOffsets[i], 0.0, 0.0]
# create projection and view matrices
GP, _ = generalizedPerspectiveProjection(posBottomLeft,
posBottomRight,
posTopLeft,
posEye,
nearClip=nearClip,
farClip=farClip)
assert np.allclose(P, GP)
if __name__ == "__main__":
pytest.main()
| 2,049
|
Python
|
.py
| 53
| 27.339623
| 78
| 0.552472
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,430
|
test_arraytools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_arraytools.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.arraytools
"""
from psychopy.tools import arraytools as at
import pytest
import numpy
def test_xys():
cases = [
{'x': [1, 2, 3, 4, 5],'y': [6, 7, 8, 9, 10], 'ans': numpy.array([
[1, 6], [2, 6], [3, 6], [4, 6], [5, 6], [1, 7], [2, 7], [3, 7], [4, 7], [5, 7], [1, 8], [2, 8], [3, 8],
[4, 8], [5, 8], [1, 9], [2, 9], [3, 9], [4, 9], [5, 9], [1, 10], [2, 10], [3, 10], [4, 10], [5, 10]
])}, # Standard
{'x': [1, 2, 3, 4, 5], 'y': None, 'ans': numpy.array([
[1, 1], [2, 1], [3, 1], [4, 1], [5, 1], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [1, 3], [2, 3], [3, 3],
[4, 3], [5, 3], [1, 4], [2, 4], [3, 4], [4, 4], [5, 4], [1, 5], [2, 5], [3, 5], [4, 5], [5, 5]
])} # No y
]
for case in cases:
# Check equality
assert numpy.allclose(
at.createXYs(x=case['x'], y=case['y']),
case['ans']
)
def test_xys():
cases = [
{'arr': numpy.array([1, 2, 3, 4, 5]), 'size': 7, 'ans': numpy.array([1, 2, 3, 4, 5, 0, 0])}, # standard
{'arr': [1, 2, 3, 4, 5], 'size': 7, 'ans': numpy.array([1, 2, 3, 4, 5, 0, 0])}, # list
{'arr': [], 'size': 7, 'ans': numpy.array([0., 0., 0., 0., 0., 0., 0.])}, # empty
]
for case in cases:
# Check equality
assert numpy.allclose(
at.extendArr(case['arr'], case['size']),
case['ans']
)
def test_makeRadialMatrix():
cases = [
{'size': 8, 'ans': numpy.array(
[
[1.4142135623730, 1.25, 1.118033988749, 1.0307764064044, 1.0, 1.0307764064044, 1.118033988749, 1.25],
[1.25, 1.06066017177, 0.90138781886, 0.79056941504, 0.75, 0.79056941504, 0.90138781886, 1.06066017177],
[1.118033988, 0.9013878188, 0.7071067811, 0.5590169943, 0.5, 0.5590169943, 0.7071067811, 0.9013878188],
[1.0307764064, 0.7905694150, 0.5590169943, 0.3535533905, 0.25, 0.3535533905, 0.5590169943, 0.7905694150],
[1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75],
[1.0307764064, 0.7905694150, 0.5590169943, 0.3535533905, 0.25, 0.3535533905, 0.5590169943, 0.7905694150],
[1.118033988, 0.9013878188, 0.7071067811, 0.5590169943, 0.5, 0.5590169943, 0.7071067811, 0.9013878188],
[1.25, 1.0606601717, 0.901387818, 0.7905694150, 0.75, 0.7905694150, 0.9013878188, 1.0606601717],
]
)},
]
for case in cases:
assert numpy.allclose(
numpy.round(at.makeRadialMatrix(case['size']), 8),
case['ans']
)
# also test that matrixSize=0 raises an error
with pytest.raises(ValueError):
at.makeRadialMatrix(0)
def test_ratioRange():
cases = [
{"start": 1, "nSteps": None, "stop": 10, "stepRatio": 2, "stepdB": None, "stepLogUnits": None,
'ans': numpy.array([1., 2., 4., 8.])}, # Step ratio + stop
{"start": 1, "nSteps": None, "stop": 10, "stepRatio": None, "stepdB": 2, "stepLogUnits": None,
'ans': numpy.array([1., 1.25892541, 1.58489319, 1.99526231, 2.51188643, 3.16227766, 3.98107171, 5.01187234, 6.30957344, 7.94328235])}, # Step db + stop
{"start": 1, "nSteps": None, "stop": 10, "stepRatio": None, "stepdB": None, "stepLogUnits": 1,
'ans': numpy.array([1.])}, # Step log units + stop
{"start": 1, "nSteps": 5, "stop": 10, "stepRatio": None, "stepdB": None, "stepLogUnits": None,
'ans': numpy.array([ 1., 1.77827941, 3.16227766, 5.62341325, 10.])}, # nSteps + stop
{"start": 1, "nSteps": 5, "stop": None, "stepRatio": 2, "stepdB": None, "stepLogUnits": None,
'ans': numpy.array([ 1., 2., 4., 8., 16.])}, # nSteps + step ratio
]
for case in cases:
assert numpy.allclose(
at.ratioRange(case['start'], nSteps=case['nSteps'], stop=case['stop'], stepRatio=case['stepRatio'], stepdB=case['stepdB'], stepLogUnits=case['stepLogUnits']),
case['ans']
)
def test_val2array():
cases = [
{'value': [1, None], 'withNone': True, 'withScalar': True, 'length': 2,
'ans': numpy.array([1., numpy.nan])}, # Default
{'value': [1, None], 'withNone': False, 'withScalar': True, 'length': 2,
'ans': numpy.array([1., numpy.nan])}, # Without None
{'value': [1, 1], 'withNone': True, 'withScalar': False, 'length': 2,
'ans': numpy.array([1.])}, # Without scalar
{'value': [1, 1, 1, 1, 1], 'withNone': True, 'withScalar': True, 'length': 5,
'ans': numpy.array([1.])}, # Longer length
]
for case in cases:
assert numpy.allclose(
at.val2array(case['value'], withNone=case['withNone'], withScalar=case['withScalar'], length=case['length']),
case['ans'],
equal_nan=True
)
def test_AliasDict():
"""
Test that the AliasDict class works as expected.
"""
# make alias
params = at.AliasDict({'patient': 1})
params.alias("patient", alias="participant")
# test that aliases are counted in contains method
assert 'participant' in params
# test that aliases are not included in iteration
for key in params:
assert key != 'participant'
# test that participant and patient return the same value
assert params['patient'] == params['participant'] == 1
# test that setting the alias sets the original
params['participant'] = 2
assert params['patient'] == params['participant'] == 2
# test that setting the original sets the alias
params['patient'] = 3
assert params['patient'] == params['participant'] == 3
# test that adding an alias to a new object doesn't affect the original
params2 = at.AliasDict({"1": 1})
params2.alias("1", alias="one")
assert "one" not in params.aliases
assert "1" not in params.aliases
class TestIndexDict:
def setup_method(self):
self.recreateData()
def recreateData(self):
"""
Recreate the test index dict from scratch, in case it changed over the course of a test.
"""
self.data = at.IndexDict({
'someKey': "abc",
'someOtherKey': "def",
'anotherOne': "ghi",
1: "jkl",
})
def test_isinstance(self):
"""
Check that an IndexDict is an instance of dict
"""
assert isinstance(self.data, dict)
def test_length(self):
"""
Check that an IndexDict reports its length as the number of explicit keys, ignoring
positional indices.
"""
assert len(self.data) == 4
def test_get_item(self):
"""
Check that items in an IndexDict can be got as expected, explicit keys should always take
precedence over positional indices.
"""
cases = [
# positional indices
(0, "abc"),
(2, "ghi"),
(3, "jkl"),
# explicit indices
('someKey', "abc"),
('someOtherKey', "def"),
('anotherOne', "ghi"),
# conflicting indices (should favour explicit)
(1, "jkl"),
]
# iterate through cases
for key, value in cases:
# check that each key returns the correct value
assert self.data[key] == value
def test_set_item(self):
"""
Check that items in an IndexDict can be set as expected, should set by position only if the
positional index is not already defined as an explicit key.
"""
cases = [
# set by positional index (no conflict)
{'set': (0, "mno"), 'get': (0, "mno")},
{'set': (0, "mno"), 'get': ('someKey', "mno")},
# set by explicit key (no conflict)
{'set': ('someKey', "mno"), 'get': (0, "mno")},
{'set': ('someKey', "mno"), 'get': ('someKey', "mno")},
# set by explicit string (when its positional index is also a key)
{'set': ('someOtherKey', "pqr"), 'get': ('someOtherKey', "pqr")},
{'set': ('someOtherKey', "mno"), 'get': (1, "jkl")},
# set by positional index (when it's also a key)
{'set': (1, "pqr"), 'get': ('someOtherKey', "def")},
{'set': (1, "pqr"), 'get': (1, "pqr")},
# set by explicit key not yet in array
{'set': ('newKey', "stu"), 'get': ('newKey', "stu")},
{'set': ('newKey', "stu"), 'get': (4, "stu")},
# set by positional index not yet in array (should treat as explicit key)
{'set': (6, "stu"), 'get': (6, "stu")},
]
# iterate through cases
for case in cases:
# recreate data to clear last changes
self.recreateData()
# get values to set and expected values to return
seti, setval = case['set']
geti, getval = case['get']
# set value
self.data[seti] = setval
# check value
assert self.data[geti] == getval, (
f"After setting data[{repr(seti)}] = {repr(setval)} expected to get data["
f"{repr(geti)}] == {repr(getval)}, but instead got data[{repr(geti)}] == "
f"{repr(self.data[geti])}"
)
def test_key_error(self):
"""
Check that supplying an invalid key/index to an IndexDict still errors like a normal
dict/list
"""
cases = [
# index bigger than array
(4, KeyError, "4 should be out of bounds, but got {}"),
# key not in array
('lalala', KeyError, "There shouldn't be a value for 'lalala', but got {}"),
]
for i, errType, msg in cases:
try:
val = self.data[i]
except errType as err:
# if it errors as expected, good!
pass
else:
# if no error, raise an assertion error with message
raise AssertionError(msg.format(val))
| 10,134
|
Python
|
.py
| 222
| 35.923423
| 170
| 0.531516
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,431
|
test_filetools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_filetools.py
|
# -*- coding: utf-8 -*-
"""
Tests for psychopy.tools.filetools
"""
import shutil
import os
import sys
import json
import pickle
import pytest
from tempfile import mkdtemp, mkstemp
from psychopy.tools.filetools import (genDelimiter, genFilenameFromDelimiter,
openOutputFile, fromFile)
def test_genDelimiter():
baseName = 'testfile'
extensions = ['.csv', '.CSV', '.tsv', '.txt', '.unknown', '']
correctDelimiters = [',', ',', '\t', '\t', '\t', '\t']
for extension, correctDelimiter in zip(extensions, correctDelimiters):
fileName = baseName + extension
delimiter = genDelimiter(fileName)
assert delimiter == correctDelimiter
def test_genFilenameFromDelimiter():
base_name = 'testfile'
delims = [',', '\t', None]
correct_extensions = ['.csv', '.tsv', '.txt']
for delim, correct_extension in zip(delims, correct_extensions):
filename = genFilenameFromDelimiter(base_name, delim)
extension = os.path.splitext(filename)[1]
assert extension == correct_extension
class TestOpenOutputFile():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.rootName = 'test_data_file'
self.baseFileName = os.path.join(self.temp_dir, self.rootName)
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_default_parameters(self):
with openOutputFile(self.baseFileName) as f:
assert f.encoding == 'utf-8-sig'
assert f.closed is False
assert f.stream.mode == 'wb'
def test_append(self):
with openOutputFile(self.baseFileName, append=True) as f:
assert f.encoding == 'utf-8-sig'
assert f.closed is False
assert f.stream.mode == 'ab'
def test_stdout(self):
f = openOutputFile(None)
assert f is sys.stdout
f = openOutputFile('stdout')
assert f is sys.stdout
class TestFromFile():
def setup_method(self):
self.tmp_dir = mkdtemp(prefix='psychopy-tests-%s' %
type(self).__name__)
def teardown_method(self):
shutil.rmtree(self.tmp_dir)
def test_json_with_encoding(self):
_, path_0 = mkstemp(dir=self.tmp_dir, suffix='.json')
_, path_1 = mkstemp(dir=self.tmp_dir, suffix='.json')
encoding_0 = 'utf-8'
encoding_1 = 'utf-8-sig'
test_data = 'Test'
with open(path_0, 'w', encoding=encoding_0) as f:
json.dump(test_data, f)
with open(path_1, 'w', encoding=encoding_1) as f:
json.dump(test_data, f)
assert test_data == fromFile(path_0, encoding=encoding_0)
assert test_data == fromFile(path_1, encoding=encoding_1)
def test_pickle(self):
_, path = mkstemp(dir=self.tmp_dir, suffix='.psydat')
test_data = 'Test'
with open(path, 'wb') as f:
pickle.dump(test_data, f)
assert test_data == fromFile(path)
if __name__ == '__main__':
pytest.main()
| 3,076
|
Python
|
.py
| 77
| 32.051948
| 77
| 0.621131
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,432
|
test_versionchooser.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_versionchooser.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.versionchooser"""
import os
import sys
import unittest
import subprocess
import shutil
from pathlib import Path
import psychopy
from psychopy.tools.versionchooser import Version, VersionRange, useVersion, versionMap
from psychopy import prefs, experiment
from psychopy.scripts.psyexpCompile import generateScript
from psychopy.experiment.components import polygon
from tempfile import mkdtemp
USERDIR = prefs.paths['userPrefsDir']
VER_SUBDIR = 'versions'
VERSIONSDIR = os.path.join(USERDIR, VER_SUBDIR)
pyVersion = Version(".".join(
[str(sys.version_info.major), str(sys.version_info.minor)]
))
class TestVersionChooser():
def setup_method(self):
self.temp = Path(mkdtemp())
def test_same_version(self):
# pick a version which works with installed Python
rVers = versionMap[pyVersion][0]
# use it
vers = useVersion(rVers)
vers = Version(vers)
# confirm that it is being used
assert (vers.major, vers.minor) == (rVers.major, rVers.minor)
def test_version_folder(self):
assert(os.path.isdir(VERSIONSDIR))
def test_writing(self):
# Can't run this test on anything beyond 3.6
if pyVersion > Version("3.6"):
return
# Create simple experiment with a Polygon
exp = experiment.Experiment()
rt = experiment.routines.Routine(name="testRoutine", exp=exp)
exp.addRoutine("testRoutine", rt)
exp.flow.addRoutine(rt, 0)
comp = polygon.PolygonComponent(exp=exp, parentName="testRoutine")
rt.addComponent(comp)
# Set use version
exp.settings.params['Use version'].val = "2021.1.4"
# Save experiment
exp.saveToXML(str(self.temp / "versionText.psyexp"))
# --- Python ---
# Write script
scriptFile = str(self.temp / "versionText.py")
generateScript(
outfile=scriptFile,
exp=exp,
target="PsychoPy"
)
# Read script
with open(scriptFile, "r") as f:
script = f.read()
# Get args passed to comp
args = script.split(f"{comp.name} = visual.ShapeStim(")[1]
args = args.split(")")[0]
# If using 2021.1.4, there shouldn't be any "anchor" arg in ShapeStim, as it wasn't implemented yet
assert "anchor" not in args, (
"When compiling Py with useversion 2021.1.4, found 'anchor' argument in ShapeStim; this was not "
"implemented in requested version."
)
# --- JS ---
# Write script
scriptFile = str(self.temp / "versionText.js")
generateScript(
outfile=scriptFile,
exp=exp,
target="PsychoJS"
)
# Read script
with open(scriptFile, "r") as f:
script = f.read()
# Check for correct version import statement
assert "import { PsychoJS } from './lib/core-2021.1.4.js'" in script, (
"When compiling JS with useversion 2021.1.4, could not find version-specific import statement."
)
class TestVersionRange:
def test_comparisons(self):
"""
Test that version numbers below the range register as less than.
"""
cases = [
# value < range
{'range': ("2023.1.0", "2023.2.0"), 'value': "2022.2.0",
'lt': False, 'eq': False, 'gt': True},
# value == range.first
{'range': ("2023.1.0", "2023.2.0"), 'value': "2023.1.0",
'lt': False, 'eq': True, 'gt': False},
# value in range
{'range': ("2023.1.0", "2023.2.0"), 'value': "2023.1.5",
'lt': False, 'eq': True, 'gt': False},
# value == range.last
{'range': ("2023.1.0", "2023.2.0"), 'value': "2023.2.0",
'lt': False, 'eq': True, 'gt': False},
# value > range
{'range': ("2023.1.0", "2023.2.0"), 'value': "2024.1.0",
'lt': True, 'eq': False, 'gt': False},
# value < range.last with no first
{'range': (None, "2023.2.0"), 'value': "2022.2.0",
'lt': False, 'eq': True, 'gt': False},
# value == range.last with no first
{'range': (None, "2023.2.0"), 'value': "2023.2.0",
'lt': False, 'eq': True, 'gt': False},
# value > range.last with no first
{'range': (None, "2023.2.0"), 'value': "2024.1.0",
'lt': True, 'eq': False, 'gt': False},
# value < range.first with no last
{'range': ("2023.1.0", None), 'value': "2022.2.0",
'lt': False, 'eq': False, 'gt': True},
# value == range.first with no last
{'range': ("2023.1.0", None), 'value': "2023.1.0",
'lt': False, 'eq': True, 'gt': False},
# value > range.first with no last
{'range': ("2023.1.0", None), 'value': "2024.1.0",
'lt': False, 'eq': True, 'gt': False},
# no last or first
{'range': (None, None), 'value': "2022.2.0",
'lt': False, 'eq': True, 'gt': False},
{'range': (None, None), 'value': "2023.1.0",
'lt': False, 'eq': True, 'gt': False},
{'range': (None, None), 'value': "2024.1.0",
'lt': False, 'eq': True, 'gt': False},
]
for case in cases:
# make VersionRange
r = VersionRange(
first=case['range'][0],
last=case['range'][1]
)
# work out le and ge from case values
case['le'] = case['lt'] or case['eq']
case['ge'] = case['gt'] or case['eq']
# confirm that comparisons work as expected
assert (r > case['value']) == case['gt'], (
"VersionRange%(range)s > '%(value)s' should be %(gt)s" % case
)
assert (r >= case['value']) == case['ge'], (
"VersionRange%(range)s >= '%(value)s' should be %(ge)s" % case
)
assert (case['value'] in r) == case['eq'], (
"'%(value)s' in VersionRange%(range)s should be %(eq)s" % case
)
assert (r <= case['value']) == case['le'], (
"VersionRange%(range)s <= '%(value)s' should be %(le)s" % case
)
assert (r < case['value']) == case['lt'], (
"VersionRange%(range)s < '%(value)s' should be %(lt)s" % case
)
class TestGitInstallation(unittest.TestCase):
def test_git_installed(self):
# Test if Git is installed on this system.
try:
# Attempt to get the Git version
result = subprocess.run(["git", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Check if the command was successful
self.assertTrue(result.returncode == 0, "Git is not installed or not in the PATH.")
except subprocess.CalledProcessError:
# If an error occurs, the test should fail
self.fail("Git is not installed or not in the PATH.")
class TestGitClone(unittest.TestCase):
def test_git_can_clone_repo(self):
# Test that Git can clone a repository
repo_url = "https://github.com/git/git" # Using a reliable repo that is always available
target_dir = "temp_repo"
try:
# Ensure the target directory does not exist before cloning
if os.path.exists(target_dir):
shutil.rmtree(target_dir)
# Run 'git clone' and capture output
subprocess.run(['git', 'clone', repo_url, target_dir], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
except subprocess.CalledProcessError as e:
# If Git clone fails for any reason
self.fail(f"Git clone command failed: {e}")
except FileNotFoundError:
# If the 'git' command is not found
self.fail("Git is not installed on this system.")
finally:
# Clean up by removing the cloned directory if it exists
if os.path.exists(target_dir):
shutil.rmtree(target_dir)
| 8,260
|
Python
|
.py
| 186
| 34.155914
| 137
| 0.555832
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,433
|
test_stringtools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_stringtools.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.mathtools
"""
from psychopy.tools import stringtools as tools
import pytest
@pytest.mark.stringtools
def test_name_wrap():
cases = [
{"text": "Hello There", "wrap": 12, "ans": "Hello There"}, # No wrap
{"text": "Hello There", "wrap": 8, "ans": "Hello \nThere"}, # Basic wrap
{"text": "Hello There Hello There Hello There", "wrap": 11, "ans": "Hello There \nHello There \nHello There"}, # Multiple wraps
{"text": "Eyetracker Calibration", "wrap": 10, "ans": "Eyetracker \nCalibratio-\nn"}, # One word longer than wrap length
]
for case in cases:
assert tools.wrap(case['text'], case['wrap']) == case['ans']
@pytest.mark.stringtools
def test_get_variables():
exemplars = [
{"code": "x=1\ny=2", "ans": {'x': 1, 'y': 2}}, # numbers
{"code": "x=\"a\"\ny=\"b\"", "ans": {'x': "a", 'y': "b"}}, # double quotes
{"code": "x='a'\ny='b'", "ans": {'x': "a", 'y': "b"}}, # single quotes
{"code": "x=(1, 2)\ny=(3, 4)", "ans": {'x': (1, 2), 'y': (3, 4)}}, # arrays
]
tykes = [
{"code": "x='(1, 2)'\ny='(3, 4)'", "ans": {'x': "(1, 2)", 'y': "(3, 4)"}}, # string representation of array (single)
{"code": "x=\"(1, 2)\"\ny=\"(3, 4)\"", "ans": {'x': "(1, 2)", 'y': "(3, 4)"}}, # string representation of array (double)
]
for case in exemplars + tykes:
assert tools.getVariables(case['code']) == case['ans']
@pytest.mark.stringtools
def test_get_arguments():
exemplars = [
{"code": "x=1,y=2", "ans": {'x': 1, 'y': 2}}, # numbers
{"code": "x=\"a\",y=\"b\"", "ans": {'x': "a", 'y': "b"}}, # double quotes
{"code": "x='a',y='b'", "ans": {'x': "a", 'y': "b"}}, # single quotes
{"code": "x=(1, 2), y=(3, 4)", "ans": {'x': (1, 2), 'y': (3, 4)}}, # arrays
]
tykes = [
{"code": "(x=1, y=2)", "ans": {'x': 1, 'y': 2}}, # outer brackets
{"code": "x='(1, 2)', y='(3, 4)'", "ans": {'x': "(1, 2)", 'y': "(3, 4)"}}, # string representation of array (single)
{"code": "x=\"(1, 2)\", y=\"(3, 4)\"", "ans": {'x': "(1, 2)", 'y': "(3, 4)"}}, # string representation of array (double)
]
for case in exemplars + tykes:
assert tools.getArgs(case['code']) == case['ans']
@pytest.mark.stringtools
def test_make_valid_name():
cases = [
# Already valid names
{"in": "ALREADYVALIDUPPER", "case": "upper", "out": "ALREADYVALIDUPPER"},
{"in": "AlreadyValidTitle", "case": "title", "out": "AlreadyValidTitle"},
{"in": "alreadyValidCamel", "case": "camel", "out": "alreadyValidCamel"},
{"in": "already_valid_snake", "case": "snake", "out": "already_valid_snake"},
{"in": "alreadyvalidlower", "case": "lower", "out": "alreadyvalidlower"},
# Sentence style names
{"in": "make upper", "case": "upper", "out": "MAKEUPPER"},
{"in": "make title", "case": "title", "out": "MakeTitle"},
{"in": "make camel", "case": "camel", "out": "makeCamel"},
{"in": "make snake", "case": "snake", "out": "make_snake"},
{"in": "make lower", "case": "lower", "out": "makelower"},
# Numbers on end
{"in": "upper case 1", "case": "upper", "out": "UPPERCASE1"},
{"in": "title case 2", "case": "title", "out": "TitleCase2"},
{"in": "camel case 3", "case": "camel", "out": "camelCase3"},
{"in": "snake case 4", "case": "snake", "out": "snake_case_4"},
{"in": "lower case 5", "case": "lower", "out": "lowercase5"},
# Numbers at start
{"in": "1 upper case", "case": "upper", "out": "UPPERCASE"},
{"in": "2 title case", "case": "title", "out": "TitleCase"},
{"in": "3 camel case", "case": "camel", "out": "camelCase"},
{"in": "4 snake case", "case": "snake", "out": "snake_case"},
{"in": "5 lower case", "case": "lower", "out": "lowercase"},
# Numbers inbetween
{"in": "upper 1 case", "case": "upper", "out": "UPPER1CASE"},
{"in": "title 2 case", "case": "title", "out": "Title2Case"},
{"in": "camel 3 case", "case": "camel", "out": "camel3Case"},
{"in": "snake 4 case", "case": "snake", "out": "snake_4_case"},
{"in": "lower 5 case", "case": "lower", "out": "lower5case"},
# Invalid chars
{"in": "exclamation!mark", "case": "snake", "out": "exclamation_mark"},
{"in": "question?mark", "case": "snake", "out": "question_mark"},
# Protected/private/core syntax
{"in": "_privateAttribute", "case": "snake", "out": "_private_attribute"},
{"in": "_privateAttribute", "case": "camel", "out": "_privateAttribute"},
{"in": "__protectedAttribute", "case": "snake", "out": "__protected_attribute"},
{"in": "__protectedAttribute", "case": "camel", "out": "__protectedAttribute"},
{"in": "__core__", "case": "snake", "out": "__core__"},
{"in": "__core__", "case": "lower", "out": "__core__"},
# Known tykes
]
for case in cases:
assert tools.makeValidVarName(name=case['in'], case=case['case']) == case['out']
def test_CaseSwitcher():
cases = [
# to camel
{'fcn': "pascal2camel", 'in': "alreadyValidCamel", 'out': "alreadyValidCamel"},
{'fcn': "title2camel", 'in': "alreadyValidCamel", 'out': "alreadyValidCamel"},
{'fcn': "snake2camel", 'in': "alreadyValidCamel", 'out': "alreadyValidCamel"},
{'fcn': "pascal2camel", 'in': "MakeCamel", 'out': "makeCamel"},
{'fcn': "title2camel", 'in': "Make Camel", 'out': "makeCamel"},
{'fcn': "snake2camel", 'in': "make_camel", 'out': "makeCamel"},
# to pascal
{'fcn': "camel2pascal", 'in': "AlreadyValidPascal", 'out': "AlreadyValidPascal"},
{'fcn': "title2pascal", 'in': "AlreadyValidPascal", 'out': "AlreadyValidPascal"},
{'fcn': "snake2pascal", 'in': "AlreadyValidPascal", 'out': "AlreadyValidPascal"},
{'fcn': "camel2pascal", 'in': "makePascal", 'out': "MakePascal"},
{'fcn': "title2pascal", 'in': "Make Pascal", 'out': "MakePascal"},
{'fcn': "snake2pascal", 'in': "make_pascal", 'out': "MakePascal"},
# to title
{'fcn': "camel2title", 'in': "Already Valid Title", 'out': "Already Valid Title"},
{'fcn': "pascal2title", 'in': "Already Valid Title", 'out': "Already Valid Title"},
{'fcn': "snake2title", 'in': "Already Valid Title", 'out': "Already Valid Title"},
{'fcn': "camel2title", 'in': "makeTitle", 'out': "Make Title"},
{'fcn': "pascal2title", 'in': "MakeTitle", 'out': "Make Title"},
{'fcn': "snake2title", 'in': "make_title", 'out': "Make Title"},
# to snake
{'fcn': "camel2snake", 'in': "already_valid_snake", 'out': "already_valid_snake"},
{'fcn': "pascal2snake", 'in': "already_valid_snake", 'out': "already_valid_snake"},
{'fcn': "title2snake", 'in': "already_valid_snake", 'out': "already_valid_snake"},
{'fcn': "camel2snake", 'in': "makeSnake", 'out': "make_snake"},
{'fcn': "pascal2snake", 'in': "MakeSnake", 'out': "make_snake"},
{'fcn': "title2snake", 'in': "Make Snake", 'out': "make_snake"},
]
for case in cases:
# get function
fcn = getattr(tools.CaseSwitcher, case['fcn'])
# call function
case['result'] = fcn(case['in'])
# check result
assert case['result'] == case['out'], "CaseSwitcher.{fcn}({in}) should be {out}, was {result}.".format(**case)
| 7,545
|
Python
|
.py
| 129
| 50.837209
| 136
| 0.526885
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,434
|
test_imagetools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_imagetools.py
|
from psychopy.tools.imagetools import *
import numpy
from psychopy.tests import utils
from pathlib import Path
from PIL import Image as image, ImageChops
import pytest
resources = Path(utils.TESTS_DATA_PATH)
imgL = image.open(str(resources / "testpixels.png")).convert("L")
imgF = image.open(str(resources / "testpixels.png")).convert("F")
arrL = numpy.array([
[ 0, 76, 226, 150, 179, 29, 105, 255],
[136, 136, 136, 136, 1, 1, 1, 1],
[136, 136, 136, 136, 1, 1, 1, 1],
[136, 136, 136, 136, 1, 1, 1, 1],
[254, 254, 254, 254, 137, 137, 137, 137],
[254, 254, 254, 254, 137, 137, 137, 137],
[254, 254, 254, 254, 137, 137, 137, 137],
[103, 242, 132, 126, 165, 160, 196, 198]
], dtype=numpy.uint8)
arrF = numpy.array([
[ 0. , 76.245, 225.93 , 149.685, 178.755, 29.07 , 105.315, 255. ],
[136. , 136. , 136. , 136. , 1. , 1. , 1. , 1. ],
[136. , 136. , 136. , 136. , 1. , 1. , 1. , 1. ],
[136. , 136. , 136. , 136. , 1. , 1. , 1. , 1. ],
[254. , 254. , 254. , 254. , 137. , 137. , 137. , 137. ],
[254. , 254. , 254. , 254. , 137. , 137. , 137. , 137. ],
[254. , 254. , 254. , 254. , 137. , 137. , 137. , 137. ],
[102.912, 242. , 132.04 , 126.477, 165.264, 159.543, 196.144, 197.993]
], dtype=numpy.float32)
@pytest.mark.imagetools
def test_array2image():
# Test when image type is F
assert not ImageChops.difference(
array2image(arrF).convert('RGB'), imgF.convert('RGB')
).getbbox()
# Test when image type is L
assert not ImageChops.difference(
array2image(arrL).convert('RGB'), imgL.convert('RGB')
).getbbox()
@pytest.mark.imagetools
def test_image2array():
# Test when image type is F
assert numpy.array_equal(
image2array(imgF), arrF
)
# Test when image type is L
assert numpy.array_equal(
image2array(imgL), arrL
)
| 2,018
|
Python
|
.py
| 49
| 37.081633
| 77
| 0.54717
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,435
|
test_animationtools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_animationtools.py
|
from psychopy.tests import utils
from psychopy.tools import animationtools as at
import numpy as np
def testSinusoidalFuncs():
cases = (
# max/min sizes
{'startSize': 0, 'apexSize': 1, 'duration': 1, 'time': 1, 'ans': 1},
{'startSize': 0, 'apexSize': 1, 'duration': 1, 'time': 0, 'ans': 0},
# arrays
{'startSize': (0, 1), 'apexSize': (1, 0), 'duration': 1, 'time': 0, 'ans': (0, 1)},
{'startSize': (0, 1), 'apexSize': (1, 0), 'duration': 1, 'time': 1, 'ans': (1, 0)},
# midpoints
{'startSize': 0, 'apexSize': 1, 'duration': 1, 'time': 0.5, 'ans': 0.5},
{'startSize': 1, 'apexSize': 0, 'duration': 1, 'time': 0.5, 'ans': 0.5},
# intermediate points
{'startSize': 0, 'apexSize': 1, 'duration': 1, 'time': 1/3, 'ans': 0.25},
{'startSize': 0, 'apexSize': 1, 'duration': 1, 'time': 2/3, 'ans': 0.75},
{'startSize': 1, 'apexSize': 0, 'duration': 1, 'time': 1/3, 'ans': 0.75},
{'startSize': 1, 'apexSize': 0, 'duration': 1, 'time': 2/3, 'ans': 0.25},
)
for case in cases:
# apply parameters from case dict to function
ans = at.sinusoidalGrowth(
startSize=case['startSize'],
apexSize=case['apexSize'],
duration=case['duration'],
time=case['time']
)
ans = np.round(ans, decimals=3)
# verify answer
assert utils.forceBool(ans == case['ans'], handler=all), (
f"Params: startSize=%(startSize)s, apexSize=%(apexSize)s, duration=%(duration)s, time=%(time)s\n"
f"Expected: %(ans)s\n"
f"Got: {ans}\n"
) % case
# verify that aslias functions behave the same
mov = at.sinusoidalMovement(
startPos=case['startSize'],
apexPos=case['apexSize'],
duration=case['duration'],
time=case['time']
)
mov = np.round(mov, decimals=3)
assert utils.forceBool(mov == case['ans'], handler=all), (
f"Params: startSize=%(startSize)s, apexSize=%(apexSize)s, duration=%(duration)s, time=%(time)s\n"
f"Expected: %(ans)s\n"
f"Got: {ans}\n"
) % case
| 2,207
|
Python
|
.py
| 48
| 36.666667
| 109
| 0.53525
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,436
|
test_mathtools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_mathtools.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.mathtools
"""
from psychopy.tools.mathtools import *
from psychopy.tools.viewtools import *
import numpy as np
import pytest
@pytest.mark.mathtools
def test_rotations():
"""Test rotations with quaternions and matrices. Checks if quaternions and
matrices constructed with the same axes and angles give the same rotations
to sets of random points.
Tests `quatFromAxisAngle`, `rotationMatrix`, `applyMatrix` and `applyQuat`.
"""
# identity check
axis = [0., 0., -1.]
angle = 0.0
q = quatFromAxisAngle(axis, angle, degrees=True)
assert np.allclose(q, np.asarray([0., 0., 0., 1.]))
q = rotationMatrix(angle, axis)
assert np.allclose(q, np.identity(4))
# full check
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3)) # random rotation axes
axes = normalize(axes, out=axes)
angles = np.random.uniform(-180.0, 180.0, (N,)) # random angles
points = np.random.uniform(-100.0, 100.0, (N, 3)) # random points to rotate
for i in range(N):
axis = axes[i, :]
angle = angles[i]
rotMat = rotationMatrix(angle, axis)[:3, :3] # rotation sub-matrix only
rotQuat = quatFromAxisAngle(axis, angle, degrees=True)
assert np.allclose(applyMatrix(rotMat, points), applyQuat(rotQuat, points))
@pytest.mark.mathtools
def test_multQuat():
"""Test quaternion multiplication.
Create two quaternions, multiply them, and check if the resulting
orientation is as expected.
"""
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(0.0, 360.0, (N, 2,)) # random angles
for i in range(N):
totalAngle = angles[i, 0] + angles[i, 1]
q0 = quatFromAxisAngle(axes[i, :], angles[i, 0], degrees=True)
q1 = quatFromAxisAngle(axes[i, :], angles[i, 1], degrees=True)
quatTarget = quatFromAxisAngle(axes[i, :], totalAngle, degrees=True)
assert np.allclose(multQuat(q0, q1), quatTarget)
@pytest.mark.mathtools
def test_matrixFromQuat():
"""Test if a matrix created using `matrixFromQuat` is equivalent to a
rotation matrix created by `rotationMatrix`.
"""
# test if quaternion conversions give the same rotation matrices
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(0.0, 360.0, (N,)) # random angles
for i in range(N):
# create a quaternion and convert it to a rotation matrix
q = quatFromAxisAngle(axes[i, :], angles[i], degrees=True)
qr = quatToMatrix(q)
# create a rotation matrix directly
rm = rotationMatrix(angles[i], axes[i, :])
# check if they are close
assert np.allclose(qr, rm)
@pytest.mark.mathtools
def test_invertQuat():
"""Test if quaternion inversion works. When multiplied, the result should be
an identity quaternion.
"""
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(0.0, 360.0, (N,)) # random angles
qidt = np.array([0., 0., 0., 1.]) # identity quaternion
for i in range(N):
# create a quaternion and convert it to a rotation matrix
q = quatFromAxisAngle(axes[i, :], angles[i], degrees=True)
qinv = invertQuat(q)
assert np.allclose(multQuat(q, qinv), qidt) # is identity?
@pytest.mark.mathtools
def test_transform():
"""Test if `transform` gives the same results as a matrix."""
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(0.0, 360.0, (N,)) # random angles
translations = np.random.uniform(-10.0, 10.0, (N, 3,)) # random translations
points = np.zeros((N, 4,))
points[:, :3] = np.random.uniform(-10.0, 10.0, (N, 3,)) # random points
points[:, 3] = 1.0
for i in range(N):
ori = quatFromAxisAngle(axes[i, :], angles[i], degrees=True)
rm = rotationMatrix(angles[i], axes[i, :])
tm = translationMatrix(translations[i, :])
m = concatenate([rm, tm])
tPoint = transform(translations[i, :], ori, points=points[:, :3])
mPoint = applyMatrix(m, points=points)
assert np.allclose(tPoint, mPoint[:, :3]) # is identity?
@pytest.mark.mathtools
def test_quatToMatrix():
"""Test converting quaternions to matrices and vice-versa. The end result
should be the same transformed vectors."""
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(0.0, 360.0, (N,)) # random angles
vectors = normalize(np.random.uniform(-1.0, 1.0, (N, 3,)))
for i in range(N):
q = matrixToQuat(rotationMatrix(angles[i], normalize(axes[i, :])))
m = quatToMatrix(quatFromAxisAngle(normalize(axes[i, :]), angles[i]))
# The returned quaternion might not be the same, but will result in the
# same rotation.
assert np.allclose(applyMatrix(m, vectors[i]), applyQuat(q, vectors[i]))
@pytest.mark.mathtools
def test_reflect():
exemplars = [
# 1d array float64
{'v': np.array([1, 2, 3, 4]),
'n': np.array([5, 6, 7, 8]),
'dtype': np.float64,
'ans': np.array([-699., -838., -977., -1116.]),
},
# 2d array float64
{'v': np.array([[1, 2], [3, 4]]),
'n': np.array([[5, 6], [7, 8]]),
'dtype': np.float64,
'ans': np.array([[-169., -202.], [-739., -844.]]),
},
]
tykes = [
# no dtype
{'v': np.array([1, 2, 3, 4]),
'n': np.array([5, 6, 7, 8]),
'dtype': None,
'ans': np.array([-699., -838., -977., -1116.]),
},
]
for case in exemplars + tykes:
assert np.array_equal(
case['ans'],
reflect(v=case['v'], n=case['n'], dtype=case['dtype'])
)
@pytest.mark.mathtools
def test_length():
"""Test function `length()`."""
np.random.seed(123456)
N = 1000
v = np.random.uniform(-1.0, 1.0, (N, 3,))
# test Nx2 vectorized input
result0 = length(v)
# test writing to another location
result1 = np.zeros((N,))
length(v, out=result1)
assert np.allclose(result0, result1)
# test squared==True
result1 = length(v, squared=True)
assert np.allclose(result0, np.sqrt(result1))
# test ndim==1
result1 = np.zeros((N,))
for i in range(N):
result1[i] = length(v[i, :])
assert np.allclose(result0, result1)
@pytest.mark.mathtools
def test_dot():
"""Test the dot-product function `dot()`. Tests cases Nx2, Nx3, and Nx4
including one-to-many cases. The test for the `cross()` function validates
if the values computed by `dot()` are meaningful.
"""
np.random.seed(123456)
N = 1000
# check Nx2, Nx3, Nx4 cases
for nCol in range(2, 5):
vectors1 = np.random.uniform(-1.0, 1.0, (N, nCol,))
vectors2 = np.random.uniform(-1.0, 1.0, (N, nCol,))
# check vectorization
results0 = dot(vectors1, vectors2)
# check write to output array
results1 = np.zeros((N,))
dot(vectors1, vectors2, out=results1)
assert np.allclose(results0, results1)
# check row-by-row
results1.fill(0.0) # clear
for i in range(N):
results1[i] = dot(vectors1[i, :], vectors2[i, :])
assert np.allclose(results0, results1)
# check 1 to many
results0 = dot(vectors1[0, :], vectors2)
results1.fill(0.0) # clear
for i in range(N):
results1[i] = dot(vectors1[0, :], vectors2[i, :])
assert np.allclose(results0, results1)
# check many to 1
results0 = dot(vectors1, vectors2[0, :])
results1.fill(0.0) # clear
for i in range(N):
results1[i] = dot(vectors1[i, :], vectors2[0, :])
assert np.allclose(results0, results1)
@pytest.mark.mathtools
def test_dist():
"""Test the distance function in mathtools. This also test the `normalize`
function to ensure all vectors have a length of 1.
"""
np.random.seed(123456)
N = 1000
# check Nx2 and Nx3 cases
for nCol in range(2, 4):
vectors = np.random.uniform(-1.0, 1.0, (N, nCol,))
vectors = normalize(vectors, out=vectors) # normalize
# point to check distance from
point = np.zeros((nCol,))
# calculate 1 to many
distOneToMany = distance(point, vectors)
# check if distances are all one
assert np.allclose(distOneToMany, 1.0)
# calculate many to 1
distManyToOne = distance(point, vectors)
# check if results are the same
assert np.allclose(distManyToOne, distOneToMany)
# check if output array is written to correctly
out = np.zeros((N,))
idToCheck = id(out)
out = distance(vectors, point, out)
# check result
assert np.allclose(out, distManyToOne)
# check same object
assert id(out) == idToCheck
# test row-by-row
vectors = normalize(np.random.uniform(-1.0, 1.0, (N, 3,)))
distRowByRow = distance(np.zeros_like(vectors), vectors)
assert np.allclose(distRowByRow, 1.0)
@pytest.mark.mathtools
def test_cross():
"""Test the cross-product function `cross()`.
Check input arrays with dimensions Nx3 and Nx4. Test data are orthogonal
vectors which the resulting cross product is confirmed to be perpendicular
using a dot product, this must be true in all cases in order for the test to
succeed. This also tests `dot()` for this purpose.
Tests for the one-to-many inputs don't compute perpendicular vectors, they
just need to return the same values when vectorized and when using a loop.
"""
np.random.seed(123456)
N = 1000
# check Nx2, Nx3, Nx4 cases
for nCol in range(3, 5):
# orthogonal vectors
vectors1 = np.zeros((N, nCol,))
vectors1[:, 1] = 1.0
vectors2 = np.zeros((N, nCol,))
vectors2[:, 0] = 1.0
if nCol == 4:
vectors1[:, 3] = vectors2[:, 3] = 1.0
# rotate the vectors randomly
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(-180.0, 180.0, (N,)) # random angles
for i in range(N):
r = rotationMatrix(angles[i], axes[i, :])
vectors1[i, :] = applyMatrix(r, vectors1[i, :])
vectors2[i, :] = applyMatrix(r, vectors2[i, :])
# test normalization output
normalize(vectors1[:, :3], out=vectors2[:, :3])
normalize(vectors2[:, :3], out=vectors2[:, :3])
# check vectorization
results0 = cross(vectors1, vectors2)
# check write to output array
results1 = np.zeros((N, nCol,))
cross(vectors1, vectors2, out=results1)
assert np.allclose(results0, results1)
# check if cross products are perpendicular
assert np.allclose(dot(vectors1[:, :3], results0[:, :3]), 0.0)
# check row-by-row
results1.fill(0.0) # clear
for i in range(N):
results1[i] = cross(vectors1[i, :], vectors2[i, :])
assert np.allclose(results0, results1)
# check 1 to many
results0 = cross(vectors1[0, :], vectors2)
results1.fill(0.0) # clear
for i in range(N):
results1[i] = cross(vectors1[0, :], vectors2[i, :])
assert np.allclose(results0, results1)
# check many to 1
results0 = cross(vectors1, vectors2[0, :])
results1.fill(0.0) # clear
for i in range(N):
results1[i] = cross(vectors1[i, :], vectors2[0, :])
assert np.allclose(results0, results1)
@pytest.mark.mathtools
def test_project():
exemplars = [
# 1d array float64
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
'dtype': np.float64,
'ans': np.array([2.01149425, 2.4137931, 2.81609195, 3.2183908]),
},
# 2d array float64
{'v0': np.array([[1, 2], [3, 4]]),
'v1': np.array([[5, 6], [7, 8]]),
'dtype': np.float64,
'ans': np.array([[10.88313479, 13.05976175], [34.90074422, 39.88656482]]),
},
]
tykes = [
# no dtype
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
'dtype': None,
'ans': np.array([2.01149425, 2.4137931, 2.81609195, 3.2183908]),
},
# These should work, but don't
# # 2d on 1d
# {'v0': np.array([[1, 2], [3, 4]]),
# 'v1': np.array([5, 6, 7, 8]),
# 'dtype': np.float64,
# 'ans': np.array([[10.88313479, 13.05976175], [34.90074422, 39.88656482]]),
# },
# #1d on 2d
# {'v0': np.array([1, 2, 3, 4]),
# 'v1': np.array([[5, 6], [7, 8]]),
# 'dtype': np.float64,
# 'ans': np.array([[10.88313479, 13.05976175], [34.90074422, 39.88656482]]),
# },
]
for case in exemplars + tykes:
assert np.allclose(
case['ans'],
project(v0=case['v0'], v1=case['v1'], dtype=case['dtype'])
)
@pytest.mark.mathtools
def test_lerp():
exemplars = [
# 1d array float64 t=1
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
't': 1,
'dtype': np.float64,
'ans': np.array([5., 6., 7., 8.]),
},
# 2d array float64 t=1
{'v0': np.array([[1, 2], [3, 4]]),
'v1': np.array([[5, 6], [7, 8]]),
't': 1,
'dtype': np.float64,
'ans': np.array([[5., 6.], [7., 8.]]),
},
# 1d array float64 t=0.5
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
't': 0.5,
'dtype': np.float64,
'ans': np.array([3., 4., 5., 6.]),
},
# 2d array float64 t=0.5
{'v0': np.array([[1, 2], [3, 4]]),
'v1': np.array([[5, 6], [7, 8]]),
't': 0.5,
'dtype': np.float64,
'ans': np.array([[3., 4.], [5., 6.]]),
},
# 1d array float64 t=0
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
't': 0,
'dtype': np.float64,
'ans': np.array([1., 2., 3., 4.]),
},
# 2d array float64 t=0
{'v0': np.array([[1, 2], [3, 4]]),
'v1': np.array([[5, 6], [7, 8]]),
't': 0,
'dtype': np.float64,
'ans': np.array([[1., 2.], [3., 4.]]),
},
]
tykes = [
# no dtype
{'v0': np.array([1, 2, 3, 4]),
'v1': np.array([5, 6, 7, 8]),
't': 1,
'dtype': None,
'ans': np.array([5., 6., 7., 8.]),
},
]
for case in exemplars + tykes:
assert np.allclose(
case['ans'],
lerp(v0=case['v0'], v1=case['v1'], t=case['t'], dtype=case['dtype'])
)
@pytest.mark.mathtools
def test_perp():
exemplars = [
# 3d array float64 norm
{'v0': np.array([[1, 2, 3], [4, 5, 6]]),
'v1': np.array([[6, 5, 4], [3, 2, 1]]),
'norm': True,
'dtype': np.float64,
'ans': np.array([[-0.72914182, -0.56073762, -0.39233343], [-0.87763952, -0.47409942, -0.07055933]]),
},
# 3d array float64 not norm
{'v0': np.array([[1, 2, 3], [4, 5, 6]]),
'v1': np.array([[6, 5, 4], [3, 2, 1]]),
'norm': False,
'dtype': np.float64,
'ans': np.array([[-18.14537685, -13.9544807, -9.76358456], [-18.44994432, -9.96662955, -1.48331477]]),
},
]
tykes = [
# no dtype
{'v0': np.array([[1, 2, 3], [4, 5, 6]]),
'v1': np.array([[6, 5, 4], [3, 2, 1]]),
'norm': True,
'dtype': None,
'ans': np.array([[-0.72914182, -0.56073762, -0.39233343], [-0.87763952, -0.47409942, -0.07055933]]),
},
]
for case in exemplars + tykes:
np.allclose(
case['ans'],
perp(v=case['v0'], n=case['v1'], norm=case['norm'], dtype=case['dtype'])
)
@pytest.mark.mathtools
def test_orthogonalize():
"""Check the `orthogonalize()` function. This function nudges a vector to
be perpendicular with another (usually a normal). All orthogonalized vectors
should be perpendicular to the normal vector, having a dot product very
close to zero. This condition must occur in all cases for the test to
succeed.
"""
np.random.seed(567890)
N = 1000
# orthogonal vectors
normals = np.zeros((N, 3,))
normals[:, 1] = 1.0
vec = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
normalize(vec, out=vec)
# rotate the normal vectors randomly
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(-180.0, 180.0, (N,)) # random angles
for i in range(N):
r = rotationMatrix(angles[i], axes[i, :])
normals[i, :] = applyMatrix(r, normals[i, :])
normalize(normals[:, :3], out=normals[:, :3])
result1 = orthogonalize(vec, normals)
result2 = np.zeros_like(result1)
orthogonalize(vec, normals, out=result2)
# check if results are the same
assert np.allclose(result1, result2)
# check if the orthogonalized vector is perpendicular
assert np.allclose(dot(normals, result1), 0.0)
@pytest.mark.mathtools
def test_invertMatrix():
"""Test of the `invertMatrix()` function.
Checks if the function can handle both homogeneous (rotation and translation
only), general, and view/projection cases.
All inverses must return something very close to an identity matrix when
multiplied with the original matrix for a test to succeed.
"""
np.random.seed(123456)
N = 1000
axes = np.random.uniform(-1.0, 1.0, (N, 3,)) # random axes
angles = np.random.uniform(-180.0, 180.0, (N,)) # random angles
trans = np.random.uniform(-1000.0, 1000.0, (N, 3,)) # random translations
scales = np.random.uniform(0.0001, 1000.0, (N, 3,)) # random scales
# check homogeneous inverse
ident = np.identity(4)
for i in range(N):
r = rotationMatrix(angles[i], axes[i, :])
assert isOrthogonal(r)
t = translationMatrix(trans[i, :])
# combine them
m = np.matmul(t, r)
assert isAffine(m) # must always be TRUE
inv = invertMatrix(m)
# check if we have identity
assert np.allclose(np.matmul(inv, m), ident)
# check non-homogeneous inverse and outputs
rout = np.zeros((4, 4))
tout = np.zeros((4, 4))
sout = np.zeros((4, 4))
inv = np.zeros((4, 4))
ident = np.identity(4)
for i in range(N):
rotationMatrix(angles[i], axes[i, :], out=rout)
assert isOrthogonal(rout)
translationMatrix(trans[i, :], out=tout)
scaleMatrix(scales[i, :], out=sout)
# combine them
m = np.matmul(tout, np.matmul(rout, sout))
assert isAffine(m) # must always be TRUE
invertMatrix(m, out=inv)
assert np.allclose(np.matmul(inv, m), ident)
# test with view/projection matrices
scrDims = np.random.uniform(0.01, 3.0, (N, 2,))
viewDists = np.random.uniform(0.025, 10.0, (N,))
eyeOffsets = np.random.uniform(-0.1, 0.1, (N,))
for i in range(N):
scrWidth = scrDims[i, 0]
scrAspect = scrDims[i, 0] / scrDims[i, 1]
viewDist = viewDists[i]
# nearClip some distance between screen and eye
nearClip = np.random.uniform(0.1, viewDist, (1,))
# nearClip some distance beyond screen
fcMin = viewDist + nearClip
farClip = np.random.uniform(fcMin, 1000.0, (1,))
# get projection matrix
frustum = computeFrustum(
scrWidth,
scrAspect,
viewDist,
eyeOffset=eyeOffsets[i],
nearClip=nearClip,
farClip=farClip)
proj = perspectiveProjectionMatrix(*frustum)
assert not isAffine(proj)
# create affine view matrix
r = rotationMatrix(angles[i], axes[i, :])
assert isOrthogonal(r)
t = translationMatrix(trans[i, :])
view = np.matmul(t, r)
assert isAffine(view)
# combine them
vp = np.matmul(proj, view)
# invert
inv = invertMatrix(vp)
assert np.allclose(ident, np.matmul(inv, vp))
@pytest.mark.mathtools
def test_alignTo():
"""Test quaternion alignment function `alignTo`. Check general nonparallel
and parallel cases.
Tests are successful if the resulting quaternion rotates the initial vector
to match the target vector.
"""
np.random.seed(12345)
N = 1000
# general use cases
vec = normalize(np.random.uniform(-1.0, 1.0, (N, 3)))
target = normalize(np.random.uniform(-1.0, 1.0, (N, 3)))
qr = alignTo(vec, target)
out = applyQuat(qr, vec)
assert np.allclose(out, target)
# test when rotation is 180 degrees, or vectors are parallel in opposite
# directions
target = -vec
qr = alignTo(vec, target)
out = applyQuat(qr, vec)
assert np.allclose(out, target)
if __name__ == "__main__":
pytest.main()
| 21,414
|
Python
|
.py
| 552
| 31.333333
| 111
| 0.579369
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,437
|
test_fileerrortools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_fileerrortools.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import os
import shutil
from tempfile import mkstemp, mkdtemp, NamedTemporaryFile
from psychopy.tools.fileerrortools import handleFileCollision
def test_handleFileCollision_overwrite():
_, path = mkstemp()
handled_path = handleFileCollision(fileName=path,
fileCollisionMethod='overwrite')
assert path == handled_path
def test_handleFileCollision_fail():
_, path = mkstemp()
with pytest.raises(IOError):
handleFileCollision(fileName=path,
fileCollisionMethod='fail')
def test_handleFileCollision_rename_file_does_not_exist():
temp_dir = mkdtemp()
# Create temporary file and close it (to destroy it). We simply use this
# procedure to grab a unique file name.
with NamedTemporaryFile(dir=temp_dir) as f:
path = f.name
handled_path = handleFileCollision(fileName=path,
fileCollisionMethod='rename')
assert path == handled_path
def test_handleFileCollision_rename_file_exists():
temp_dir = mkdtemp()
# Create temporary file and close it (to destroy it). We simply use this
# procedure to grab a unique file name.
with NamedTemporaryFile(dir=temp_dir, suffix='.xyz') as f:
path = f.name
handled_path = handleFileCollision(fileName=path,
fileCollisionMethod='rename')
filename, suffix = os.path.splitext(path)
expected_path = '%s_1%s' % (filename, suffix)
assert handled_path == expected_path
os.rmdir(temp_dir)
def test_handleFileCollision_rename_multiple_files_exists():
temp_dir = mkdtemp()
path = os.path.join(temp_dir, 'test.txt')
filename, suffix = os.path.splitext(path)
# Create a file to start with.
with open(path, 'w') as f:
f.write('foo')
# Now handle collisions of files with the same name.
for i, _ in enumerate(range(10), start=1):
handled_path = handleFileCollision(fileName=path,
fileCollisionMethod='rename')
expected_path = '%s_%i%s' % (filename, i, suffix)
assert handled_path == expected_path
# We need to write something to the file to create it.
with open(handled_path, 'w') as f:
f.write('foo')
shutil.rmtree(temp_dir)
def test_handleFileCollision_invalid_method():
_, path = mkstemp()
with pytest.raises(ValueError):
handleFileCollision(fileName=path,
fileCollisionMethod='invalid_value')
if __name__ == '__main__':
test_handleFileCollision_overwrite()
test_handleFileCollision_fail()
test_handleFileCollision_rename_file_does_not_exist()
test_handleFileCollision_rename_file_exists()
test_handleFileCollision_rename_multiple_files_exists()
test_handleFileCollision_invalid_method()
| 2,953
|
Python
|
.py
| 67
| 35.761194
| 76
| 0.663866
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,438
|
test_colorspacetools.py
|
psychopy_psychopy/psychopy/tests/test_tools/test_colorspacetools.py
|
# -*- coding: utf-8 -*-
"""Tests for psychopy.tools.colorspacetools
"""
from psychopy.tools.colorspacetools import *
import numpy as np
import pytest
@pytest.mark.colorspacetools
def test_rgb2hsv():
"""Test the conversion (forward and inverse) for HSV to RGB (signed). This
does not test for "correctness", but rather if the functions provided for
the conversion are the inverse of each other.
"""
# basic test (Nx3)
N = 1024
np.random.seed(123456)
hsvColors = np.zeros((N, 3))
hsvColors[:, 0] = np.random.randint(0, 360, (N,))
hsvColors[:, 1:] = np.random.uniform(0, 1, (N, 2))
# test conversion back and forth
hsvOut = rgb2hsv(hsv2rgb(hsvColors))
assert np.allclose(hsvOut, hsvColors)
# test if the function can handle pictures
hsvColors = np.zeros((N, N, 3))
hsvColors[:, :, 0] = np.random.randint(0, 360, (N, N,))
hsvColors[:, :, 1:] = np.random.uniform(0, 1, (N, N, 2))
hsvOut = rgb2hsv(hsv2rgb(hsvColors))
assert np.allclose(hsvOut, hsvColors)
@pytest.mark.colorspacetools
def test_lms2rgb():
"""Test the conversion (forward and inverse) for LMS to RGB (signed). This
does not test for "correctness", but rather if the functions provided for
the conversion are the inverse of each other.
"""
N = 1024
np.random.seed(123456)
rgbColors = np.random.uniform(-1, 1, (N, 3))
# test conversion back and forth
rgbOut = lms2rgb(rgb2lms(rgbColors))
assert np.allclose(rgbOut, rgbColors)
@pytest.mark.colorspacetools
def test_cartDKL2rgb():
"""Test the conversion (forward and inverse) for cartesian DKL to RGB
(signed). This does not test for "correctness", but rather if the functions
provided for the conversion are the inverse of each other.
"""
N = 1024
np.random.seed(123456)
rgbColors = np.random.uniform(-1, 1, (N, N, 3))
# test conversion, inputs are specified differently between functions
rgbOut = dklCart2rgb(rgb2dklCart(rgbColors)[:, :, 0],
rgb2dklCart(rgbColors)[:, :, 1],
rgb2dklCart(rgbColors)[:, :, 2])
assert np.allclose(rgbOut, rgbColors)
@pytest.mark.colorspacetools
def test_dkl2rgb():
"""Test the conversion (forward) for DKL to RGB (signed).
"""
N = 1024
np.random.seed(123456)
dklColors = np.zeros((N, 3))
# elevation
dklColors[:, 0] = np.random.uniform(0, 90, (N,))
# azimuth
dklColors[:, 1] = np.random.uniform(0, 360, (N,))
# radius
dklColors[:, 2] = np.random.uniform(0, 1, (N,))
# test conversion using vector input
_ = dkl2rgb(dklColors)
# now test with some known colors, just white for now until we generate more
dklWhite = [90, 0, 1]
assert np.allclose(np.asarray((1, 1, 1)), dkl2rgb(dklWhite))
@pytest.mark.colorspacetools
def test_srgbTF():
"""Test the sRGB transfer function which converts linear RGB values to
gamma corrected according to the sRGB standard.
"""
N = 1024
np.random.seed(123456)
rgbColors = np.random.uniform(-1, 1, (N, 3))
# test conversion, inputs are specified differently between functions
rgbOut = srgbTF(srgbTF(rgbColors), reverse=True)
assert np.allclose(rgbOut, rgbColors)
@pytest.mark.colorspacetools
def test_cielab2rgb():
"""Test the CIE-Lab to RGB function using the sRGB transfer function.
"""
# preset CIE-Lab colors using a D65 white-point and expected RGB values
cielabD65 = np.array([
[0.0, 0.0, 0.0], # black
[100.0, 0.0, 0.0], # white
[53.24, 80.09, 67.20], # red
[87.73, -86.18, 83.18], # green
[32.30, 79.19, -107.86], # blue
[97.14, -21.55, 94.48], # yellow
[91.11, -48.09, -14.13], # cyan
[60.32, 98.23, -60.82] # magenta
])
rgbExpected = np.array([
[-1., -1., -1.],
[1., 1., 1.],
[1., -1., -1.],
[-1., 1., -1.],
[-1., -1., 1.],
[1., 1., -1.],
[-1., 1., 1.],
[1., -1., 1.]
])
# test conversion with D65 white point
rgbOutD65 = cielab2rgb(cielabD65, transferFunc=srgbTF)
assert np.allclose(rgbOutD65, rgbExpected, atol=0.01)
if __name__ == "__main__":
pytest.main()
| 4,266
|
Python
|
.py
| 112
| 32.491071
| 80
| 0.633228
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,439
|
correctNoiseStimComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctNoiseStimComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newNoiseStimComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
noise = visual.NoiseStim(
win=win, name='noise',
noiseImage=None, mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5), sf=None,
phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=1, blendmode='avg', contrast=1.0,
texRes=128, filter=None,
noiseType='Binary', noiseElementSize=0.0625,
noiseBaseSf=8.0, noiseBW=1,
noiseBWO=30, noiseOri=0.0,
noiseFractalPower=0.0,noiseFilterLower=1.0,
noiseFilterUpper=8.0, noiseFilterOrder=0.0,
noiseClip=3.0, imageComponent='Phase', interpolate=False, depth=0.0)
noise.buildNoise()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [noise]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *noise* updates
if t >= 0.0 and noise.status == NOT_STARTED:
# keep track of start time/frame for later
noise.tStart = t # not accounting for scr refresh
noise.frameNStart = frameN # exact frame index
win.timeOnFlip(noise, 'tStartRefresh') # time at next scr refresh
noise.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if noise.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
noise.tStop = t # not accounting for scr refresh
noise.frameNStop = frameN # exact frame index
win.timeOnFlip(noise, 'tStopRefresh') # time at next scr refresh
noise.setAutoDraw(False)
if noise.status == STARTED:
if noise._needBuild:
noise.buildNoise()
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('noise.started', noise.tStartRefresh)
thisExp.addData('noise.stopped', noise.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,863
|
Python
|
.py
| 149
| 41.818792
| 100
| 0.72015
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,440
|
correctSliderComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctSliderComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newSliderComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
slider = visual.Slider(win=win, name='slider',
size=(1.0, 0.1), pos=(0, -0.4),
labels=None, ticks=(1, 2, 3, 4, 5),
granularity=0, style=['rating'],
color='LightGray', font='HelveticaBold',
flip=False)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
slider.reset()
# keep track of which components have finished
trialComponents = [slider]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *slider* updates
if t >= 0.0 and slider.status == NOT_STARTED:
# keep track of start time/frame for later
slider.tStart = t # not accounting for scr refresh
slider.frameNStart = frameN # exact frame index
win.timeOnFlip(slider, 'tStartRefresh') # time at next scr refresh
slider.setAutoDraw(True)
# Check slider for response to end routine
if slider.getRating() is not None and slider.status == STARTED:
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('slider.response', slider.getRating())
thisExp.addData('slider.rt', slider.getRT())
thisExp.addData('slider.started', slider.tStartRefresh)
thisExp.addData('slider.stopped', slider.tStopRefresh)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,324
|
Python
|
.py
| 138
| 41.905797
| 100
| 0.725985
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,441
|
correctVariableComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctVariableComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newVariableComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
# Set experiment start values for variable component var1
var1 = ''
var1Container = []
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [var1]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 5,457
|
Python
|
.py
| 120
| 41.9
| 100
| 0.732981
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,442
|
correctJoystickComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctJoystickComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newJoystickComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
from psychopy.hardware import joystick as joysticklib # joystick/gamepad accsss
from psychopy.experiment.components.joystick import virtualJoystick as virtualjoysticklib
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
x, y = [None, None]
joystick = type('', (), {})() # Create an object to use as a name space
joystick.device = None
joystick.device_number = 0
joystick.joystickClock = core.Clock()
joystick.xFactor = 1
joystick.yFactor = 1
try:
numJoysticks = joysticklib.getNumJoysticks()
if numJoysticks > 0:
try:
joystickCache
except NameError:
joystickCache={}
if not 0 in joystickCache:
joystickCache[0] = joysticklib.Joystick(0)
joystick.device = joystickCache[0]
if win.units == 'height':
joystick.xFactor = 0.5 * win.size[0]/win.size[1]
joystick.yFactor = 0.5
else:
joystick.device = virtualjoysticklib.VirtualJoystick(0)
logging.warning("joystick_{}: Using keyboard+mouse emulation 'ctrl' + 'Alt' + digit.".format(joystick.device_number))
except Exception:
pass
if not joystick.device:
logging.error('No joystick/gamepad device found.')
core.quit()
joystick.status = None
joystick.clock = core.Clock()
joystick.numButtons = joystick.device.getNumButtons()
joystick.getNumButtons = joystick.device.getNumButtons
joystick.getAllButtons = joystick.device.getAllButtons
joystick.getX = lambda: joystick.xFactor * joystick.device.getX()
joystick.getY = lambda: joystick.yFactor * joystick.device.getY()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
joystick.oldButtonState = joystick.device.getAllButtons()[:]
joystick.activeButtons=[i for i in range(joystick.numButtons)]
# setup some python lists for storing info about the joystick
gotValidClick = False # until a click is received
# keep track of which components have finished
trialComponents = [joystick]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *joystick* updates
if t >= 0.0 and joystick.status == NOT_STARTED:
# keep track of start time/frame for later
joystick.tStart = t # not accounting for scr refresh
joystick.frameNStart = frameN # exact frame index
win.timeOnFlip(joystick, 'tStartRefresh') # time at next scr refresh
joystick.status = STARTED
joystick.joystickClock.reset()
if joystick.status == STARTED: # only update if started and not finished!
joystick.newButtonState = joystick.getAllButtons()[:]
if joystick.newButtonState != joystick.oldButtonState: # New button press
joystick.pressedButtons = [i for i in range(joystick.numButtons) if joystick.newButtonState[i] and not joystick.oldButtonState[i]]
joystick.releasedButtons = [i for i in range(joystick.numButtons) if not joystick.newButtonState[i] and joystick.oldButtonState[i]]
joystick.newPressedButtons = [i for i in joystick.activeButtons if i in joystick.pressedButtons]
joystick.oldButtonState = joystick.newButtonState
joystick.buttons = joystick.newPressedButtons
[logging.data("joystick_{}_button: {}, pos=({:1.4f},{:1.4f})".format(joystick.device_number, i, joystick.getX(), joystick.getY())) for i in joystick.pressedButtons]
if len(joystick.buttons) > 0: # state changed to a new click
# abort routine on response
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# store data for thisExp (ExperimentHandler)
# store data for thisExp (ExperimentHandler)
x, y = joystick.getX(), joystick.getY()
joystick.newButtonState = joystick.getAllButtons()[:]
joystick.pressedState = [joystick.newButtonState[i] for i in range(joystick.numButtons)]
joystick.time = joystick.joystickClock.getTime()
thisExp.addData('joystick.x', x)
thisExp.addData('joystick.y', y)
[thisExp.addData('joystick.button_{0}'.format(i), int(joystick.pressedState[i])) for i in joystick.activeButtons]
thisExp.addData('joystick.time', joystick.time)
thisExp.addData('joystick.started', joystick.tStart)
thisExp.addData('joystick.stopped', joystick.tStop)
thisExp.nextEntry()
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 9,268
|
Python
|
.py
| 191
| 44.125654
| 176
| 0.730382
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,443
|
correctRatingScaleComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctRatingScaleComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newRatingScaleComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=True, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
rating = visual.RatingScale(win=win, name='rating', marker='triangle', size=1.0, pos=[0.0, -0.4], low=1, high=7, labels=[''], scale='')
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
rating.reset()
# keep track of which components have finished
trialComponents = [rating]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *rating* updates
if t >= 0.0 and rating.status == NOT_STARTED:
# keep track of start time/frame for later
rating.tStart = t # not accounting for scr refresh
rating.frameNStart = frameN # exact frame index
win.timeOnFlip(rating, 'tStartRefresh') # time at next scr refresh
rating.setAutoDraw(True)
continueRoutine &= rating.noResponse # a response ends the trial
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# store data for thisExp (ExperimentHandler)
thisExp.addData('rating.response', rating.getRating())
thisExp.addData('rating.rt', rating.getRT())
thisExp.nextEntry()
thisExp.addData('rating.started', rating.tStart)
thisExp.addData('rating.stopped', rating.tStop)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,207
|
Python
|
.py
| 133
| 42.954887
| 135
| 0.72947
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,444
|
correctPolygonComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctPolygonComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newPolygonComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
polygon = visual.ShapeStim(
win=win, name='polygon',
vertices=[[-(0.5, 0.5)[0]/2.0,-(0.5, 0.5)[1]/2.0], [+(0.5, 0.5)[0]/2.0,-(0.5, 0.5)[1]/2.0], [0,(0.5, 0.5)[1]/2.0]],
ori=0, pos=(0, 0),
lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',
fillColor=[1,1,1], fillColorSpace='rgb',
opacity=1, depth=0.0, interpolate=True)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [polygon]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *polygon* updates
if t >= 0.0 and polygon.status == NOT_STARTED:
# keep track of start time/frame for later
polygon.tStart = t # not accounting for scr refresh
polygon.frameNStart = frameN # exact frame index
win.timeOnFlip(polygon, 'tStartRefresh') # time at next scr refresh
polygon.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if polygon.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
polygon.tStop = t # not accounting for scr refresh
polygon.frameNStop = frameN # exact frame index
win.timeOnFlip(polygon, 'tStopRefresh') # time at next scr refresh
polygon.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('polygon.started', polygon.tStartRefresh)
thisExp.addData('polygon.stopped', polygon.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,586
|
Python
|
.py
| 139
| 43.258993
| 119
| 0.718009
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,445
|
correctFormComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctFormComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newFormComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
win.allowStencil = True
form = visual.Form(win=win, name='form',
items='.csv',
textHeight=0.03,
randomize=False,
size=(1, 0.7),
pos=(0, 0),
itemPadding=0.05)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [form]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
form.draw()
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
formData = form.getData()
while formData['questions']:
for dataTypes in formData.keys():
thisExp.addData(dataTypes, formData[dataTypes].popleft())
thisExp.nextEntry()
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 5,747
|
Python
|
.py
| 131
| 40.175573
| 100
| 0.728054
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,446
|
correctSoundComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctSoundComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.0),
on May 10, 2019, at 11:15
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newSoundComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
sound_1 = sound.Sound('A', secs=1.0, stereo=True)
sound_1.setVolume(1)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
sound_1.setSound('A', secs=1.0)
sound_1.setVolume(1, log=False)
# keep track of which components have finished
trialComponents = [sound_1]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# start/stop sound_1
if t >= 0.0 and sound_1.status == NOT_STARTED:
# keep track of start time/frame for later
sound_1.tStart = t # not accounting for scr refresh
sound_1.frameNStart = frameN # exact frame index
win.timeOnFlip(sound_1, 'tStartRefresh') # time at next scr refresh
win.callOnFlip(sound_1.play) # screen flip
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if sound_1.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
sound_1.tStop = t # not accounting for scr refresh
sound_1.frameNStop = frameN # exact frame index
win.timeOnFlip(sound_1, 'tStopRefresh') # time at next scr refresh
if 1.0 > 0.5: # don't force-stop brief sounds
sound_1.stop()
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
sound_1.stop() # ensure sound has stopped at end of routine
thisExp.addData('sound_1.started', sound_1.tStartRefresh)
thisExp.addData('sound_1.stopped', sound_1.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,489
|
Python
|
.py
| 138
| 43.021739
| 100
| 0.721835
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,447
|
correctioLabsButtonBoxComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctioLabsButtonBoxComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock, hardware
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newioLabsButtonBoxComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# connect to ioLabs bbox, turn lights off
from psychopy.hardware import iolab
iolab.ButtonBox().standby()
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
bbox = iolab.ButtonBox()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
bbox.clearEvents()
bbox.active = (0,1,2,3,4,5,6,7) # tuple or list of int 0..7
bbox.setEnabled(bbox.active)
bbox.setLights(bbox.active)
bbox.btns = [] # responses stored in .btns and .rt
bbox.rt = []
# keep track of which components have finished
trialComponents = [bbox]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *bbox* updates
if t >= 0.0 and bbox.status == NOT_STARTED:
# keep track of start time/frame for later
bbox.tStart = t # not accounting for scr refresh
bbox.frameNStart = frameN # exact frame index
win.timeOnFlip(bbox, 'tStartRefresh') # time at next scr refresh
bbox.status = STARTED
bbox.clearEvents()
# buttonbox checking is just starting
bbox.resetClock() # set bbox hardware internal clock to 0.000; ms accuracy
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if bbox.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
bbox.tStop = t # not accounting for scr refresh
bbox.frameNStop = frameN # exact frame index
win.timeOnFlip(bbox, 'tStopRefresh') # time at next scr refresh
bbox.status = FINISHED
if bbox.status == STARTED:
theseButtons = bbox.getEvents()
if theseButtons: # at least one button was pressed this frame
if bbox.btns == []: # True if the first
bbox.btns = theseButtons[0].key # just the first button
bbox.rt = theseButtons[0].rt
# a response forces the end of the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# store ioLabs bbox data for bbox (ExperimentHandler)
if len(bbox.btns) == 0: # no ioLabs responses
bbox.btns = None
thisExp.addData('bbox.btns', bbox.btns)
if bbox.btns != None: # add RTs if there are responses
thisExp.addData('bbox.rt', bbox.rt)
# check responses
if bbox.keys in ['', [], None]: # No response was made
bbox.keys = None
thisExp.addData('bbox.keys',bbox.keys)
if bbox.keys != None: # we had a response
thisExp.addData('bbox.rt', bbox.rt)
thisExp.addData('bbox.started', bbox.tStartRefresh)
thisExp.addData('bbox.stopped', bbox.tStopRefresh)
thisExp.nextEntry()
thisExp.nextEntry()
bbox.standby() # lights out etc
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 7,652
|
Python
|
.py
| 168
| 41.327381
| 100
| 0.71557
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,448
|
correctApertureComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctApertureComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newApertureComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=True,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
aperture = visual.Aperture(
win=win, name='aperture',
units='norm', size=1, pos=(0, 0))
aperture.disable() # disable until its actually used
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [aperture]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *aperture* updates
if t >= 0.0 and aperture.status == NOT_STARTED:
# keep track of start time/frame for later
aperture.tStart = t # not accounting for scr refresh
aperture.frameNStart = frameN # exact frame index
win.timeOnFlip(aperture, 'tStartRefresh') # time at next scr refresh
aperture.enabled = True
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if aperture.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
aperture.tStop = t # not accounting for scr refresh
aperture.frameNStop = frameN # exact frame index
win.timeOnFlip(aperture, 'tStopRefresh') # time at next scr refresh
aperture.enabled = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
aperture.enabled = False # just in case it was left enabled
thisExp.addData('aperture.started', aperture.tStartRefresh)
thisExp.addData('aperture.stopped', aperture.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,460
|
Python
|
.py
| 137
| 43.10219
| 100
| 0.726607
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,449
|
correctQmixPumpComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctQmixPumpComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.0),
on May 10, 2019, at 11:15
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
from psychopy.hardware import qmix
# Initialize all pumps so they are ready to be used when we
# need them later. This enables us to dynamically select
# pumps during the experiment without worrying about their
# initialization.
qmix._init_all_pumps()
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.0'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newQmixPumpComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# Select the correct pre-initialized pump, and set the
# syringe type according to the Pumo Component properties.
_pumpInstance = qmix.pumps[0]
pump = qmix._PumpWrapperForBuilderComponent(_pumpInstance)
pump.syringeType = '50 mL glass'
pump.flowRateUnit = 'mL/s'
pump.status = None
# keep track of which components have finished
trialComponents = [pump]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *pump* updates
if t >= 0.0 and pump.status == NOT_STARTED:
# keep track of start time/frame for later
pump.tStart = t # not accounting for scr refresh
pump.frameNStart = frameN # exact frame index
win.timeOnFlip(pump, 'tStartRefresh') # time at next scr refresh
pump.status = STARTED
win.callOnFlip(pump.empty, flowRate=1.0)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if pump.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
pump.tStop = t # not accounting for scr refresh
pump.frameNStop = frameN # exact frame index
win.timeOnFlip(pump, 'tStopRefresh') # time at next scr refresh
pump.status = FINISHED
win.callOnFlip(pump.stop)
win.callOnFlip(pump.switchValvePosition)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
if pump.status == STARTED:
pump.stop()
pump.switchValvePosition()
thisExp.addData('pump.started', pump.tStart)
thisExp.addData('pump.stopped', pump.tStop)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,914
|
Python
|
.py
| 151
| 41.860927
| 100
| 0.729071
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,450
|
correctCodeComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctCodeComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newCodeComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = []
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 5,361
|
Python
|
.py
| 117
| 42.188034
| 100
| 0.731913
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,451
|
correctMovieComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctMovieComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newMovieComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
movie = visual.MovieStim3(
win=win, name='movie',
noAudio = False,
filename=None,
ori=0, pos=(0, 0), opacity=1,
loop=False,
depth=0.0,
)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [movie]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *movie* updates
if t >= 0.0 and movie.status == NOT_STARTED:
# keep track of start time/frame for later
movie.tStart = t # not accounting for scr refresh
movie.frameNStart = frameN # exact frame index
win.timeOnFlip(movie, 'tStartRefresh') # time at next scr refresh
movie.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if movie.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
movie.tStop = t # not accounting for scr refresh
movie.frameNStop = frameN # exact frame index
win.timeOnFlip(movie, 'tStopRefresh') # time at next scr refresh
movie.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('movie.started', movie.tStartRefresh)
thisExp.addData('movie.stopped', movie.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,367
|
Python
|
.py
| 140
| 41.371429
| 100
| 0.722016
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,452
|
correctMouseComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctMouseComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newMouseComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
mouse = event.Mouse(win=win)
x, y = [None, None]
mouse.mouseClock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# setup some python lists for storing info about the mouse
gotValidClick = False # until a click is received
# keep track of which components have finished
trialComponents = [mouse]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *mouse* updates
if t >= 0.0 and mouse.status == NOT_STARTED:
# keep track of start time/frame for later
mouse.tStart = t # not accounting for scr refresh
mouse.frameNStart = frameN # exact frame index
win.timeOnFlip(mouse, 'tStartRefresh') # time at next scr refresh
mouse.status = STARTED
mouse.mouseClock.reset()
prevButtonState = mouse.getPressed() # if button is down already this ISN'T a new click
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if mouse.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
mouse.tStop = t # not accounting for scr refresh
mouse.frameNStop = frameN # exact frame index
win.timeOnFlip(mouse, 'tStopRefresh') # time at next scr refresh
mouse.status = FINISHED
if mouse.status == STARTED: # only update if started and not finished!
buttons = mouse.getPressed()
if buttons != prevButtonState: # button state changed?
prevButtonState = buttons
if sum(buttons) > 0: # state changed to a new click
# abort routine on response
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# store data for thisExp (ExperimentHandler)
x, y = mouse.getPos()
buttons = mouse.getPressed()
thisExp.addData('mouse.x', x)
thisExp.addData('mouse.y', y)
thisExp.addData('mouse.leftButton', buttons[0])
thisExp.addData('mouse.midButton', buttons[1])
thisExp.addData('mouse.rightButton', buttons[2])
thisExp.addData('mouse.started', mouse.tStart)
thisExp.addData('mouse.stopped', mouse.tStop)
thisExp.nextEntry()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 7,189
|
Python
|
.py
| 155
| 42.174194
| 100
| 0.720714
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,453
|
correctParallelOutComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctParallelOutComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock, parallel
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newParallelOutComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
p_port = parallel.ParallelPort(address='0x0378')
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [p_port]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *p_port* updates
if t >= 0.0 and p_port.status == NOT_STARTED:
# keep track of start time/frame for later
p_port.tStart = t # not accounting for scr refresh
p_port.frameNStart = frameN # exact frame index
win.timeOnFlip(p_port, 'tStartRefresh') # time at next scr refresh
p_port.status = STARTED
win.callOnFlip(p_port.setData, int(1))
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if p_port.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
p_port.tStop = t # not accounting for scr refresh
p_port.frameNStop = frameN # exact frame index
win.timeOnFlip(p_port, 'tStopRefresh') # time at next scr refresh
p_port.status = FINISHED
win.callOnFlip(p_port.setData, int(0))
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
if p_port.status == STARTED:
win.callOnFlip(p_port.setData, int(0))
thisExp.addData('p_port.started', p_port.tStart)
thisExp.addData('p_port.stopped', p_port.tStop)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,431
|
Python
|
.py
| 137
| 42.839416
| 100
| 0.721725
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,454
|
correctMicrophoneComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctMicrophoneComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock, microphone
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newMicrophoneComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
wavDirName = filename + '_wav'
if not os.path.isdir(wavDirName):
os.makedirs(wavDirName) # to hold .wav files
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# Enable sound input/output:
microphone.switchOn()
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(2.000000)
# update component parameters for each repeat
mic_1 = microphone.AdvAudioCapture(name='mic_1', saveDir=wavDirName, stereo=False, chnl=0)
# keep track of which components have finished
trialComponents = [mic_1]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *mic_1* updates
if t >= 0.0 and mic_1.status == NOT_STARTED:
# keep track of start time/frame for later
mic_1.tStart = t # not accounting for scr refresh
mic_1.frameNStart = frameN # exact frame index
win.timeOnFlip(mic_1, 'tStartRefresh') # time at next scr refresh
mic_1.status = STARTED
mic_1.record(sec=2.0, block=False) # start the recording thread
if mic_1.status == STARTED and not mic_1.recorder.running:
mic_1.status = FINISHED
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# mic_1 stop & responses
mic_1.stop() # sometimes helpful
if not mic_1.savedFile:
mic_1.savedFile = None
# store data for thisExp (ExperimentHandler)
thisExp.addData('mic_1.filename', mic_1.savedFile)
thisExp.addData('mic_1.started', mic_1.tStart)
thisExp.addData('mic_1.stopped', mic_1.tStop)
thisExp.nextEntry()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,447
|
Python
|
.py
| 141
| 41.914894
| 100
| 0.727839
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,455
|
correctImageComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctImageComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newImageComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
image = visual.ImageStim(
win=win,
name='image',
image=None, mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [image]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if t >= 0.0 and image.status == NOT_STARTED:
# keep track of start time/frame for later
image.tStart = t # not accounting for scr refresh
image.frameNStart = frameN # exact frame index
win.timeOnFlip(image, 'tStartRefresh') # time at next scr refresh
image.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if image.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
image.tStop = t # not accounting for scr refresh
image.frameNStop = frameN # exact frame index
win.timeOnFlip(image, 'tStopRefresh') # time at next scr refresh
image.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('image.started', image.tStartRefresh)
thisExp.addData('image.stopped', image.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,460
|
Python
|
.py
| 140
| 42.007143
| 100
| 0.7217
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,456
|
correctKeyboardComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctKeyboardComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newKeyboardComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
key_resp = keyboard.Keyboard()
# keep track of which components have finished
trialComponents = [key_resp]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *key_resp* updates
if t >= 0.0 and key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
key_resp.tStart = t # not accounting for scr refresh
key_resp.frameNStart = frameN # exact frame index
win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh
key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(key_resp.clock.reset) # t=0 on next screen flip
key_resp.clearEvents(eventType='keyboard')
if key_resp.status == STARTED:
theseKeys = key_resp.getKeys(keyList=['y', 'n', 'left', 'right', 'space'], waitRelease=False)
if len(theseKeys):
theseKeys = theseKeys[0] # at least one key was pressed
# check for quit:
if "escape" == theseKeys:
endExpNow = True
key_resp.keys = theseKeys.name # just the last key pressed
key_resp.rt = theseKeys.rt
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if key_resp.keys in ['', [], None]: # No response was made
key_resp.keys = None
thisExp.addData('key_resp.keys',key_resp.keys)
if key_resp.keys != None: # we had a response
thisExp.addData('key_resp.rt', key_resp.rt)
thisExp.addData('key_resp.started', key_resp.tStartRefresh)
thisExp.addData('key_resp.stopped', key_resp.tStopRefresh)
thisExp.nextEntry()
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,859
|
Python
|
.py
| 148
| 41.783784
| 101
| 0.714221
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,457
|
correctStaticComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctStaticComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newStaticComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
text = visual.TextStim(win=win, name='text',
text='Any text\n\nincluding line breaks',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
ISI = clock.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI')
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [text, ISI]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text* updates
if t >= 0.0 and text.status == NOT_STARTED:
# keep track of start time/frame for later
text.tStart = t # not accounting for scr refresh
text.frameNStart = frameN # exact frame index
win.timeOnFlip(text, 'tStartRefresh') # time at next scr refresh
text.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if text.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
text.tStop = t # not accounting for scr refresh
text.frameNStop = frameN # exact frame index
win.timeOnFlip(text, 'tStopRefresh') # time at next scr refresh
text.setAutoDraw(False)
# *ISI* period
if t >= 0.0 and ISI.status == NOT_STARTED:
# keep track of start time/frame for later
ISI.tStart = t # not accounting for scr refresh
ISI.frameNStart = frameN # exact frame index
win.timeOnFlip(ISI, 'tStartRefresh') # time at next scr refresh
ISI.start(0.5)
elif ISI.status == STARTED: # one frame should pass before updating params and completing
# updating other components during *ISI*
text.setColor('white', colorSpace='rgb')
# component updates done
# Adding custom code for ISI
customStaticCode = True
ISI.complete() # finish the static period
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text.started', text.tStartRefresh)
thisExp.addData('text.stopped', text.tStopRefresh)
thisExp.addData('ISI.started', ISI.tStart)
thisExp.addData('ISI.stopped', ISI.tStop)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 7,278
|
Python
|
.py
| 156
| 42.217949
| 100
| 0.715798
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,458
|
correctPatchComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctPatchComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newPatchComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
patch = visual.PatchStim(
win=win, name='patch',
tex='sin', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5), sf=None, phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=1,
texRes=128
, interpolate=True, depth=0.0)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [patch]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *patch* updates
if t >= 0.0 and patch.status == NOT_STARTED:
# keep track of start time/frame for later
patch.tStart = t # not accounting for scr refresh
patch.frameNStart = frameN # exact frame index
win.timeOnFlip(patch, 'tStartRefresh') # time at next scr refresh
patch.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if patch.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
patch.tStop = t # not accounting for scr refresh
patch.frameNStop = frameN # exact frame index
win.timeOnFlip(patch, 'tStopRefresh') # time at next scr refresh
patch.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('patch.started', patch.tStartRefresh)
thisExp.addData('patch.stopped', patch.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,438
|
Python
|
.py
| 139
| 42.223022
| 100
| 0.721406
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,459
|
correctcedrusButtonBoxComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctcedrusButtonBoxComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock, hardware
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newcedrusButtonBoxComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
import pyxid2 as pyxid # to use the Cedrus response box
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
buttonBox = None
for n in range(10): # doesn't always work first time!
try:
devices = pyxid.get_xid_devices()
core.wait(0.1)
buttonBox = devices[0]
break # found a device so can break the loop
except Exception:
pass
if not buttonBox:
logging.error('could not find a Cedrus device.')
core.quit()
buttonBox.clock = core.Clock()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
buttonBox.keys = [] # to store response values
buttonBox.rt = []
buttonBox.status = None
# keep track of which components have finished
trialComponents = [buttonBox]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *buttonBox* updates
if t >= 0.0 and buttonBox.status == NOT_STARTED:
# keep track of start time/frame for later
buttonBox.tStart = t # not accounting for scr refresh
buttonBox.frameNStart = frameN # exact frame index
win.timeOnFlip(buttonBox, 'tStartRefresh') # time at next scr refresh
buttonBox.status = STARTED
buttonBox.clock.reset() # now t=0
# clear buttonBox responses (in a loop - the Cedrus own function doesn't work well)
buttonBox.poll_for_response()
while len(buttonBox.response_queue):
buttonBox.clear_response_queue()
buttonBox.poll_for_response() #often there are more resps waiting!
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if buttonBox.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
buttonBox.tStop = t # not accounting for scr refresh
buttonBox.frameNStop = frameN # exact frame index
win.timeOnFlip(buttonBox, 'tStopRefresh') # time at next scr refresh
buttonBox.status = FINISHED
if buttonBox.status == STARTED:
theseKeys=[]
theseRTs=[]
# check for key presses
buttonBox.poll_for_response()
while len(buttonBox.response_queue):
evt = buttonBox.get_next_response()
if evt['pressed']:
theseKeys.append(evt['key'])
theseRTs.append(buttonBox.clock.getTime())
buttonBox.poll_for_response()
buttonBox.clear_response_queue() # don't process again
if len(theseKeys) > 0: # at least one key was pressed
if buttonBox.keys == []: # then this is first keypress
buttonBox.keys = theseKeys[0] # the first key pressed
buttonBox.rt = theseRTs[0]
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if buttonBox.keys in ['', [], None]: # No response was made
buttonBox.keys = None
thisExp.addData('buttonBox.keys',buttonBox.keys)
if buttonBox.keys != None: # we had a response
thisExp.addData('buttonBox.rt', buttonBox.rt)
thisExp.addData('buttonBox.started', buttonBox.tStartRefresh)
thisExp.addData('buttonBox.stopped', buttonBox.tStopRefresh)
thisExp.nextEntry()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 8,235
|
Python
|
.py
| 180
| 40.722222
| 100
| 0.707518
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,460
|
correctEnvGratingComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctEnvGratingComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newEnvGratingComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
env_grating = visual.EnvelopeGrating(
win=win, name='env_grating',
carrier='sin', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5),
sf=1.0, phase=0.0,
color=[1,1,1], colorSpace='rgb',
opacity=1, contrast=0.5,
texRes=128, envelope='sin',
envori=0.0, envsf=1.0,
envphase=0.0, power=1.0,
moddepth=1.0, blendmode='avg', beat=False, interpolate=True, depth=0.0)
if sys.version[0]=='3' and np.min(win.gamma) == None:
logging.warning('Envelope grating in use with no gamma set. Unless you have hardware gamma correction the image will be distorted.')
elif np.min(win.gamma) < 1.01:
logging.warning('Envelope grating in use with window gamma <= 1.0 or no gamma set at all. Unless you have hardware gamma correction the image will be distorted.')
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [env_grating]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *env_grating* updates
if t >= 0.0 and env_grating.status == NOT_STARTED:
# keep track of start time/frame for later
env_grating.tStart = t # not accounting for scr refresh
env_grating.frameNStart = frameN # exact frame index
win.timeOnFlip(env_grating, 'tStartRefresh') # time at next scr refresh
env_grating.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if env_grating.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
env_grating.tStop = t # not accounting for scr refresh
env_grating.frameNStop = frameN # exact frame index
win.timeOnFlip(env_grating, 'tStopRefresh') # time at next scr refresh
env_grating.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('env_grating.started', env_grating.tStartRefresh)
thisExp.addData('env_grating.stopped', env_grating.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 7,087
|
Python
|
.py
| 147
| 44.108844
| 166
| 0.722914
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,461
|
correctTextComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctTextComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newTextComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
text = visual.TextStim(win=win, name='text',
text='Any text\n\nincluding line breaks',
font='Arial',
pos=(0, 0), height=0.1, wrapWidth=None, ori=0,
color='white', colorSpace='rgb', opacity=1,
languageStyle='LTR',
depth=0.0);
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [text]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *text* updates
if t >= 0.0 and text.status == NOT_STARTED:
# keep track of start time/frame for later
text.tStart = t # not accounting for scr refresh
text.frameNStart = frameN # exact frame index
win.timeOnFlip(text, 'tStartRefresh') # time at next scr refresh
text.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if text.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
text.tStop = t # not accounting for scr refresh
text.frameNStop = frameN # exact frame index
win.timeOnFlip(text, 'tStopRefresh') # time at next scr refresh
text.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('text.started', text.tStartRefresh)
thisExp.addData('text.stopped', text.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,439
|
Python
|
.py
| 139
| 42.18705
| 100
| 0.72145
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,462
|
correctJoyButtonsComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctJoyButtonsComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:54 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newJoyButtonsComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
from psychopy.hardware import joystick as joysticklib # joystick/gamepad accsss
from psychopy.experiment.components.joyButtons import virtualJoyButtons as virtualjoybuttonslib
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
button_resp = type('', (), {})() # Create an object to use as a name space
button_resp.device = None
button_resp.device_number = 0
try:
numJoysticks = joysticklib.getNumJoysticks()
if numJoysticks > 0:
button_resp.device = joysticklib.Joystick(0)
try:
joystickCache
except NameError:
joystickCache={}
if not 0 in joystickCache:
joystickCache[0] = joysticklib.Joystick(0)
button_resp.device = joystickCache[0]
else:
button_resp.device = virtualjoybuttonslib.VirtualJoyButtons(0)
logging.warning("joystick_{}: Using keyboard emulation 'ctrl' + 'Alt' + digit.".format(button_resp.device_number))
except Exception:
pass
if not button_resp.device:
logging.error('No joystick/gamepad device found.')
core.quit()
button_resp.status = None
button_resp.clock = core.Clock()
button_resp.numButtons = button_resp.device.getNumButtons()
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
# update component parameters for each repeat
button_resp.oldButtonState = button_resp.device.getAllButtons()[:]
button_resp.keys = []
button_resp.rt = []
# keep track of which components have finished
trialComponents = [button_resp]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *button_resp* updates
if t >= 0.0 and button_resp.status == NOT_STARTED:
# keep track of start time/frame for later
button_resp.tStart = t # not accounting for scr refresh
button_resp.frameNStart = frameN # exact frame index
win.timeOnFlip(button_resp, 'tStartRefresh') # time at next scr refresh
button_resp.status = STARTED
# joyButtons checking is just starting
win.callOnFlip(button_resp.clock.reset) # t=0 on next screen flip
if button_resp.status == STARTED:
button_resp.newButtonState = button_resp.device.getAllButtons()[:]
button_resp.pressedButtons = []
button_resp.releasedButtons = []
button_resp.newPressedButtons = []
if button_resp.newButtonState != button_resp.oldButtonState:
button_resp.pressedButtons = [i for i in range(button_resp.numButtons) if button_resp.newButtonState[i] and not button_resp.oldButtonState[i]]
button_resp.releasedButtons = [i for i in range(button_resp.numButtons) if not button_resp.newButtonState[i] and button_resp.oldButtonState[i]]
button_resp.oldButtonState = button_resp.newButtonState
button_resp.newPressedButtons = [i for i in [0, 1, 2, 3, 4] if i in button_resp.pressedButtons]
[logging.data("joystick_{}_button: {}".format(button_resp.device_number,i)) for i in button_resp.pressedButtons]
theseKeys = button_resp.newPressedButtons
if len(theseKeys) > 0: # at least one key was pressed
button_resp.keys = theseKeys[-1] # just the last key pressed
button_resp.rt = button_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if button_resp.keys in ['', [], None]: # No response was made
button_resp.keys=None
thisExp.addData('button_resp.keys',button_resp.keys)
if button_resp.keys != None: # we had a response
thisExp.addData('button_resp.rt', button_resp.rt)
thisExp.nextEntry()
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 8,644
|
Python
|
.py
| 180
| 43.255556
| 155
| 0.719615
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,463
|
correctDotsComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctDotsComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newDotsComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
dots = visual.DotStim(
win=win, name='dots',
nDots=100, dotSize=2,
speed=0.1, dir=0.0, coherence=1.0,
fieldPos=(0.0, 0.0), fieldSize=1.0,fieldShape='circle',
signalDots='same', noiseDots='direction',dotLife=3,
color=[1.0,1.0,1.0], colorSpace='rgb', opacity=1,
depth=0.0)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
dots.refreshDots()
# keep track of which components have finished
trialComponents = [dots]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *dots* updates
if t >= 0.0 and dots.status == NOT_STARTED:
# keep track of start time/frame for later
dots.tStart = t # not accounting for scr refresh
dots.frameNStart = frameN # exact frame index
win.timeOnFlip(dots, 'tStartRefresh') # time at next scr refresh
dots.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if dots.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
dots.tStop = t # not accounting for scr refresh
dots.frameNStop = frameN # exact frame index
win.timeOnFlip(dots, 'tStopRefresh') # time at next scr refresh
dots.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('dots.started', dots.tStartRefresh)
thisExp.addData('dots.stopped', dots.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,506
|
Python
|
.py
| 141
| 42.035461
| 100
| 0.721309
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,464
|
correctGratingComponent.py
|
psychopy_psychopy/psychopy/tests/data/correctScript/python/correctGratingComponent.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.1.1),
on Thu May 9 17:56:55 2019
If you publish work using this script please cite the PsychoPy publications:
Peirce, JW (2007) PsychoPy - Psychophysics software in Python.
Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.
Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
from psychopy.hardware import keyboard
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
# Store info about the experiment session
psychopyVersion = '3.1.1'
expName = 'untitled.py'
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='newGratingComponent.py',
savePickle=True, saveWideText=True,
dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(
size=(1024, 768), fullscr=True, screen=0,
winType='pyglet', allowGUI=False, allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
blendMode='avg', useFBO=True,
units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Initialize components for Routine "trial"
trialClock = core.Clock()
grating = visual.GratingStim(
win=win, name='grating',
tex='sin', mask=None,
ori=0, pos=(0, 0), size=(0.5, 0.5), sf=None, phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=1,blendmode='avg',
texRes=128, interpolate=True, depth=0.0)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [grating]
for thisComponent in trialComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *grating* updates
if t >= 0.0 and grating.status == NOT_STARTED:
# keep track of start time/frame for later
grating.tStart = t # not accounting for scr refresh
grating.frameNStart = frameN # exact frame index
win.timeOnFlip(grating, 'tStartRefresh') # time at next scr refresh
grating.setAutoDraw(True)
frameRemains = 0.0 + 1.0- win.monitorFramePeriod * 0.75 # most of one frame period left
if grating.status == STARTED and t >= frameRemains:
# keep track of stop time/frame for later
grating.tStop = t # not accounting for scr refresh
grating.frameNStop = frameN # exact frame index
win.timeOnFlip(grating, 'tStopRefresh') # time at next scr refresh
grating.setAutoDraw(False)
# check for quit (typically the Esc key)
if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
core.quit()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('grating.started', grating.tStartRefresh)
thisExp.addData('grating.stopped', grating.tStopRefresh)
# Flip one final time so any remaining win.callOnFlip()
# and win.timeOnFlip() tasks get executed before quitting
win.flip()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| 6,493
|
Python
|
.py
| 138
| 42.934783
| 100
| 0.723243
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,465
|
test_prefs.py
|
psychopy_psychopy/psychopy/tests/test_preferences/test_prefs.py
|
import pytest
import re
from psychopy import preferences
import psychopy.app as app
@pytest.mark.prefs
def testGenerateSpec():
# Get base spec
base = open(preferences.__folder__ / "baseNoArch.spec").read()
# Change theme default for use as a marker
base = re.sub(r"(?<=theme = string\(default=')PsychopyLight(?='\))", "PsychopyDark", base)
# Generate spec
preferences.generateSpec(baseSpec=base)
darwin = open(preferences.__folder__ / "Darwin.spec").read()
freeBSD = open(preferences.__folder__ / "FreeBSD.spec").read()
linux = open(preferences.__folder__ / "Linux.spec").read()
windows = open(preferences.__folder__ / "Windows.spec").read()
# Check for marker
assert all("theme = string(default='PsychopyDark')" in target for target in [darwin, freeBSD, linux, windows])
assert all("theme = string(default='PsychopyLight')" not in target for target in [darwin, freeBSD, linux, windows])
# Check generated prefs
prefs = preferences.Preferences()
prefs.resetPrefs()
assert prefs.app['theme'] == "PsychopyDark"
# Check that the app still loads
app.startApp(testMode=True, showSplash=False)
app.quitApp()
| 1,184
|
Python
|
.py
| 26
| 41.384615
| 119
| 0.701557
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,466
|
test_Liaison.py
|
psychopy_psychopy/psychopy/tests/test_liaison/test_Liaison.py
|
import threading
from psychopy import liaison, session, hardware
from psychopy.hardware import DeviceManager
from psychopy.tests import utils, skip_under_vm
from pathlib import Path
import json
import asyncio
import time
class TestingProtocol:
"""
Gives Liaison a protocol to communicate with, stores what it receives and raises any errors.
"""
messages = []
async def send(self, msg):
# parse message
msg = json.loads(msg)
# store message
self.messages.append(msg)
# raise any errors
if msg.get('type', None) == "error":
raise RuntimeError(msg['msg'])
return True
def clear(self):
self.messages = []
def runInLiaison(server, protocol, obj, method, *args):
cmd = {'object': obj, 'method': method, 'args': args}
asyncio.run(
server._processMessage(protocol, json.dumps(cmd))
)
@skip_under_vm
class TestLiaison:
def setup_class(self):
# create liaison server
self.server = liaison.WebSocketServer()
self.protocol = TestingProtocol()
self.server._connections = [self.protocol]
# add session to liaison server
self.server.registerClass(session.Session, "session")
runInLiaison(
self.server, self.protocol, "session", "init",
str(Path(utils.TESTS_DATA_PATH) / "test_session" / "root")
)
runInLiaison(
self.server, self.protocol, "session", "registerMethods"
)
# add device manager to liaison server
self.server.registerClass(hardware.DeviceManager, "DeviceManager")
runInLiaison(
self.server, self.protocol, "DeviceManager", "init"
)
runInLiaison(
self.server, self.protocol, "DeviceManager", "registerMethods"
)
# start Liaison
self.server.run("localhost", 8100)
# start session
runInLiaison(
self.server, self.protocol, "session", "start"
)
# setup window
runInLiaison(
self.server, self.protocol, "session", "setupWindowFromParams", "{}", "false"
)
def test_session_init(self):
assert "session" in self.server._methods
assert isinstance(self.server._methods['session'][0], session.Session)
def test_device_manager_init(self):
assert "DeviceManager" in self.server._methods
assert isinstance(self.server._methods['DeviceManager'][0], hardware.DeviceManager)
def test_basic_experiment(self):
runInLiaison(
self.server, self.protocol, "session", "addExperiment",
"exp1/exp1.psyexp", "exp1"
)
time.sleep(1)
runInLiaison(
self.server, self.protocol, "session", "runExperiment",
"exp1"
)
def test_future_trials(self):
# add experiment
runInLiaison(
self.server, self.protocol, "session", "addExperiment",
"testFutureTrials/testFutureTrials.psyexp", "testFutureTrials"
)
time.sleep(1)
# define a threaded task to run alongside experiment
def _thread():
# wait for first meaningful result
resp = None
i = 0
while resp is None and i < 24:
# get future trial
runInLiaison(
self.server, self.protocol, "session", "getFutureTrial",
"1", "True"
)
# get result
resp = json.loads(self.protocol.messages[-1]["result"])
# wait 0.1s
time.sleep(0.1)
# iterate towards limit
i += 1
# if we hit iteration limit, fail
assert i < 24, "Timed out waiting for a non-None result from getFutureTrial"
# does response have all the keys we expect?
expectedKeys = (
"type", "thisN", "thisRepN", "thisTrialN", "thisIndex", "data"
)
keysPresent = [key in resp for key in expectedKeys]
assert all(keysPresent), "Trial object missing key(s): {}".format(
expectedKeys[i] for i, val in enumerate(keysPresent) if not val
)
# resp should have type "trial_data"
assert resp['type'] == "trial_data", (
f"First non-None result from getFutureTrial doesn't look like a Trial object: {resp}"
)
# start thread
threading.Thread(target=_thread).start()
# run experiment
runInLiaison(
self.server, self.protocol, "session", "runExperiment",
"testFutureTrials"
)
def test_experiment_error(self):
"""
Test that an error in an experiment is sent to Liaison properly
"""
# run an experiment with an error in it
runInLiaison(
self.server, self.protocol, "session", "addExperiment",
"error/error.psyexp", "error"
)
time.sleep(1)
try:
runInLiaison(
self.server, self.protocol, "session", "runExperiment",
"error"
)
except RuntimeError as err:
# we expect an error from this experiment, so don't crash the whole process
pass
# check that the error looks right in Liaison's output
assert self.protocol.messages[-1]['context'] == "error"
def test_add_device_with_listener(self):
# add keyboard
runInLiaison(
self.server, self.protocol, "DeviceManager", "addDevice",
"psychopy.hardware.keyboard.KeyboardDevice", "defaultKeyboard"
)
# get keyboard from device manager
kb = hardware.DeviceManager.getDevice("defaultKeyboard")
# make sure we got it
from psychopy.hardware.keyboard import KeyboardDevice, KeyPress
assert isinstance(kb, KeyboardDevice)
# add listener
runInLiaison(
self.server, self.protocol, "DeviceManager", "addListener",
"defaultKeyboard", "liaison", "True"
)
time.sleep(1)
# send dummy message
kb.receiveMessage(
KeyPress("a", 1234)
)
time.sleep(1)
# check that message was sent to Liaison
lastMsg = self.protocol.messages[-1]
assert lastMsg['type'] == "hardware_response"
assert lastMsg['class'] == "KeyPress"
assert lastMsg['data']['t'] == 1234
assert lastMsg['data']['value'] == "a"
def test_actualize_session_win(self):
"""
Test that attribute strings (e.g. "session.win") are actualized by Liaison to be the
object they represent.
"""
# add screen buffer photodiode
runInLiaison(
self.server, self.protocol, "DeviceManager", "addDevice",
"psychopy.hardware.photodiode.ScreenBufferSampler", "screenBuffer",
"session.win"
)
# get screen buffer photodidoe
device = DeviceManager.getDevice("screenBuffer")
# make sure its window is a window object
from psychopy.visual import Window
assert isinstance(device.win, Window)
def test_device_by_name(self):
"""
Test that adding a device by name to the device manager prior to running means Components
using that named device use the one set up in device manager, rather than setting it up
again according to the Component params.
"""
# add experiment which creates a button box with different buttons
runInLiaison(
self.server, self.protocol, "session", "addExperiment",
"testNamedButtonBox/testNamedButtonBox.psyexp", "testNamedButtonBox"
)
# setup generic devices (use exp1 as a template)
runInLiaison(
self.server, self.protocol, "session", "addExperiment",
"exp1/exp1.psyexp", "exp1"
)
runInLiaison(
self.server, self.protocol, "session", "setupDevicesFromExperiment",
"exp1"
)
# add keyboard button box with abc as its buttons
runInLiaison(
self.server, self.protocol, "DeviceManager", "addDevice",
"psychopy.hardware.button.KeyboardButtonBox", "testNamedButtonBox",
'["a", "b", "c"]'
)
# run experiment
runInLiaison(
self.server, self.protocol, "session", "runExperiment",
"testNamedButtonBox"
)
def test_device_JSON(self):
cases = {
'testMic': "psychopy.hardware.microphone.MicrophoneDevice",
'testPhotodiode': "psychopy.hardware.photodiode.ScreenBufferSampler",
'testButtonBox': "psychopy.hardware.button.KeyboardButtonBox"
}
for deviceName, deviceClass in cases.items():
# get the first available device
available = DeviceManager.getAvailableDevices(deviceClass)
if not available:
continue
profile = available[0]
# replace deviceName
profile['deviceName'] = deviceName
# setup device
DeviceManager.addDevice(**profile)
# call getDevice from Liaison
runInLiaison(
self.server, self.protocol, "DeviceManager", "getDevice",
deviceName
)
# get message
result = self.protocol.messages[-1]['result']
# whatever is returned should be json serializable, load it to confirm that it is
json.loads(result)
def test_device_error(self):
# add a device in a way which will trigger an error
runInLiaison(
self.server, self.protocol, "DeviceManager", "addDevice",
"psychopy.hardware.keyboard.KeyboardDevice", "testWrongKeyboard",
"-1", "wrong", "wrong", "wrong",
)
time.sleep(1)
# make sure error looks correct in JSON format
result = self.protocol.messages[-1]
assert result['type'] == "hardware_error"
assert "psychopy.hardware.manager.ManagedDeviceError" in result['msg']
| 10,232
|
Python
|
.py
| 256
| 29.738281
| 101
| 0.601326
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,467
|
test_TrialHandler2.py
|
psychopy_psychopy/psychopy/tests/test_data/test_TrialHandler2.py
|
"""Tests for psychopy.data.DataHandler"""
import os
import glob
from os.path import join as pjoin
import shutil
from tempfile import mkdtemp, mkstemp
import numpy as np
import io
import json_tricks
import pytest
from psychopy import data
from psychopy.tools.filetools import fromFile
from psychopy.tests import utils
thisPath = os.path.split(__file__)[0]
fixturesPath = os.path.join(thisPath,'..','data')
class TestTrialHandler2:
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.rootName = 'test_data_file'
self.conditions = [dict(foo=1, bar=2),
dict(foo=2, bar=3),
dict(foo=3, bar=4)]
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_th1_indexing_unchanged(self):
"""
Checks that indexing style is the same for TrialHandler2 as TrialHandler
"""
# make both trial handlers
th1 = data.trial.TrialHandler(self.conditions, nReps=3, method="sequential")
th2 = data.trial.TrialHandler2(self.conditions, nReps=3, method="sequential")
# start a trials loop
for n in range(9):
# iterate trial
th1.next()
th2.next()
# make sure thisN is the same
for attr in ("thisN", "thisIndex", "thisRepN", "thisTrialN"):
assert getattr(th1, attr) == getattr(th2, attr), (
f"Expected `.{attr}` to be the same between TrialHandler and TrialHandler2, "
f"but on iteration {n} got {getattr(th1, attr)} for TrialHandler and "
f"{getattr(th2, attr)} for TrialHandler2."
)
def test_underscores_in_datatype_names2(self):
trials = data.TrialHandler2([], 1, autoLog=False)
for trial in trials: # need to run trials or file won't be saved
trials.addData('with_underscore', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
# Make sure the file is there
data_filename = base_data_filename + '.csv'
trials.saveAsWideText(data_filename, delim=',', appendFile=False)
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
with io.open(data_filename, 'r', encoding='utf-8-sig') as f:
header = f.readline()
expected_header = u'n,with_underscore_mean,with_underscore_raw,with_underscore_std,order\n'
if expected_header != header:
print(base_data_filename)
print(repr(expected_header),type(expected_header),len(expected_header))
print(repr(header), type(header), len(header))
#so far the headers don't match those from TrialHandler so this would fail
#assert expected_header == unicode(header)
def test_psydat_filename_collision_renaming2(self):
for count in range(1,20):
trials = data.TrialHandler2([], 1, autoLog=False)
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename)
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there. (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*.psydat")))
assert matches==count, "Found %d matching files, should be %d" % (matches, count)
def test_psydat_filename_collision_overwriting2(self):
for count in [1, 10, 20]:
trials = data.TrialHandler2([], 1, autoLog=False)
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName+'overwrite')
trials.saveAsPickle(base_data_filename, fileCollisionMethod='overwrite')
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there. (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*overwrite.psydat")))
assert matches==1, "Found %d matching files, should be %d" % (matches, count)
def test_multiKeyResponses2(self):
pytest.skip() # temporarily; this test passed locally but not under travis, maybe PsychoPy version of the .psyexp??
dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat'))
def test_psydat_filename_collision_failure2(self):
with pytest.raises(IOError):
for count in range(1,3):
trials = data.TrialHandler2([], 1, autoLog=False)
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename, fileCollisionMethod='fail')
def test_psydat_filename_collision_output2(self):
# create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
trials = data.TrialHandler2(trialList=conditions, seed=self.random_seed,
nReps=3, method='fullRandom', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
trials.addData('resp', resp)
trials.addData('rand', randResp)
# test wide data outputs
trials.saveAsWideText(pjoin(self.temp_dir, 'testFullRandom.csv'),
delim=',', appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testFullRandom.csv'),
pjoin(fixturesPath,'corrFullRandomTH2.csv'))
def test_random_data_output2(self):
# create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
trials= data.TrialHandler2(trialList=conditions, seed=self.random_seed,
nReps=3, method='random', autoLog=False)
#simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = np.round(rng.rand(), 9)
trials.addData('resp', resp)
trials.addData('rand', randResp)
# test wide data outputs
trials.saveAsWideText(pjoin(self.temp_dir, 'testRandom.csv'),
delim=',', appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testRandom.csv'),
pjoin(fixturesPath,'corrRandomTH2.csv'))
def test_comparison_equals(self):
t1 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
t2 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
assert t1 == t2
def test_comparison_equals_after_iteration(self):
t1 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
t2 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
t1.__next__()
t2.__next__()
assert t1 == t2
def test_comparison_not_equal(self):
t1 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
t2 = data.TrialHandler2([dict(foo=1)], 3, seed=self.random_seed)
assert t1 != t2
def test_comparison_not_equal_after_iteration(self):
t1 = data.TrialHandler2([dict(foo=1)], 2, seed=self.random_seed)
t2 = data.TrialHandler2([dict(foo=1)], 3, seed=self.random_seed)
t1.__next__()
t2.__next__()
assert t1 != t2
def test_json_dump(self):
t = data.TrialHandler2(self.conditions, nReps=5)
dump = t.saveAsJson()
t.origin = ''
t_loaded = json_tricks.loads(dump)
t_loaded._rng = np.random.default_rng()
t_loaded._rng.bit_generator.state = t_loaded._rng_state
del t_loaded._rng_state
assert t == t_loaded
def test_json_dump_with_data(self):
t = data.TrialHandler2(self.conditions, nReps=5)
t.addData('foo', 'bar')
dump = t.saveAsJson()
t.origin = ''
t_loaded = json_tricks.loads(dump)
t_loaded._rng = np.random.default_rng()
t_loaded._rng.bit_generator.state = t_loaded._rng_state
del t_loaded._rng_state
assert t == t_loaded
def test_json_dump_after_iteration(self):
t = data.TrialHandler2(self.conditions, nReps=5)
t.__next__()
dump = t.saveAsJson()
t.origin = ''
t_loaded = json_tricks.loads(dump)
t_loaded._rng = np.random.default_rng()
t_loaded._rng.bit_generator.state = t_loaded._rng_state
del t_loaded._rng_state
assert t == t_loaded
def test_json_dump_with_data_after_iteration(self):
t = data.TrialHandler2(self.conditions, nReps=5)
t.addData('foo', 'bar')
t.__next__()
dump = t.saveAsJson()
t.origin = ''
t_loaded = json_tricks.loads(dump)
t_loaded._rng = np.random.default_rng()
t_loaded._rng.bit_generator.state = t_loaded._rng_state
del t_loaded._rng_state
assert t == t_loaded
def test_json_dump_to_file(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.json')
t = data.TrialHandler2(self.conditions, nReps=5)
t.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
def test_json_dump_and_reopen_file(self):
t = data.TrialHandler2(self.conditions, nReps=5)
t.addData('foo', 'bar')
t.__next__()
_, path = mkstemp(dir=self.temp_dir, suffix='.json')
t.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
t.origin = ''
t_loaded = fromFile(path)
assert t == t_loaded
def test_getAllTrials(self):
"""
Check that TrialHandler2.getAllTrials returns as expected
"""
# make a trial handler
t = data.TrialHandler2(
self.conditions,
nReps=2,
method="sequential"
)
# check that calling now (before upcoming trials are calculated) doesn't break anything
trials, i = t.getAllTrials()
assert trials == [None]
assert i == 0
# move on to the first trial, triggering upcoming trials to be calculated
t.__next__()
# get an exemplar array of what trials should look like
exemplar, _ = t.getAllTrials()
# define array of cases to try
cases = [
{'advance': 2, 'i': 2},
{'advance': 1, 'i': 3},
{'advance': -2, 'i': 1},
]
# try cases
for case in cases:
# account for current iteration ending (as if in experiment)
t.__next__()
# move forwards/backwards according to case values
if case['advance'] >= 0:
t.skipTrials(case['advance'])
else:
t.rewindTrials(case['advance'])
# get trials
trials, i = t.getAllTrials()
# make sure array is unchanged and i is as we expect
assert trials == exemplar
assert i == case['i']
def test_getFutureTrials(self):
"""
Check that TrialHandler2 can return future trials correctly.
"""
# make a trial handler
t = data.TrialHandler2(
self.conditions,
nReps=2,
method="sequential"
)
# check that calling now (before upcoming trials are calculated) doesn't break anything
up1 = t.getFutureTrial(1)
ups3 = t.getFutureTrials(3)
# move on to the first trial, triggering upcoming trials to be calculated
t.__next__()
# define array of answers
answers = [
{'thisN': 5, 'thisRepN': 1, 'thisTrialN': 2, 'thisIndex': 2},
{'thisN': 1, 'thisRepN': 0, 'thisTrialN': 1, 'thisIndex': 1},
{'thisN': 2, 'thisRepN': 0, 'thisTrialN': 2, 'thisIndex': 2},
{'thisN': 3, 'thisRepN': 1, 'thisTrialN': 0, 'thisIndex': 0},
{'thisN': 4, 'thisRepN': 1, 'thisTrialN': 1, 'thisIndex': 1},
{'thisN': 5, 'thisRepN': 1, 'thisTrialN': 2, 'thisIndex': 2},
None,
]
# get future trials
for n in range(7):
trial = t.getFutureTrial(n)
if trial is not None:
# if we got a trial, make sure each attribute matches expected
for key in answers[n]:
assert getattr(trial, key) == answers[n][key]
else:
# if we got None, make sure we were expecting to
assert answers[n] is None
# test getting all trials
trials = t.getFutureTrials(None)
for i in range(len(trials)):
assert trials[i] == t.upcomingTrials[i]
def test_skipTrials_rewindTrials(self):
# make trial hancler
t = data.TrialHandler2(
self.conditions,
nReps=2,
method="sequential"
)
t.__next__()
# some values to move forwards/backwards by and the values at that point
cases = [
# move backwards and forwards and check we land in the right place
(+4, {'thisN': 4, 'thisRepN': 1, 'thisTrialN': 1, 'thisIndex': 1}),
(-1, {'thisN': 3, 'thisRepN': 1, 'thisTrialN': 0, 'thisIndex': 0}),
(-3, {'thisN': 0, 'thisRepN': 0, 'thisTrialN': 0, 'thisIndex': 0}),
(+2, {'thisN': 2, 'thisRepN': 0, 'thisTrialN': 2, 'thisIndex': 2}),
(-1, {'thisN': 1, 'thisRepN': 0, 'thisTrialN': 1, 'thisIndex': 1}),
(+2, {'thisN': 3, 'thisRepN': 1, 'thisTrialN': 0, 'thisIndex': 0}),
# move back past the start and check we land at the start
(-10, {'thisN': 0, 'thisRepN': 0, 'thisTrialN': 0, 'thisIndex': 0}),
# move forwards past the end and check we land at the end
(+10, {'thisN': 5, 'thisRepN': 1, 'thisTrialN': 2, 'thisIndex': 2}),
]
# iterate through cases
for inc, answer in cases:
# account for current iteration ending (as if in experiment)
t.__next__()
if inc < 0:
# if increment is negative, rewind
t.rewindTrials(inc)
else:
# if positive, skip
t.skipTrials(inc)
# check that new current Trial is correct
for key in answer:
assert getattr(t.thisTrial, key) == answer[key], (
f"Was expecting current trial to match all fields {answer}, instead was "
f"{t.thisTrial.getDict()} (different {key})"
)
# check that trials are still in the correct order
if t.upcomingTrials:
assert t.upcomingTrials[0].thisN == t.thisTrial.thisN + 1
else:
# if there's no upcoming trials, thisN should be 5
assert t.thisTrial.thisN == 5
if t.elapsedTrials:
assert t.elapsedTrials[-1].thisN == t.thisTrial.thisN - 1
else:
# if there's no elapsed trials, thisN should be 0
assert t.thisTrial.thisN == 0
def test_finished(self):
# make trial hancler
t = data.TrialHandler2(
self.conditions,
nReps=2,
method="sequential"
)
t.__next__()
# there are trials remaining, so .finished should be False
assert not t.finished
# try setting .finished and confirm that subsequent trials are skipped
t.finished = True
assert not len(t.upcomingTrials)
# now set not finished and confirm trials are back
t.finished = False
assert len(t.upcomingTrials)
# now skip past the end and confirm that .finished is True again
t.skipTrials(n=100)
assert t.finished
class TestTrialHandler2Output():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def setup_method(self, method):
# create conditions
conditions = []
for trialType in range(5):
conditions.append({'trialType':trialType})
self.trials = data.TrialHandler2(trialList=conditions,
seed=self.random_seed,
nReps=3, method='random',
autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in self.trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
self.trials.addData('resp', resp)
self.trials.addData('rand', randResp)
def test_output_no_filename_no_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = self.trials.columns
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_comma_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ','
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.csv'
assert os.path.isfile(path + expected_suffix)
expected_header = self.trials.columns
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_tab_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = '\t'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_header = self.trials.columns
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_semicolon_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.txt'
assert os.path.isfile(path + expected_suffix)
expected_header = self.trials.columns
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_delim = ','
expected_header = self.trials.columns
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_arbitrary_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.xyz')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = self.trials.columns
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_and_semicolon(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
assert os.path.isfile(path)
expected_delim = ';'
expected_header = self.trials.columns
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_conditions_from_csv(self):
conditions_file = pjoin(fixturesPath, 'trialTypes.csv')
trials = data.TrialHandler2(conditions_file, nReps=1)
assert type(trials.columns) == list
for _ in trials:
pass
def test_conditions_from_xlsx(self):
conditions_file = pjoin(fixturesPath, 'trialTypes.xlsx')
trials = data.TrialHandler2(conditions_file, nReps=1)
assert type(trials.columns) == list
for _ in trials:
pass
if __name__ == '__main__':
pytest.main()
| 21,986
|
Python
|
.py
| 469
| 36.017058
| 124
| 0.594949
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,468
|
test_TrialHandlerExt.py
|
psychopy_psychopy/psychopy/tests/test_data/test_TrialHandlerExt.py
|
"""Tests for psychopy.data.TrialHandlerExt
So far, just copies tests for TrialHandler, no further test of weights etc.
Maybe not worth doing if TrialHandler2 is going to have weights eventually.
"""
import os, glob
from os.path import join as pjoin
import shutil
from tempfile import mkdtemp, mkstemp
import numpy as np
import io
import pytest
from psychopy import data
from psychopy.tools.filetools import fromFile
from psychopy.tests import utils
thisPath = os.path.split(__file__)[0]
fixturesPath = os.path.join(thisPath, '..', 'data')
class TestTrialHandlerExt():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.rootName = 'test_data_file'
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_underscores_in_datatype_names(self):
trials = data.TrialHandlerExt([], 1, autoLog=False)
trials.data.addDataType('with_underscore')
for trial in trials:#need to run trials or file won't be saved
trials.addData('with_underscore', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsExcel(base_data_filename)
trials.saveAsText(base_data_filename, delim=',')
# Make sure the file is there
data_filename = base_data_filename + '.csv'
assert os.path.exists(data_filename), "File not found: %s" % os.path.abspath(data_filename)
with io.open(data_filename, 'r', encoding='utf-8-sig') as f:
header = f.readline()
expected_header = u'n,with_underscore_mean,with_underscore_raw,with_underscore_std,order\n'
if expected_header != header:
print(base_data_filename)
print(repr(expected_header),type(expected_header),len(expected_header))
print(repr(header), type(header), len(header))
assert expected_header == str(header)
def test_psydat_filename_collision_renaming(self):
for count in range(1,20):
trials = data.TrialHandlerExt([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename)
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there. (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*.psydat")))
assert matches==count, "Found %d matching files, should be %d" % (matches, count)
def test_psydat_filename_collision_overwriting(self):
for count in [1, 10, 20]:
trials = data.TrialHandlerExt([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName+'overwrite')
trials.saveAsPickle(base_data_filename, fileCollisionMethod='overwrite')
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there.
# (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*overwrite.psydat")))
assert matches==1, "Found %d matching files, should be %d" % (matches, count)
def test_multiKeyResponses(self):
pytest.skip()
# temporarily; this test passed locally but not under travis,
# maybe PsychoPy version of the .psyexp??
dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat'))
# test csv output
dat.saveAsText(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'),
appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'),
pjoin(fixturesPath,'corrMultiKeyTrials.csv'))
# test xlsx output
dat.saveAsExcel(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'),
appendFile=False)
utils.compareXlsxFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'),
pjoin(fixturesPath,'corrMultiKeyTrials.xlsx'))
def test_psydat_filename_collision_failure(self):
with pytest.raises(IOError):
for count in range(1,3):
trials = data.TrialHandlerExt([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials: # need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename, fileCollisionMethod='fail')
def test_psydat_filename_collision_output(self):
# create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
trials= data.TrialHandlerExt(trialList=conditions,
seed=self.random_seed,
nReps=3, method='fullRandom',
autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp'+str(thisTrial['trialType'])
randResp = rng.rand()
trials.addData('resp', resp)
trials.addData('rand', randResp)
# test summarised data outputs #this omits values
trials.saveAsText(pjoin(self.temp_dir, 'testFullRandom.tsv'),
stimOut=['trialType'] ,appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testFullRandom.tsv'),
pjoin(fixturesPath,'corrFullRandom.tsv'))
# test wide data outputs #this omits values
trials.saveAsWideText(pjoin(self.temp_dir, 'testFullRandom.csv'),
delim=',', appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testFullRandom.csv'),
pjoin(fixturesPath,'corrFullRandom.csv'))
def test_random_data_output(self):
# create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
trials= data.TrialHandlerExt(trialList=conditions, seed=100, nReps=3,
method='random', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp'+str(thisTrial['trialType'])
randResp = rng.rand()
trials.addData('resp', resp)
trials.addData('rand', randResp)
# test summarised data outputs
# this omits values
trials.saveAsText(pjoin(self.temp_dir, 'testRandom.tsv'),
stimOut=['trialType'], appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testRandom.tsv'),
pjoin(fixturesPath,'corrRandom.tsv'))
# test wide data outputs
trials.saveAsWideText(pjoin(self.temp_dir, 'testRandom.csv'),
delim=',', appendFile=False) # this omits values
utils.compareTextFiles(pjoin(self.temp_dir, 'testRandom.csv'),
pjoin(fixturesPath,'corrRandom.csv'))
def test_comparison_equals(self):
t1 = data.TrialHandlerExt([dict(foo=1)], 2)
t2 = data.TrialHandlerExt([dict(foo=1)], 2)
assert t1 == t2
def test_comparison_equals_after_iteration(self):
t1 = data.TrialHandlerExt([dict(foo=1)], 2)
t2 = data.TrialHandlerExt([dict(foo=1)], 2)
t1.__next__()
t2.__next__()
assert t1 == t2
def test_comparison_not_equal(self):
t1 = data.TrialHandlerExt([dict(foo=1)], 2)
t2 = data.TrialHandlerExt([dict(foo=1)], 3)
assert t1 != t2
def test_comparison_not_equal_after_iteration(self):
t1 = data.TrialHandlerExt([dict(foo=1)], 2)
t2 = data.TrialHandlerExt([dict(foo=1)], 3)
t1.__next__()
t2.__next__()
assert t1 != t2
class TestTrialHandlerOutput():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def setup_method(self, method):
# create conditions
conditions = []
for trialType in range(5):
conditions.append({'trialType':trialType})
self.trials = data.TrialHandlerExt(
trialList=conditions, seed=self.random_seed, nReps=3,
method='random', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in self.trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
self.trials.addData('resp', resp)
self.trials.addData('rand', randResp)
def test_output_no_filename_no_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_comma_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ','
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.csv'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_tab_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = '\t'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_semicolon_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.txt'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_delim = ','
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_arbitrary_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.xyz')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_and_semicolon(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
assert os.path.isfile(path)
expected_delim = ';'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
if __name__ == '__main__':
pytest.main()
| 14,284
|
Python
|
.py
| 281
| 40.142349
| 104
| 0.62535
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,469
|
test_fitFunctions.py
|
psychopy_psychopy/psychopy/tests/test_data/test_fitFunctions.py
|
"""Tests for psychopy.data.DataHandler"""
import numpy
from scipy import special
from pytest import raises
PLOTTING = False #turn this on to check it all looks right too
if PLOTTING:
import pylab
from psychopy import data
def cumNorm(xx, sd, thresh, chance=0.5):
"""For a given x value (e.g. contrast) returns the probability (y) of
the subject responding yes (or 'correctly')
"""
xx = numpy.asarray(xx)
y = (special.erf((xx-thresh) / (numpy.sqrt(2) * sd)) + 1) * 0.5 # NB numpy.special.erf() goes from -1:1
# y = special.erf((xx - thresh)*slope)/2.0+0.5 #cum norm from 0-1
y = y * (1 - chance) + chance # scale to be from chance to 1
return y
#create some data to test
thresh=0.2
sd=0.1
contrasts = numpy.linspace(0.0,0.5,10)
responses = cumNorm(contrasts, sd=sd, thresh=thresh)
def plotFit(fittedResps, thresh, title):
pylab.figure()
pylab.plot(contrasts, responses, 'o')
pylab.plot(contrasts, fittedResps)
pylab.plot([0,thresh],[0.75,0.75],'--b')#horiz
pylab.plot([thresh,thresh],[0.,0.75],'--b')#vert
pylab.title(title)
def test_fitNakaRushton():
#the data are actually from a cum norm so this should be exact
fit = data.FitNakaRushton(contrasts, responses)
assert numpy.allclose([ 0.21105363, 3.19844141, 0.5233062, 1.04135427 ], fit.params,
atol=1e-004, rtol=1e-004 )
modResps = fit.eval(contrasts)
#check that inverse works too
invs = fit.inverse(modResps)
assert numpy.allclose(contrasts,invs)#inverse should match the forwards function
#plot if needed
if PLOTTING:
plotFit(modResps, thresh, 'Naka-Rushton (params=%s)' %(fit.params))
def test_fitCumNorm():
#the data are actually from a cum norm so this should be exact
fit = data.FitCumNormal(contrasts, responses, display=0, expectedMin=0.5)
assert numpy.allclose([thresh,sd], fit.params)
modResps = fit.eval(contrasts)
#check that inverse works too
invs = fit.inverse(responses)
assert numpy.allclose(contrasts,invs)#inverse should match the forwards function
#plot if needed
if PLOTTING:
plotFit(modResps, thresh, 'CumulativeNormal (thresh=%.2f, params=%s)' %(fit.inverse(0.75), fit.params))
def test_weibull():
#fit to the fake data
fit = data.FitWeibull(contrasts, responses, display=0, expectedMin=0.5)
#check threshold is close (maybe not identical because not same function)
assert thresh-fit.inverse(0.75)<0.01
#check that inverse works too
modResps = fit.eval(contrasts)
invs = fit.inverse(modResps)
assert numpy.allclose(contrasts,invs), contrasts-invs#inverse should match the forwards function
#do a plot to check fits look right
if PLOTTING:
plotFit(modResps, thresh, 'Weibull (thresh=%.2f, params=%s)' %(fit.inverse(0.75), fit.params))
def test_logistic():
#fit to the fake data
fit = data.FitLogistic(contrasts, responses, display=0, expectedMin=0.5)
#check threshold is close (maybe not identical because not same function)
assert thresh-fit.inverse(0.75)<0.001
#check that inverse works too
modResps = fit.eval(contrasts)
invs = fit.inverse(modResps)
assert numpy.allclose(contrasts,invs), contrasts-invs#inverse should match the forwards function
#do a plot to check fits look right
if PLOTTING:
plotFit(modResps, thresh, 'Logistic (thresh=%.2f, params=%s)' %(fit.inverse(0.75), fit.params))
def teardown_method():
if PLOTTING:
pylab.show()
if __name__=='__main__':
# test_fitCumNorm()
# test_weibull()
# test_logistic()
test_fitNakaRushton()
if PLOTTING:
pylab.show()
| 3,670
|
Python
|
.py
| 86
| 38.081395
| 111
| 0.700196
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,470
|
test_StairHandlers.py
|
psychopy_psychopy/psychopy/tests/test_data/test_StairHandlers.py
|
"""Test StairHandler"""
import numpy as np
import shutil
import json_tricks
from tempfile import mkdtemp, mkstemp
from operator import itemgetter
import pytest
from psychopy import data, logging
from psychopy.tools.filetools import fromFile
logging.console.setLevel(logging.DEBUG)
DEBUG = False
np.random.seed(1000)
class _BaseTestStairHandler():
def setup_method(self):
self.tmp_dir = mkdtemp(prefix='psychopy-tests-%s' %
type(self).__name__)
self.stairs = None
self.responses = []
self.intensities = []
self.reversalIntensities = []
self.reversalPoints = []
self.exp = data.ExperimentHandler(
name='testExp',
savePickle=True,
saveWideText=True,
dataFileName=('%sx' % self.tmp_dir)
)
if DEBUG:
print(self.tmp_dir)
def teardown_method(self):
shutil.rmtree(self.tmp_dir)
def simulate(self):
"""
Simulate a staircase run.
"""
self.exp.addLoop(self.stairs)
for trialN, _ in enumerate(self.stairs):
self.stairs.addResponse(self.responses[trialN])
self.stairs.addOtherData(
'RT', 0.1 + 2*np.random.random_sample(1)
)
self.exp.nextEntry()
def checkSimulationResults(self):
"""
Verify the results of a simulated staircase run.
"""
stairs = self.stairs
responses = self.responses
intensities = self.intensities
reversalPoints = self.reversalPoints
reversalIntensities = self.reversalIntensities
assert stairs.finished # Staircase terminated normally.
assert stairs.data == responses # Responses were stored correctly.
# Trial count starts at zero.
assert stairs.thisTrialN == len(stairs.data) - 1
# Intensity values are sane.
assert np.min(stairs.intensities) >= stairs.minVal
assert np.max(stairs.intensities) <= stairs.maxVal
assert np.allclose(stairs.intensities, intensities)
# Reversal values are sane.
if stairs.nReversals is not None:
# The first trial can never be a reversal.
assert stairs.nReversals <= len(stairs.data) - 1
assert len(stairs.reversalPoints) >= stairs.nReversals
assert len(stairs.reversalIntensities) >= stairs.nReversals
if stairs.reversalPoints:
assert stairs.reversalIntensities
if stairs.reversalIntensities:
assert stairs.reversalPoints
if stairs.reversalPoints:
assert (len(stairs.reversalPoints) ==
len(stairs.reversalIntensities))
if reversalIntensities:
assert np.allclose(stairs.reversalIntensities,
reversalIntensities)
if reversalPoints:
assert stairs.reversalPoints == reversalPoints
class _BaseTestMultiStairHandler(_BaseTestStairHandler):
def checkSimulationResults(self):
"""
Verify the results of a simulated staircase run.
"""
stairs = self.stairs
responses = self.responses
intensities = self.intensities
assert all([s.finished for s in stairs.staircases])
assert (sum([len(s.data) for s in stairs.staircases]) ==
len(responses))
assert (sum([len(s.intensities) for s in stairs.staircases]) ==
len(intensities))
assert (sum([len(s.data) for s in stairs.staircases]) ==
sum([len(s.intensities) for s in stairs.staircases]))
class TestStairHandler(_BaseTestStairHandler):
"""
Test StairHandler, but with the ExperimentHandler attached as well.
"""
def test_StairHandlerLinear(self):
nTrials = 20
startVal, minVal, maxVal = 0.8, 0, 1
stepSizes = [0.1, 0.01, 0.001]
nUp, nDown = 1, 3
nReversals = 4
stepType = 'lin'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=3, nCorrect=4, nIncorrect=4, length=20
)
self.intensities = [
0.8, 0.7, 0.6, 0.5, 0.4, 0.41, 0.42, 0.43, 0.44, 0.44, 0.44,
0.439, 0.439, 0.44, 0.441, 0.442, 0.443, 0.443, 0.443, 0.442
]
self.reversalPoints = [4, 10, 12, 18]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_StairHandlerLog(self):
nTrials = 20
startVal, minVal, maxVal = 0.8, 0, 1
# We try to reproduce the values from test_StairHandlerDb().
stepSizes = [0.4/20, 0.2/20, 0.2/20, 0.1/20]
nUp, nDown = 1, 3
nReversals = 4
stepType = 'log'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=3, nCorrect=4, nIncorrect=4, length=20
)
self.intensities = [
0.8, 0.763994069, 0.729608671, 0.696770872, 0.665411017,
0.680910431, 0.696770872, 0.713000751, 0.729608671,
0.729608671, 0.729608671, 0.713000751, 0.713000751,
0.72125691, 0.729608671, 0.738057142, 0.746603441,
0.746603441, 0.746603441, 0.738057142
]
self.reversalPoints = [4, 10, 12, 18]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_StairHandlerDb(self):
nTrials = 20
startVal, minVal, maxVal = 0.8, 0, 1
stepSizes = [0.4, 0.2, 0.2, 0.1]
nUp, nDown = 1, 3
nReversals = 4
stepType = 'db'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=3, nCorrect=4, nIncorrect=4, length=20
)
self.intensities = [
0.8, 0.763994069, 0.729608671, 0.696770872, 0.665411017,
0.680910431, 0.696770872, 0.713000751, 0.729608671,
0.729608671, 0.729608671, 0.713000751, 0.713000751,
0.72125691, 0.729608671, 0.738057142, 0.746603441,
0.746603441, 0.746603441, 0.738057142
]
self.reversalPoints = [4, 10, 12, 18]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_StairHandlerScalarStepSize(self):
nTrials = 10
startVal, minVal, maxVal = 0.8, 0, 1
stepSizes = 0.1
nUp, nDown = 1, 1
nReversals = 6
stepType = 'lin'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=4, nCorrect=2, nIncorrect=1, length=10
)
self.intensities = [
0.8, 0.7, 0.6, 0.7, 0.6, 0.5, 0.6, 0.5, 0.4, 0.5
]
self.reversalPoints = [2, 3, 5, 6, 8, 9]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_StairHandlerLinearReveralsNone(self):
nTrials = 20
startVal, minVal, maxVal = 0.8, 0, 1
stepSizes = [0.1, 0.01, 0.001]
nUp, nDown = 1, 3
nReversals = None
stepType = 'lin'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=3, nCorrect=4, nIncorrect=4, length=20
)
self.intensities = [
0.8, 0.7, 0.6, 0.5, 0.4, 0.41, 0.42, 0.43, 0.44, 0.44, 0.44,
0.439, 0.439, 0.44, 0.441, 0.442, 0.443, 0.443, 0.443, 0.442
]
self.reversalPoints = [4, 10, 12, 18]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_StairHandlerLinearScalarStepSizeReveralsNone(self):
nTrials = 10
startVal, minVal, maxVal = 0.8, 0, 1
stepSizes = 0.1
nUp, nDown = 1, 1
nReversals = None
stepType = 'lin'
self.stairs = data.StairHandler(
startVal=startVal, nUp=nUp, nDown=nDown, minVal=minVal,
maxVal=maxVal, nReversals=nReversals, stepSizes=stepSizes,
nTrials=nTrials, stepType=stepType
)
self.responses = makeBasicResponseCycles(
cycles=4, nCorrect=2, nIncorrect=1, length=10
)
self.intensities = [
0.8, 0.7, 0.6, 0.7, 0.6, 0.5, 0.6, 0.5, 0.4, 0.5
]
self.reversalPoints = [2, 3, 5, 6, 8, 9]
self.reversalIntensities = list(
itemgetter(*self.reversalPoints)(self.intensities)
)
self.simulate()
self.checkSimulationResults()
def test_nReversals(self):
start_val = 1
step_sizes = list(range(5))
staircase = data.StairHandler(startVal=start_val, stepSizes=step_sizes,
nReversals=None)
assert staircase.nReversals == len(step_sizes)
staircase = data.StairHandler(startVal=start_val, stepSizes=step_sizes,
nReversals=len(step_sizes) - 1)
assert staircase.nReversals == len(step_sizes)
staircase = data.StairHandler(startVal=start_val, stepSizes=step_sizes,
nReversals=len(step_sizes) + 1)
assert staircase.nReversals == len(step_sizes) + 1
def test_applyInitialRule_False(self):
start_val = 10
step_sizes = 2
staircase = data.StairHandler(startVal=start_val, stepSizes=step_sizes,
nReversals=2, nUp=1, nDown=2,
applyInitialRule=False,
stepType='lin')
responses = [0, 1, 1, 0]
intensities = [10, 12, 12, 10]
for r in responses:
try:
staircase.__next__()
staircase.addResponse(r)
except StopIteration:
break
assert staircase.data == responses
assert staircase.intensities == intensities
def test_comparison_equals(self):
s1 = data.StairHandler(5)
s2 = data.StairHandler(5)
assert s1 == s2
def test_comparison_equals_after_iteration(self):
s1 = data.StairHandler(5)
s2 = data.StairHandler(5)
s1.__next__()
s2.__next__()
assert s1 == s2
def test_comparison_not_equal(self):
s1 = data.StairHandler(5)
s2 = data.StairHandler(6)
assert s1 != s2
def test_comparison_not_equal_after_iteration(self):
s1 = data.StairHandler(5)
s2 = data.StairHandler(6)
s1.__next__()
s2.__next__()
assert s1 != s2
def test_json_dump(self):
s = data.StairHandler(5)
dump = s.saveAsJson()
s.origin = ''
assert s == json_tricks.loads(dump)
def test_json_dump_with_data(self):
s = data.StairHandler(5)
s.addResponse(1)
s.addOtherData('foo', 'bar')
dump = s.saveAsJson()
s.origin = ''
assert s == json_tricks.loads(dump)
def test_json_dump_after_iteration(self):
s = data.StairHandler(5)
s.__next__()
dump = s.saveAsJson()
s.origin = ''
assert s == json_tricks.loads(dump)
def test_json_dump_with_data_after_iteration(self):
s = data.StairHandler(5)
s.addResponse(1)
s.addOtherData('foo', 'bar')
s.__next__()
dump = s.saveAsJson()
s.origin = ''
assert s == json_tricks.loads(dump)
def test_json_dump_to_file(self):
s = data.StairHandler(5)
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
s.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
def test_json_dump_and_reopen_file(self):
s = data.StairHandler(5)
s.addResponse(1)
s.addOtherData('foo', 'bar')
s.__next__()
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
s.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
s.origin = ''
s_loaded = fromFile(path)
assert s == s_loaded
class TestQuestHandler(_BaseTestStairHandler):
"""
Test QuestHandler, but with the ExperimentHandler attached as well.
"""
def test_QuestHandler(self):
nTrials = 10
startVal, minVal, maxVal = 50, 0, 100
range = maxVal - minVal
startValSd = 50
grain = 0.01
pThreshold = 0.82
beta, gamma, delta = 3.5, 0.5, 0.01
stopInterval = None
method = 'quantile'
self.stairs = data.QuestHandler(
startVal, startValSd, pThreshold=pThreshold, nTrials=nTrials,
stopInterval=stopInterval, method=method, beta=beta,
gamma=gamma, delta=delta, grain=grain, range=range,
minVal=minVal, maxVal=maxVal
)
self.stairs.nReversals = None
self.responses = makeBasicResponseCycles(
cycles=3, nCorrect=2, nIncorrect=2, length=10
)
self.intensities = [
50, 45.139710407074872, 37.291086503930742,
58.297413127139947, 80.182967131096547, 75.295251409003527,
71.57627192423783, 79.881680484036906, 90.712313302815517,
88.265808957695796
]
mean = 86.0772169427
mode = 80.11
quantile = 86.3849031085
self.simulate()
self.checkSimulationResults()
assert self.stairs.startVal == startVal
assert self.stairs.startValSd == startValSd
assert np.allclose(self.stairs.mean(), mean)
assert np.allclose(self.stairs.mode(), mode)
assert np.allclose(self.stairs.quantile(), quantile)
# Check if the internal grid has the expected dimensions.
assert len(self.stairs._quest.x) == (maxVal - minVal) / grain + 1
assert np.allclose(
self.stairs._quest.x[1] - self.stairs._quest.x[0],
grain
)
assert self.stairs._quest.x[0] == -range/2
assert self.stairs._quest.x[-1] == range/2
def test_attributes(self):
beta = 3.5
gamma = 0.01
delta = 0.02
grain = 0.01
range = 1
q = data.QuestHandler(startVal=0.5, startValSd=0.2, pThreshold=0.63,
nTrials=10,
beta=beta, gamma=gamma, delta=delta,
grain=grain, range=range)
assert q.beta == beta
assert q.gamma == gamma
assert q.delta == delta
assert q.grain == grain
assert q.range == range
def test_comparison_equals(self):
q1 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q2 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
assert q1 == q2
def test_comparison_equals_after_iteration(self):
q1 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q2 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q1.__next__()
q2.__next__()
assert q1 == q2
def test_comparison_not_equal(self):
q1 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q2 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=2)
assert q1 != q2
def test_comparison_not_equal_after_iteration(self):
q1 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q2 = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=2)
q1.__next__()
q2.__next__()
assert q1 != q2
def test_json_dump(self):
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
dump = q.saveAsJson()
q.origin = ''
assert q == json_tricks.loads(dump)
def test_json_dump_with_data(self):
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q.addResponse(1)
q.addOtherData('foo', 'bar')
dump = q.saveAsJson()
q.origin = ''
assert q == json_tricks.loads(dump)
def test_json_dump_after_iteration(self):
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q.__next__()
dump = q.saveAsJson()
q.origin = ''
assert q == json_tricks.loads(dump)
def test_json_dump_with_data_after_iteration(self):
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q.addResponse(1)
q.addOtherData('foo', 'bar')
q.__next__()
dump = q.saveAsJson()
q.origin = ''
assert q == json_tricks.loads(dump)
def test_json_dump_to_file(self):
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
def test_json_dump_and_reopen_file(self):
q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01,
nTrials=20, minVal=0, maxVal=1)
q.addResponse(1)
q.addOtherData('foo', 'bar')
q.__next__()
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
q.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
q.origin = ''
q_loaded = fromFile(path)
assert q == q_loaded
def test_epsilon(self):
# Values used by Harvey (1986), Table 3.
beta = 3.5
gamma = 0
delta = 0
epsilon = 0.0571
# QuestHandler needs this, but it doesn't influence our
# test. Values chosen arbitrarily.
startVal = 0.5
startValSd = 1
# Estimate the target proportion correct based on epsilon.
# (The values provided by Harvey (1986) are rounded to two
# decimal places and, therefore, too imprecise. So we
# have to we calculate it again.)
def weibull(x, beta, gamma, delta):
p = delta*gamma + (1-delta) * (1 - (1-gamma) * np.exp(-10 ** (beta*x)))
return p
p = weibull(x=epsilon, beta=beta, gamma=gamma, delta=delta)
q = data.QuestHandler(startVal=startVal, startValSd=startValSd,
pThreshold=p, beta=beta, gamma=gamma, delta=delta)
assert np.isclose(q.epsilon, epsilon, atol=1e-4)
class TestPsiHandler(_BaseTestStairHandler):
def test_comparison_equals(self):
p1 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
p2 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
assert p1 == p2
def test_comparison_equals_after_iteration(self):
p1 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
p2 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
p1.__next__()
p2.__next__()
assert p1 == p2
def test_comparison_not_equal(self):
p1 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
p2 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.001)
assert p1 != p2
def test_comparison_not_equal_after_iteration(self):
p1 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.01)
p2 = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=0.1, alphaPrecision=0.1,
betaPrecision=0.1, delta=0.001)
p1.__next__()
p2.__next__()
assert p1 != p2
def test_json_dump(self):
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
dump = p.saveAsJson()
p.origin = ''
assert p == json_tricks.loads(dump)
def test_json_dump_with_data(self):
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
p.addResponse(1)
p.addOtherData('foo', 'bar')
dump = p.saveAsJson()
p.origin = ''
assert p == json_tricks.loads(dump)
def test_json_dump_after_iteration(self):
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
p.__next__()
dump = p.saveAsJson()
p.origin = ''
assert p == json_tricks.loads(dump)
def test_json_dump_with_data_after_iteration(self):
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
p.addResponse(1)
p.addOtherData('foo', 'bar')
p.__next__()
dump = p.saveAsJson()
p.origin = ''
assert p == json_tricks.loads(dump)
def test_json_dump_to_file(self):
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
p.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
def test_json_dump_and_reopen_file(self):
p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10],
alphaRange=[0.1, 10], betaRange=[0.1, 3],
intensPrecision=1, alphaPrecision=1,
betaPrecision=0.5, delta=0.01)
p.addResponse(1)
p.addOtherData('foo', 'bar')
p.__next__()
_, path = mkstemp(dir=self.tmp_dir, suffix='.json')
p.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
p.origin = ''
p_loaded = fromFile(path)
assert p == p_loaded
class TestMultiStairHandler(_BaseTestMultiStairHandler):
"""
Test MultiStairHandler, but with the ExperimentHandler attached as well
"""
def test_multiStairQuestSequentialIdenticalConditions(self):
"""
Identical parameters passed to both QuestHandlers, and identical
simulated responses provided.
We use the exact same settings as in
TestQuestHandler.test_QuestHandler().
"""
# These are the parameters for the QuestHandlers.
nTrials = 10 # This is going to yield 10 trials per staircase.
startVal, minVal, maxVal = 50, 0, 100
range = maxVal - minVal
startValSd = 50
grain = 0.01
pThreshold = 0.82
beta, gamma, delta = 3.5, 0.5, 0.01
stopInterval = None
method = 'quantile'
# These parameters are shared between the two staircases. The only
# thing we will need to add is individual labels, which will
# happen below.
conditions = {
'startVal': startVal, 'startValSd': startValSd,
'minVal': minVal, 'maxVal': maxVal, 'range': range,
'pThreshold': pThreshold, 'gamma': gamma, 'delta': delta,
'grain': grain, 'method': method, 'nTrials': nTrials,
'stopInterval': stopInterval
}
self.conditions = [
dict(list({'label': 'staircase_0'}.items()) + list(conditions.items())),
dict(list({'label': 'staircase_1'}.items()) + list(conditions.items())),
]
self.stairs = data.MultiStairHandler(stairType='quest',
conditions=self.conditions)
# Responses for only one staircase. We will duplicate this below.
responses = makeBasicResponseCycles(
cycles=3, nCorrect=2, nIncorrect=2, length=10
)
self.responses = np.repeat(responses, 2)
# Same procedure as with the responses: This lists the responses
# for one of the staircases, and will be duplicated below.
intensities = [
50, 45.139710407074872, 37.291086503930742,
58.297413127139947, 80.182967131096547, 75.295251409003527,
71.57627192423783, 79.881680484036906, 90.712313302815517,
88.265808957695796
]
self.intensities = np.repeat(intensities, 2)
mean = 86.0772169427
mode = 80.11
quantile = 86.3849031085
self.simulate()
self.checkSimulationResults()
assert np.allclose(self.stairs.staircases[0].mean(), mean)
assert np.allclose(self.stairs.staircases[0].mode(), mode)
assert np.allclose(self.stairs.staircases[0].quantile(), quantile)
assert (self.stairs.staircases[0].intensities ==
self.stairs.staircases[1].intensities)
assert (self.stairs.staircases[0].data ==
self.stairs.staircases[1].data)
def makeBasicResponseCycles(cycles=10, nCorrect=4, nIncorrect=4,
length=None):
"""
Helper function to create a basic set of responses.
:Parameters:
cycles : int, optional
The number of response cycles to generate. One cycle consists of a
number of correct and incorrect responses.
Defaults to 10.
nCorrect, nIncorrect : int, optional
The number of correct and incorrect responses per cycle.
Defaults to 4.
length : int or None, optional
:Returns:
responses : list
A list of simulated responses with length
`cycles * (nCorrect + nIncorrect)`.
"""
responsesCorrectPerCycle = np.ones(nCorrect, dtype=int)
responsesIncorrectPerCycle = np.zeros(nIncorrect, dtype=int)
responses = np.tile(
np.r_[responsesCorrectPerCycle, responsesIncorrectPerCycle],
cycles
).tolist()
if length is not None:
return responses[:length]
else:
return responses
def test_QuestPlusHandler():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
expected_contrasts = [-18, -22, -25, -28, -30, -22, -13, -15, -16, -18,
-19, -20, -21, -22, -23, -19, -20, -20, -18, -18,
-19, -17, -17, -18, -18, -18, -19, -19, -19, -19,
-19, -19]
responses = ['Correct', 'Correct', 'Correct', 'Correct', 'Incorrect',
'Incorrect', 'Correct', 'Correct', 'Correct', 'Correct',
'Correct', 'Correct', 'Correct', 'Correct', 'Incorrect',
'Correct', 'Correct', 'Incorrect', 'Correct', 'Correct',
'Incorrect', 'Correct', 'Correct', 'Correct', 'Correct',
'Correct', 'Correct', 'Correct', 'Correct', 'Correct',
'Correct', 'Correct']
expected_mode_threshold = -20
scale = 'dB'
stim_selection_method = 'minEntropy'
param_estimation_method = 'mode'
func = 'weibull'
response_vals = ['Correct', 'Incorrect']
q = QuestPlusHandler(nTrials=len(expected_contrasts),
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
stimSelectionMethod=stim_selection_method,
stimScale=scale,
paramEstimationMethod=param_estimation_method)
for trial_index, next_contrast in enumerate(q):
assert next_contrast == expected_contrasts[trial_index]
q.addResponse(response=responses[trial_index])
assert np.allclose(q.paramEstimate['threshold'],
expected_mode_threshold)
def test_QuestPlusHandler_startIntensity():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
start_intensity = contrasts[10]
scale = 'dB'
stim_selection_method = 'minEntropy'
param_estimation_method = 'mode'
func = 'weibull'
q = QuestPlusHandler(nTrials=10,
startIntensity=start_intensity,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
stimSelectionMethod=stim_selection_method,
stimScale=scale,
paramEstimationMethod=param_estimation_method)
assert q.startIntensity == start_intensity
assert q._nextIntensity == start_intensity
def test_QuestPlusHandler_saveAsJson():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
scale = 'dB'
stim_selection_method = 'minEntropy'
param_estimation_method = 'mode'
func = 'weibull'
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
stimSelectionMethod=stim_selection_method,
stimScale=scale,
paramEstimationMethod=param_estimation_method)
q.origin = ''
# Add some random responses.
q.__next__()
q.addResponse(response='Correct')
q.__next__()
q.addResponse(response='Incorrect')
# Test dump to memory.
q.saveAsJson()
# Test dump to file.
temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
_, path = mkstemp(dir=temp_dir, suffix='.json')
q.saveAsJson(fileName=path, fileCollisionMethod='overwrite')
# Test loading from file.
q_loaded = fromFile(path)
assert q == q_loaded
# Check if it still works afterwards.
q.addResponse(response='Correct')
shutil.rmtree(temp_dir)
def test_QuestPlusHandler_paramEstimate_weibull():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
func = 'weibull'
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func)
assert 'threshold' in q.paramEstimate.keys()
assert 'slope' in q.paramEstimate.keys()
assert 'lowerAsymptote' in q.paramEstimate.keys()
assert 'lapseRate' in q.paramEstimate.keys()
def test_QuestPlusHandler_posterior_weibull():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
func = 'weibull'
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func)
assert 'threshold' in q.posterior.keys()
assert 'slope' in q.posterior.keys()
assert 'lowerAsymptote' in q.posterior.keys()
assert 'lapseRate' in q.posterior.keys()
def test_QuesPlusHandler_unknown_kwargs():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
func = 'weibull'
unknown_kwargs = dict(foo=1, bar='baz')
with pytest.warns(RuntimeWarning):
QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
**unknown_kwargs)
def test_QuesPlusHandler_unused_StairHandler_attribs():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
func = 'weibull'
stim_scale = 'linear'
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
stimScale=stim_scale)
assert q.currentDirection is None
assert q.stepSizeCurrent is None
assert q.stepType == q.stimScale
def test_QuesPlusHandler_stimSelectionOptions():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
response_vals = ['Correct', 'Incorrect']
func = 'weibull'
stim_scale = 'linear'
stim_selection_method = 'minNEntropy'
stim_selection_options = dict(N=10, maxConsecutiveReps=4, randomSeed=0)
stim_selection_options_qp = dict(n=10, max_consecutive_reps=4,
random_seed=0)
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
responseVals=response_vals,
psychometricFunc=func,
stimScale=stim_scale,
stimSelectionMethod=stim_selection_method,
stimSelectionOptions=stim_selection_options)
assert q.stimSelectionOptions == stim_selection_options
assert q._qp.stim_selection_options == stim_selection_options_qp
def test_QuesPlusHandler_prior():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
threshold_prior_vals = np.random.randint(low=1, high=10,
size=len(thresholds))
threshold_prior_vals = threshold_prior_vals / threshold_prior_vals.sum()
prior = dict(threshold=threshold_prior_vals)
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
prior=prior)
assert np.allclose(q._qp.prior.squeeze().values, threshold_prior_vals)
# Even though we only specified a prior for threshold, all parameters
# should be present (auto-populated) in q.prior.
assert all([k in q.prior for k in ('threshold', 'slope', 'lowerAsymptote',
'lapseRate')])
def test_QuesPlusHandler_invalid_prior_params():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
prior_vals = np.random.randint(low=1, high=10,
size=len(thresholds))
prior_vals = prior_vals / prior_vals.sum()
prior = dict(unknownParam=prior_vals)
with pytest.raises(ValueError):
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
prior=prior)
def test_QuesPlusHandler_unknown_stimSelectionOptions():
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
from psychopy.data.staircase import QuestPlusHandler
thresholds = np.arange(-40, 0 + 1)
slope, guess, lapse = 3.5, 0.5, 0.02
contrasts = thresholds.copy()
stim_selection_method = 'minNEntropy'
stim_selection_options = dict(unknownParam=1)
with pytest.raises(ValueError):
q = QuestPlusHandler(nTrials=20,
intensityVals=contrasts,
thresholdVals=thresholds,
slopeVals=slope,
lowerAsymptoteVals=guess,
lapseRateVals=lapse,
stimSelectionMethod=stim_selection_method,
stimSelectionOptions=stim_selection_options)
if __name__ == '__main__':
test_QuestPlusHandler()
test_QuestPlusHandler_startIntensity()
test_QuestPlusHandler_saveAsJson()
test_QuestPlusHandler_paramEstimate_weibull()
test_QuestPlusHandler_posterior_weibull()
test_QuesPlusHandler_unknown_kwargs()
test_QuesPlusHandler_unused_StairHandler_attribs()
test_QuesPlusHandler_stimSelectionOptions()
test_QuesPlusHandler_prior()
test_QuesPlusHandler_invalid_prior_params()
test_QuesPlusHandler_unknown_stimSelectionOptions()
| 43,911
|
Python
|
.py
| 994
| 32.204225
| 84
| 0.580257
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,471
|
test_utils.py
|
psychopy_psychopy/psychopy/tests/test_data/test_utils.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pytest
import numpy as np
from psychopy import exceptions
from psychopy.data import utils
from os.path import join
thisDir, _ = os.path.split(os.path.abspath(__file__))
fixturesPath = join(thisDir, '..', 'data')
#
class Test_utilsClass:
def test_importConditions(self):
standard_files = []
standard_files.append(join(fixturesPath, 'trialTypes.xlsx'))
#standard_files.append(join(fixturesPath, 'trialTypes.xls')) # xls is depreciated
standard_files.append(join(fixturesPath, 'trialTypes.csv'))
standard_files.append(join(fixturesPath, 'trialTypes_eu.csv'))
standard_files.append(join(fixturesPath, 'trialTypes.tsv'))
# some extra formats (expected fails)
fileName_pkl = join(fixturesPath, 'trialTypes.pkl')
fileName_docx = join(fixturesPath, 'trialTypes.docx')
expected_cond = utils.OrderedDict(
[('text', 'red'),
('congruent', 1),
('corrAns', 1),
('letterColor', 'red'),
('n', 2),
('float', 1.1)])
# check import worked for standard file formats
for filename in standard_files:
conds = utils.importConditions(filename)
assert conds[0] == expected_cond, (
"Did not correctly import for '{}': "
"expected({}) != imported({})"
.format(filename, expected_cond, conds[0]))
# test for None in filename with _assertValidVarNames
assert utils.importConditions(fileName=None) == []
assert utils.importConditions(fileName=None, returnFieldNames=True) == ([], [])
# Test value error for non-existent file
with pytest.raises(exceptions.ConditionsImportError) as errMsg:
utils.importConditions(fileName='raiseErrorfileName')
assert 'Conditions file not found:' in str(errMsg.value)
assert 'raiseErrorfileName' in str(errMsg.value)
conds = utils.importConditions(fileName_pkl)
assert conds[0] == expected_cond
# trialTypes.pkl saved in list of list format (see trialTypes.docx)
# test assertion for invalid file type
with pytest.raises(exceptions.ConditionsImportError) as errMsg:
utils.importConditions(fileName_docx)
assert ('Your conditions file should be an ''xlsx, csv, dlm, tsv or pkl file') == str(errMsg.value)
# test random selection of conditions
all_conditions = utils.importConditions(standard_files[0])
assert len(all_conditions) == 6
num_selected_conditions = 1001
selected_conditions = utils.importConditions(
standard_files[0],
selection=(np.concatenate(
([0.9], np.random.random(num_selected_conditions - 1)*len(all_conditions)))))
assert selected_conditions[0] == expected_cond
assert len(selected_conditions) == num_selected_conditions
def test_isValidVariableName(self):
cases = [
{'val': 'Name', 'valid': True, 'msg': ''},
{'val': 'a_b_c', 'valid': True, 'msg': ''},
{'val': '', 'valid': False, 'msg': "Variables cannot be missing, None, or ''"},
{'val': '0Name', 'valid': False, 'msg': 'Variables cannot begin with numeric character'},
{'val': 'first second', 'valid': False, 'msg': 'Variables cannot contain punctuation or spaces'},
{'val': None, 'valid': False, 'msg': "Variables cannot be missing, None, or ''"},
{'val': 26, 'valid': False, 'msg': 'Variables must be string-like'},
]
for case in cases:
valid, msg, translated = utils.isValidVariableName(case['val'])
assert valid == case['valid']
assert msg == case['msg']
def test_GetExcelCellName(self):
assert utils._getExcelCellName(0,0) == 'A1'
assert utils._getExcelCellName(2, 1) == 'C2'
def test_importTrialTypes(self):
filename = join(fixturesPath, 'dataTest.xlsx')
expected_cond = utils.OrderedDict(
[('text', 'red'),
('congruent', 1),
('corrAns', 1),
('letterColor', 'red'),
('n', 2)])
conds = utils.importTrialTypes(filename)
assert conds[0] == expected_cond
def test_sliceFromString(self):
assert utils.sliceFromString('0:10') == slice(0,10,None)
assert utils.sliceFromString('0::3') == slice(0, None, 3)
assert utils.sliceFromString('-8:') == slice(-8, None, None)
def test_indicesFromString(self):
assert utils.indicesFromString("6") == [6]
assert utils.indicesFromString("6::2") == slice(6, None, 2)
assert utils.indicesFromString("1,4,8") == [1, 4, 8]
def test_bootStraps(self):
import numpy as np
data = ['a','b','c']
assert isinstance(utils.bootStraps(data, n=1), np.ndarray)
assert utils.bootStraps(data,n = 1).shape == (1, 3, 1)
assert utils.bootStraps(data, n = 1).size == 3
assert utils.bootStraps(data, n=1).ndim == len(utils.bootStraps(data,n = 1).shape)
def test_functionFromStaircase(self):
import numpy as np
intensities = np.arange(0,1,.1)
responses = [1 if x >= .5 else 0 for x in intensities]
bin10, binUniq = 10, 'unique'
# try unequal dimension concatenation exception
with pytest.raises(Exception):
utils.functionFromStaircase(intensities, responses[:9], bin10)
assert isinstance(utils.functionFromStaircase(intensities, responses, bin10), tuple)
assert utils.functionFromStaircase(intensities, responses, binUniq).__len__() == 3
# test outputs from function
assert len(utils.functionFromStaircase(intensities, responses, bin10)[0]) == len(intensities)
assert len(utils.functionFromStaircase(intensities, responses, bin10)[1]) == len(responses)
assert len(utils.functionFromStaircase(intensities, responses, bin10)[2]) == len([1]*bin10)
assert len(utils.functionFromStaircase(intensities, responses, binUniq)[0]) == len(intensities)
assert len(utils.functionFromStaircase(intensities, responses, binUniq)[1]) == len(responses)
assert len(utils.functionFromStaircase(intensities, responses, binUniq)[2]) == len([1]*bin10)
def test_getDateStr(self):
import time
millisecs_dateStr = utils.getDateStr()
microsecs_dateStr = utils.getDateStr(fractionalSecondDigits=6)
assert len(millisecs_dateStr) == len(microsecs_dateStr[:-3]) # ms=3dp not 6
shortFormat = "%Y_%b_%d_%H%M"
customDateStr = utils.getDateStr(shortFormat)
# getDateStr() uses datetime.now().strftime(format) but should match
# format for time.strftime (the latter doesn't support milli/microsecs)
assert customDateStr == time.strftime(shortFormat, time.localtime())
def test_import_blankColumns(self):
fileName_blanks = join(fixturesPath, 'trialsBlankCols.xlsx')
conds = utils.importConditions(fileName_blanks)
assert len(conds) == 6
assert len(list(conds[0].keys())) == 6
def test_listFromString():
assert ['yes', 'no'] == utils.listFromString("yes, no")
assert ['yes', 'no'] == utils.listFromString("[yes, no]")
assert ['yes', 'no'] == utils.listFromString("(yes, no)")
assert ['yes', 'no'] == utils.listFromString("'yes', 'no'")
assert ['yes', 'no'] == utils.listFromString("['yes', 'no']")
assert ['yes', 'no'] == utils.listFromString("('yes', 'no')")
# this should be returned without ast.literal_eval being used
assert ['yes', 'no'] == utils.listFromString(('yes', 'no'))
# this would create a syntax error in ast.literal_eval
assert ["Don't", "Do"] == utils.listFromString("Don't, Do")
if __name__ == '__main__':
pytest.main()
| 7,913
|
Python
|
.py
| 148
| 44.614865
| 109
| 0.63546
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,472
|
test_MultiStairHandler.py
|
psychopy_psychopy/psychopy/tests/test_data/test_MultiStairHandler.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import shutil
import os
import numpy as np
from tempfile import mkdtemp
from psychopy import data
thisPath = os.path.split(__file__)[0]
fixturesPath = os.path.join(thisPath, '..', 'data')
class TestMultiStairHandler():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_simple(self):
conditions = data.importConditions(
os.path.join(fixturesPath, 'multiStairConds.xlsx'))
stairs = data.MultiStairHandler(
stairType='simple', conditions=conditions, method='random',
nTrials=20, name='simpleStairs', autoLog=False)
exp = data.ExperimentHandler(
name='testExp', savePickle=True, saveWideText=True,
dataFileName=os.path.join(self.temp_dir, 'multiStairExperiment'),
autoLog=False)
rng = np.random.RandomState(seed=self.random_seed)
exp.addLoop(stairs)
for intensity, condition in stairs:
# make data that will cause different stairs to finish different
# times
if rng.rand() > condition['startVal']:
corr = 1
else:
corr = 0
stairs.addData(corr)
stairs.saveAsExcel(os.path.join(self.temp_dir, 'multiStairOut'))
# contains more info
stairs.saveAsPickle(os.path.join(self.temp_dir, 'multiStairOut'))
exp.close()
def test_quest(self):
conditions = data.importConditions(
os.path.join(fixturesPath, 'multiStairConds.xlsx'))
stairs = data.MultiStairHandler(
stairType='quest', conditions=conditions, method='random',
nTrials=20, name='QuestStairs', autoLog=False)
exp = data.ExperimentHandler(
name='testExp', savePickle=True, saveWideText=True,
dataFileName=os.path.join(self.temp_dir, 'multiQuestExperiment'),
autoLog=False)
rng = np.random.RandomState(seed=self.random_seed)
exp.addLoop(stairs)
for intensity, condition in stairs:
# make data that will cause different stairs to finish different
# times
if rng.rand() > condition['startVal']:
corr = 1
else:
corr = 0
stairs.addData(corr)
stairs.saveAsExcel(os.path.join(self.temp_dir, 'multiQuestOut'))
# contains more info
stairs.saveAsPickle(os.path.join(self.temp_dir, 'multiQuestOut'))
exp.close()
def test_QuestPlus(self):
import sys
if not (sys.version_info.major == 3 and sys.version_info.minor >= 6):
pytest.skip('QUEST+ only works on Python 3.6+')
conditions = data.importConditions(os.path.join(fixturesPath,
'multiStairQuestPlus.xlsx'))
stairs = data.MultiStairHandler(stairType='questplus',
conditions=conditions,
method='random',
nTrials=20,
name='QuestPlusStairs',
autoLog=False)
exp = data.ExperimentHandler(name='testExp',
savePickle=True,
saveWideText=True,
dataFileName=os.path.join(self.temp_dir,
'multiQuestPlusExperiment'),
autoLog=False)
exp.addLoop(stairs)
for intensity, condition in stairs:
response = np.random.choice(['Correct', 'Incorrect'])
stairs.addResponse(response)
stairs.saveAsExcel(os.path.join(self.temp_dir, 'multiQuestPlusOut'))
# contains more info
stairs.saveAsPickle(os.path.join(self.temp_dir, 'multiQuestPlusOut'))
exp.close()
def test_random():
conditions = data.importConditions(os.path.join(fixturesPath,
'multiStairConds.xlsx'))
seed = 11
first_pass = ['low', 'high', 'medium']
kwargs = dict(method='random', randomSeed=seed, stairType='simple',
conditions=conditions, nTrials=5)
multistairs = data.MultiStairHandler(**kwargs)
for staircase_idx, staircase in enumerate(multistairs.thisPassRemaining):
assert staircase.condition['label'] == first_pass[staircase_idx]
def test_different_seeds():
conditions = data.importConditions(os.path.join(fixturesPath,
'multiStairConds.xlsx'))
seeds = [7, 11]
first_pass = [['high', 'medium', 'low'],
['low', 'high', 'medium']]
kwargs = dict(method='random', stairType='simple',
conditions=conditions, nTrials=5)
for seed_idx, seed in enumerate(seeds):
multistairs = data.MultiStairHandler(randomSeed=seed, **kwargs)
for staircase_idx, staircase in enumerate(multistairs.thisPassRemaining):
assert staircase.condition['label'] == first_pass[seed_idx][staircase_idx]
def test_fullRandom():
conditions = data.importConditions(os.path.join(fixturesPath,
'multiStairConds.xlsx'))
seed = 11
first_pass = ['medium', 'low', 'medium']
kwargs = dict(method='fullRandom', randomSeed=seed, stairType='simple',
conditions=conditions, nTrials=5)
multistairs = data.MultiStairHandler(**kwargs)
for staircase_idx, staircase in enumerate(multistairs.thisPassRemaining):
assert staircase.condition['label'] == first_pass[staircase_idx]
def test_invalid_method():
conditions = data.importConditions(os.path.join(fixturesPath,
'multiStairConds.xlsx'))
kwargs = dict(method='foobar', stairType='simple',
conditions=conditions, nTrials=5)
with pytest.raises(ValueError):
data.MultiStairHandler(**kwargs)
if __name__ == '__main__':
pytest.main()
| 6,315
|
Python
|
.py
| 131
| 35.091603
| 91
| 0.592574
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,473
|
test_TrialHandler.py
|
psychopy_psychopy/psychopy/tests/test_data/test_TrialHandler.py
|
"""Tests for psychopy.data.DataHandler"""
import os, glob
from os.path import join as pjoin
import shutil
from tempfile import mkdtemp, mkstemp
import numpy as np
import io
import pytest
from psychopy import data
from psychopy.tools.filetools import fromFile
from psychopy.tests import utils
thisPath = os.path.split(__file__)[0]
fixturesPath = os.path.join(thisPath, '..', 'data')
class TestTrialHandler():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.rootName = 'test_data_file'
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_underscores_in_datatype_names(self):
trials = data.TrialHandler([], 1, autoLog=False)
trials.data.addDataType('with_underscore')
for trial in trials: # need to run trials or file won't be saved
trials.addData('with_underscore', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsExcel(base_data_filename)
trials.saveAsText(base_data_filename, delim=',')
# Make sure the file is there
data_filename = base_data_filename + '.csv'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
with io.open(data_filename, 'r', encoding='utf-8-sig') as f:
header = f.readline()
expected_header = u'n,with_underscore_mean,with_underscore_raw,with_underscore_std,order\n'
if expected_header != header:
print(base_data_filename)
print(repr(expected_header),type(expected_header),len(expected_header))
print(repr(header), type(header), len(header))
assert expected_header == str(header)
def test_psydat_filename_collision_renaming(self):
for count in range(1,20):
trials = data.TrialHandler([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename)
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there. (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*.psydat")))
assert matches==count, "Found %d matching files, should be %d" % (matches, count)
def test_psydat_filename_collision_overwriting(self):
for count in [1, 10, 20]:
trials = data.TrialHandler([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName+'overwrite')
trials.saveAsPickle(base_data_filename, fileCollisionMethod='overwrite')
# Make sure the file just saved is there
data_filename = base_data_filename + '.psydat'
assert os.path.exists(data_filename), "File not found: %s" %os.path.abspath(data_filename)
# Make sure the correct number of files for the loop are there. (No overwriting by default).
matches = len(glob.glob(os.path.join(self.temp_dir, self.rootName + "*overwrite.psydat")))
assert matches==1, "Found %d matching files, should be %d" % (matches, count)
def test_multiKeyResponses(self):
pytest.skip() # temporarily; this test passed locally but not under travis, maybe PsychoPy version of the .psyexp??
dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat'))
#test csv output
dat.saveAsText(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), appendFile=False)
utils.compareTextFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), pjoin(fixturesPath,'corrMultiKeyTrials.csv'))
#test xlsx output
dat.saveAsExcel(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), appendFile=False)
utils.compareXlsxFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), pjoin(fixturesPath,'corrMultiKeyTrials.xlsx'))
def test_psydat_filename_collision_failure(self):
with pytest.raises(IOError):
for count in range(1,3):
trials = data.TrialHandler([], 1, autoLog=False)
trials.data.addDataType('trialType')
for trial in trials:#need to run trials or file won't be saved
trials.addData('trialType', 0)
base_data_filename = pjoin(self.temp_dir, self.rootName)
trials.saveAsPickle(base_data_filename, fileCollisionMethod='fail')
def test_psydat_filename_collision_output(self):
#create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
#create trials
trials= data.TrialHandler(trialList=conditions, seed=self.random_seed,
nReps=3, method='fullRandom', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
trials.addData('resp', resp)
trials.addData('rand',randResp)
# test summarised data outputs
trials.saveAsText(pjoin(self.temp_dir, 'testFullRandom.tsv'), stimOut=['trialType'],appendFile=False)#this omits values
utils.compareTextFiles(pjoin(self.temp_dir, 'testFullRandom.tsv'), pjoin(fixturesPath,'corrFullRandom.tsv'))
# test wide data outputs
trials.saveAsWideText(pjoin(self.temp_dir, 'testFullRandom.csv'), delim=',', appendFile=False)#this omits values
utils.compareTextFiles(pjoin(self.temp_dir, 'testFullRandom.csv'), pjoin(fixturesPath,'corrFullRandom.csv'))
def test_random_data_output(self):
# create conditions
conditions=[]
for trialType in range(5):
conditions.append({'trialType':trialType})
trials = data.TrialHandler(trialList=conditions, seed=self.random_seed,
nReps=3, method='random', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
trials.addData('resp', resp)
trials.addData('rand', randResp)
# test summarised data outputs
trials.saveAsText(pjoin(self.temp_dir, 'testRandom.tsv'), stimOut=['trialType'],appendFile=False)#this omits values
utils.compareTextFiles(pjoin(self.temp_dir, 'testRandom.tsv'), pjoin(fixturesPath,'corrRandom.tsv'))
# test wide data outputs
trials.saveAsWideText(pjoin(self.temp_dir, 'testRandom.csv'), delim=',', appendFile=False)#this omits values
utils.compareTextFiles(pjoin(self.temp_dir, 'testRandom.csv'), pjoin(fixturesPath,'corrRandom.csv'))
def test_comparison_equals(self):
t1 = data.TrialHandler([dict(foo=1)], 2)
t2 = data.TrialHandler([dict(foo=1)], 2)
assert t1 == t2
def test_comparison_equals_after_iteration(self):
t1 = data.TrialHandler([dict(foo=1)], 2)
t2 = data.TrialHandler([dict(foo=1)], 2)
t1.__next__()
t2.__next__()
assert t1 == t2
def test_comparison_not_equal(self):
t1 = data.TrialHandler([dict(foo=1)], 2)
t2 = data.TrialHandler([dict(foo=1)], 3)
assert t1 != t2
def test_comparison_not_equal_after_iteration(self):
t1 = data.TrialHandler([dict(foo=1)], 2)
t2 = data.TrialHandler([dict(foo=1)], 3)
t1.__next__()
t2.__next__()
assert t1 != t2
class TestTrialHandlerOutput():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def setup_method(self, method):
# create conditions
conditions = []
for trialType in range(5):
conditions.append({'trialType':trialType})
self.trials = data.TrialHandler(trialList=conditions,
seed=self.random_seed,
nReps=3, method='random', autoLog=False)
# simulate trials
rng = np.random.RandomState(seed=self.random_seed)
for thisTrial in self.trials:
resp = 'resp' + str(thisTrial['trialType'])
randResp = rng.rand()
self.trials.addData('resp', resp)
self.trials.addData('rand', randResp)
def test_output_no_filename_no_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_comma_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ','
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.csv'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_tab_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = '\t'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_no_filename_semicolon_delim(self):
_, path = mkstemp(dir=self.temp_dir)
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.txt'
assert os.path.isfile(path + expected_suffix)
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_delim = ','
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_arbitrary_suffix_no_delim(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.xyz')
delim = None
self.trials.saveAsWideText(path, delim=delim)
expected_suffix = '.tsv'
assert os.path.isfile(path + expected_suffix)
expected_delim = '\t'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path + expected_suffix, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
def test_output_csv_and_semicolon(self):
_, path = mkstemp(dir=self.temp_dir, suffix='.csv')
delim = ';'
self.trials.saveAsWideText(path, delim=delim)
assert os.path.isfile(path)
expected_delim = ';'
expected_header = ['TrialNumber']
expected_header.extend(list(self.trials.trialList[0].keys()))
expected_header.extend(self.trials.data.dataTypes)
expected_header = expected_delim.join(expected_header) + '\n'
with io.open(path, 'r', encoding='utf-8-sig') as f:
header = f.readline()
assert header == expected_header
if __name__ == '__main__':
pytest.main()
| 13,665
|
Python
|
.py
| 261
| 42.440613
| 127
| 0.64186
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,474
|
test_ExperimentHandler.py
|
psychopy_psychopy/psychopy/tests/test_data/test_ExperimentHandler.py
|
# -*- coding: utf-8 -*-
from psychopy import data, logging
import numpy as np
import os, glob, shutil
import io
from tempfile import mkdtemp
from psychopy.tools.filetools import openOutputFile
logging.console.setLevel(logging.DEBUG)
class TestExperimentHandler():
def setup_class(self):
self.tmpDir = mkdtemp(prefix='psychopy-tests-testExp')
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.tmpDir)
# for a while (until 1.74.00) files were being left in the tests folder by mistake
for f in glob.glob('testExp*.psyexp'):
os.remove(f)
for f in glob.glob('testExp*.csv'):
os.remove(f)
def test_default(self):
exp = data.ExperimentHandler(
name='testExp',
version='0.1',
extraInfo={'participant': 'jwp', 'ori': 45},
runtimeInfo=None,
originPath=None,
savePickle=True,
saveWideText=True,
dataFileName=self.tmpDir + 'default'
)
# First loop: Training.
conds = data.createFactorialTrialList(
{'faceExpression': ['happy', 'sad'], 'presTime': [0.2, 0.3]}
)
training = data.TrialHandler(
trialList=conds, nReps=3, name='train',
method='random',
seed=self.random_seed)
exp.addLoop(training)
rng = np.random.RandomState(seed=self.random_seed)
for trial in training:
training.addData('training.rt', rng.rand() * 0.5 + 0.5)
if rng.rand() > 0.5:
training.addData('training.key', 'left')
else:
training.addData('training.key', 'right')
exp.nextEntry()
# Then run 3 repeats of a staircase.
outerLoop = data.TrialHandler(
trialList=[], nReps=3,name='stairBlock', method='random'
)
exp.addLoop(outerLoop)
for thisRep in outerLoop: # The outer loop doesn't save any data.
staircase = data.StairHandler(
startVal=10, name='staircase', nTrials=5
)
exp.addLoop(staircase)
for thisTrial in staircase:
id = rng.rand()
if rng.rand() > 0.5:
staircase.addData(1)
else:
staircase.addData(0)
exp.addData('id', id)
exp.nextEntry()
def test_addData_with_mutable_values(self):
# add mutable objects to data, check that the value *at that time* is saved
exp = data.ExperimentHandler(
name='testExp',
savePickle=False,
saveWideText=True,
dataFileName=self.tmpDir + 'mutables'
)
mutant = [1]
exp.addData('mutable', mutant)
exp.nextEntry()
mutant[0] = 9999
exp.addData('mutable', mutant)
exp.nextEntry()
exp.saveAsWideText(exp.dataFileName+'.csv', delim=',')
# get data file contents:
with io.open(exp.dataFileName + '.csv', 'r', encoding='utf-8-sig') as f:
contents = f.read()
assert contents == "thisRow.t,notes,mutable,\n,,[1],\n,,[9999],\n"
def test_unicode_conditions(self):
fileName = self.tmpDir + 'unicode_conds'
exp = data.ExperimentHandler(
savePickle=False,
saveWideText=False,
dataFileName=fileName
)
conds = [
{'id': '01', 'name': u'umlauts-öäü'},
{'id': '02', 'name': u'accents-àáâă'}
]
trials = data.TrialHandler(
trialList=conds, nReps=1, method='sequential'
)
exp.addLoop(trials)
for trial in trials:
pass
trials.saveAsWideText(fileName)
exp.saveAsWideText(fileName)
exp.saveAsPickle(fileName)
def test_comparison_equals(self):
e1 = data.ExperimentHandler()
e2 = data.ExperimentHandler()
assert e1 == e2
def test_comparison_not_equal(self):
e1 = data.ExperimentHandler()
e2 = data.ExperimentHandler(name='foo')
assert e1 != e2
def test_comparison_equals_with_same_TrialHandler_attached(self):
e1 = data.ExperimentHandler()
e2 = data.ExperimentHandler()
t = data.TrialHandler([dict(foo=1)], 2)
e1.addLoop(t)
e2.addLoop(t)
assert e1 == e2
def test_save_unicode(self):
exp = data.ExperimentHandler()
# Try to save data to csv
for encoding in ['utf-8', 'utf-16']:
for asDecimal in range(143859):
# Add each unicode character to the data file
try:
chr(asDecimal).encode(encoding)
except UnicodeEncodeError:
# Skip if not a valid unicode
continue
exp.addData("char", chr(asDecimal))
exp.nextEntry()
try:
exp.saveAsWideText(self.tmpDir + '\\unicode_chars.csv', encoding=encoding)
except UnicodeEncodeError as err:
# If failed, remove and store character which failed
raise UnicodeEncodeError(*err.args[:4], "character failing to save to csv")
if __name__ == '__main__':
import pytest
pytest.main()
| 5,370
|
Python
|
.py
| 140
| 27.514286
| 91
| 0.56953
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,475
|
test_xlsx.py
|
psychopy_psychopy/psychopy/tests/test_data/test_xlsx.py
|
"""Tests for psychopy.data.DataHandler"""
import os, shutil
import numpy as np
from tempfile import mkdtemp
import pytest
from psychopy import data
from psychopy.tests import utils
thisDir,filename = os.path.split(os.path.abspath(__file__))
fixturesPath = os.path.join(thisDir,'..','data')
class TestXLSX():
def setup_class(self):
self.temp_dir = mkdtemp(prefix='psychopy-tests-testdata')
self.name = os.path.join(self.temp_dir,'testXlsx')
self.fullName = self.name+'.xlsx'
self.random_seed = 100
def teardown_class(self):
shutil.rmtree(self.temp_dir)
def test_TrialHandlerAndXLSX(self):
"""Currently tests the contents of xslx file against known good example
"""
conds = data.importConditions(os.path.join(fixturesPath,
'trialTypes.xlsx'))
trials = data.TrialHandler(trialList=conds,
seed=self.random_seed,
nReps=2, autoLog=False)
responses = [1,1,None,3,2,3, 1,3,2,2,1,1]
rts = [0.1,0.1,None,0.3,0.2,0.3, 0.1,0.3,0.2,0.2,0.1,0.1]
for trialN, trial in enumerate(trials):
if responses[trialN] is None:
continue
trials.addData('resp', responses[trialN])
trials.addData('rt',rts[trialN])
trials.saveAsExcel(self.name)# '.xlsx' should be added automatically
trials.saveAsText(self.name, delim=',')# '.xlsx' added automatically
trials.saveAsWideText(os.path.join(self.temp_dir,'actualXlsx'))
# Make sure the file is there
assert os.path.isfile(self.fullName)
#compare with known good file
utils.compareXlsxFiles(self.fullName,
os.path.join(fixturesPath,'corrXlsx.xlsx'))
def test_TrialTypeImport():
def checkEachtrial(fromCSV, fromXLSX):
for trialN, trialCSV in enumerate(fromCSV):
trialXLSX = fromXLSX[trialN]
assert list(trialXLSX.keys()) == list(trialCSV.keys())
for header in trialCSV:
if trialXLSX[header] != trialCSV[header]:
print(header, trialCSV[header], trialXLSX[header])
assert trialXLSX[header] == trialCSV[header]
fromCSV = data.importConditions(os.path.join(fixturesPath,
'trialTypes.csv'))
# use pandas/xlrd once
fromXLSX = data.importConditions(os.path.join(fixturesPath,
'trialTypes.xlsx'))
checkEachtrial(fromCSV, fromXLSX)
# then pretend it doesn't exist to force use of openpyxl
haveXlrd = data.haveXlrd
data.haveXlrd = False
fromXLSX = data.importConditions(os.path.join(fixturesPath,
'trialTypes.xlsx'))
checkEachtrial(fromCSV, fromXLSX)
data.haveXlrd = haveXlrd # return to what it was
def test_ImportCondsUnicode():
if not data.haveXlrd:
# open pyxl thinks the right-to-left file has blanks in header
pytest.skip("We know this fails with openpyxl")
fromXLSX = data.importConditions(os.path.join(fixturesPath,
'right_to_left_unidcode.xlsx'))
assert u'\u05d2\u05d9\u05dc' in fromXLSX[0]['question']
if __name__ == '__main__':
t = TestXLSX()
t.setup_class()
t.test_TrialHandlerAndXLSX()
t.teardown_class()
| 3,481
|
Python
|
.py
| 74
| 35.824324
| 79
| 0.61375
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,476
|
test_Session.py
|
psychopy_psychopy/psychopy/tests/test_session/test_Session.py
|
import json
from psychopy import session, visual, clock
from psychopy.hardware import deviceManager
from psychopy.tests import utils, skip_under_vm
from pathlib import Path
import shutil
import threading
import time
@skip_under_vm
class TestSession:
def setup_class(cls):
root = Path(utils.TESTS_DATA_PATH) / "test_session" / "root"
win = visual.Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False)
cls.sess = session.Session(
root,
loggingLevel="info",
win=win,
experiments={
'exp1': "exp1/exp1.psyexp",
'exp2': "exp2/exp2.psyexp",
'testCtrls': "testCtrls/testCtrls.psyexp",
'error': "error/error.psyexp",
'annotation': "annotation/annotation.psyexp",
'trialNav': "testTrialNav/trialNav.psyexp"
}
)
# setup devices
cls.sess.setupDevicesFromExperiment("exp1")
def test_outside_root(self):
# Add an experiment from outside of the Session root
expFile = Path(utils.TESTS_DATA_PATH) / "test_session" / "outside_root" / "externalExp.psyexp"
self.sess.addExperiment(expFile, key="externalExp")
# Check that file is copied
newExpFile = self.sess.root / "outside_root" / "externalExp.psyexp"
assert newExpFile.is_file()
# Check that newly added experiment still runs
self.sess.runExperiment("externalExp")
# Remove external experiment
shutil.rmtree(str(newExpFile.parent))
del self.sess.experiments['externalExp']
def test_run_exp(self):
self.sess.runExperiment("exp2")
self.sess.runExperiment("exp1")
def test_trial_navigation(self):
self.sess.runExperiment("trialNav")
def test_ctrls(self):
"""
Check that experiments check Session often enough for pause/resume commands sent asynchronously will still work.
"""
def send_dummy_commands(sess):
"""
Call certain functions of the Session class with time inbetween
"""
# Set experiment going
sess.runExperiment("testCtrls", blocking=False)
# Wait 0.1s then pause
time.sleep(.2)
sess.pauseExperiment()
# Wait 0.1s then resume
time.sleep(.2)
sess.resumeExperiment()
# Wait then close
time.sleep(.2)
sess.stop()
# Send dummy commands from a new thread
thread = threading.Thread(
target=send_dummy_commands,
args=(self.sess,)
)
thread.start()
# Start session
self.sess.start()
def test_sync_clocks(self):
"""
Test that experiment clock is applied to ioHub
"""
from psychopy import iohub
def _sameTimes():
times = [
# ioHub process time
deviceManager.ioServer.getTime(),
# ioHub time in current process
iohub.Computer.global_clock.getTime(),
# experiment time
self.sess.sessionClock.getTime(),
]
# confirm that all values are within 0.001 of eachother
avg = sum(times) / len(times)
deltas = [abs(t - avg) for t in times]
same = [d < 0.001 for d in deltas]
return all(same)
# knock ioHub timer out of sync
time.sleep(1)
# run experiment
self.sess.runExperiment("exp1")
# confirm that ioHub timer was brought back into sync
assert _sameTimes(), (
deviceManager.ioServer.getTime(),
iohub.Computer.global_clock.getTime(),
self.sess.sessionClock.getTime(),
)
def test_clock_format(self):
cases = [
# usual from-zero time should return a float
{'val': "float", 'ans': float},
# iso should return iso formatted string
{'val': "iso", 'ans': str},
# custom str format should return as custom formatted string
{'val': "%m/%d/%Y, %H:%M:%S", 'ans': "%m/%d/%Y, %H:%M:%S"}
]
for case in cases:
sess = session.Session(
root=Path(utils.TESTS_DATA_PATH) / "test_session" / "root",
clock=case['val'],
win=self.sess.win,
experiments={
'clockFormat': "testClockFormat/testClockFormat.psyexp"
}
)
sess.runExperiment('clockFormat', expInfo={'targetFormat': case['ans']})
# get first value of thisRow from ExperimentHandler
tRowVal = sess.runs[-1].entries[0]['thisRow.t']
# get first value of thisRow from ExperimentHandler's JSON output
tRowJSON = json.loads(sess.runs[-1].getJSON())['trials'][0]['thisRow.t']
# check that JSON output and direct value are the same
assert tRowVal == tRowJSON
# make into a Timestamp object
tRowObj = clock.Timestamp(tRowVal, format=case['ans'])
# make sure stringified value is same as stringified timestamp with requested format
assert str(tRowVal) == str(tRowObj)
# get last timestamp in log file
sess.logFile.logger.flush()
fmtStr = sess.logFile.logger.format
msg = fmtStr.format(
**sess.logFile.logger.flushed[-1].__dict__
)
tLastLog = msg.split("\t")[0].strip()
# make sure last logged time fits format
try:
tLastLog = float(tLastLog)
except ValueError:
pass
if case['ans'] is float:
# if wanting float, value should convert to float
float(tLastLog)
else:
# if anything else, try to parse
fmt = case['ans']
if fmt is str:
fmt = "%Y-%m-%d_%H:%M:%S.%f"
# should parse safely with format
time.strptime(tLastLog, fmt)
def test_disable_useversion(self):
"""
Experiment compiled via a Session shouldn't respect the useVersion setting.
"""
# add an experiment which has useVersion set to 2023.1.3
self.sess.addExperiment("invUseVersion/invUseVersion.psyexp", "invUseVersion")
# make sure compiled Python file has correct version
from psychopy import __version__
assert self.sess.experiments['invUseVersion'].psychopyVersion == __version__
def test_update_expInfo(self):
"""
Test that expInfo can be update during an experiment running.
"""
# add test experiment to Session
self.sess.addExperiment("testEditExpInfo/testEditExpInfo.psyexp", "testEditExpInfo")
# make expInfo dict
expInfo = self.sess.getExpInfoFromExperiment("testEditExpInfo")
# run test experiment
self.sess.runExperiment(
"testEditExpInfo",
expInfo=expInfo,
blocking=True
)
# check that our reference to expInfo is updated too
assert 'insertedKey' in expInfo
assert expInfo['insertedKey'] == "insertedValue"
def test_get_frame_rate(self):
"""
Test getting the frame rate of the monitor.
"""
# get frame rate forcing retest
fr1 = self.sess.getFrameRate(retest=True)
print(fr1)
assert isinstance(fr1, (float, int))
# get frame rate again without a retest and confirm it's the same
fr2 = self.sess.getFrameRate(retest=False)
assert fr1 == fr2
def test_frame_rate(self):
"""
Test that frameRate is present in expInfo when running from Session.
"""
# add test experiment to Session
self.sess.addExperiment("frameRate/frameRate.psyexp", "frameRate")
# make expInfo dict
expInfo = {'participant': "test", 'date': "0/0/000"}
# run test experiment
self.sess.runExperiment(
"frameRate",
expInfo=expInfo,
blocking=True
)
def test_get_device_names(self):
"""
Test that device names can be got from an experiment as expected.
Returns
-------
"""
# add test experiment to Session
self.sess.addExperiment(
"testNamedButtonBox/testNamedButtonBox.psyexp", "testNamedButtonBox"
)
# check its reported device names
names = self.sess.getRequiredDeviceNamesFromExperiment("testNamedButtonBox")
assert names == ["testNamedButtonBox"]
# def test_error(self, capsys):
# """
# Check that an error in an experiment doesn't interrupt the session.
# """
# # run experiment which has an error in it
# success = self.sess.runExperiment("error")
# # check that it returned False after failing
# assert not success
# # flush the log
# logging.flush()
# # get stdout and stderr
# stdout, stderr = capsys.readouterr()
# # check that our error has been logged as CRITICAL
# assert "CRITICAL" in stdout + stderr
# assert "ValueError:" in stdout + stderr
# # check that another experiment still runs after this
# success = self.sess.runExperiment("exp1")
# assert success
| 9,533
|
Python
|
.py
| 234
| 30.307692
| 120
| 0.58743
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,477
|
test_monitors.py
|
psychopy_psychopy/psychopy/tests/test_monitors/test_monitors.py
|
import os
import sys
import glob
import uuid
from psychopy.monitors.calibTools import Monitor
import numpy as np
import pytest
@pytest.mark.monitors
class TestMonitorCalibration():
def setup_class(self):
self.monitor_name = str(uuid.uuid4().hex) # random monitor name
if sys.platform == 'win32':
self.monitor_folder = os.path.join(os.environ['APPDATA'],
'psychopy3', 'monitors')
else:
self.monitor_folder = os.path.join(os.environ['HOME'],
'.psychopy3', 'monitors')
self.fullname = os.path.join(self.monitor_folder, self.monitor_name)
self.mon = Monitor(self.monitor_name,
width=40,
distance=57,
gamma=1.0,
notes='Here are notes')
def teardown_class(self):
"""Remove leftover monitor calibration files (if they exist)"""
for f in glob.glob(self.fullname + '.*'):
os.remove(f)
def test_save(self):
"""See if the monitor calibration file ended up in the correct
location"""
self.mon.save()
assert os.path.isfile(self.fullname + '.json')
def test_saveMon(self):
"""See if the monitor calibration file ended up in the correct
location"""
self.mon.save()
assert os.path.isfile(self.fullname + '.json')
def test_reload_monitor(self):
"""Reload the monitor and verify that all elements in each object
match"""
mon2 = Monitor(self.monitor_name)
# test that all values in the reloaded monitor match the original
# instance
for key1 in self.mon.calibs.keys():
for key2 in self.mon.calibs[key1].keys():
if isinstance(self.mon.calibs[key1][key2],
(np.ndarray, np.generic)):
assert (self.mon.calibs[key1][key2] ==
mon2.calibs[key1][key2]).all()
else:
assert (self.mon.calibs[key1][key2] ==
mon2.calibs[key1][key2])
@pytest.mark.monitors
def test_linearizeLums_method_1():
m = Monitor(name='foo')
m.currentCalib['gamma'] = 1
m.currentCalib['linearizeMethod'] = 1
desired_lums = np.array([0.1, 0.2, 0.3])
r = m.linearizeLums(desiredLums=desired_lums)
assert np.allclose(r, desired_lums)
@pytest.mark.monitors
def test_lineariseLums_method_1():
m = Monitor(name='foo')
m.currentCalib['gamma'] = 1
m.currentCalib['linearizeMethod'] = 1
desired_lums = np.array([0.1, 0.2, 0.3])
# American spelling
r = m.linearizeLums(desiredLums=desired_lums)
assert np.allclose(r, desired_lums)
# British spelling
r = m.lineariseLums(desiredLums=desired_lums)
assert np.allclose(r, desired_lums)
if __name__ == '__main__':
pytest.main()
| 2,986
|
Python
|
.py
| 74
| 30.148649
| 76
| 0.587565
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,478
|
known_py_diffs.txt
|
psychopy_psychopy/psychopy/tests/test_experiment/known_py_diffs.txt
|
#
# This file is used to contain diffs that do not indicate a meaningful test failure, and so should be ignored.
#
# If testExperiment fails because of a diff between .py files, a file "tmp_py_diff_NameOfPsyexpScript.tmp" will be generated.
# However, the .py file from (load psyexp -> .py) might differ in uninteresting ways from the .py file
# from (load psyexp -> saveToXML -> loadFromXML -> .py), e.g., based merely on the order of items within a dict.
# If a diff is generated, its worth inspecting it as a clue to a bug, or for how to ignore it.
#
# Check for a new file (e.g., shows up as an unstaged change in git gui), and view the diff in the temp file.
# From there, inspect the original XML file. In the case of the Navon task, there was a dict for a trialList:
# <Param name="trialList" val="[{'xPos': 200.0, 'congruence': 'conflicting', 'yPos': 200.0, 'corrAns': 'h',
# 'stimFile': 'bigHsmallH.png', 'location': 'up_right'},
# that was getting written out in different orders into the .py file:
# stimOut=['xPos', 'congruence', 'yPos', 'location', 'stimFile', 'corrAns', ]
# So it looks like something that SHOULD be ignored. To ignore, you can just append (>>) the tmp_py_diff.tmp to this file
# (the "known_py_diff.txt" file):
# cat tmp_py_diff.txt >> known_py_diffs.txt
# If you then run testApp again, and that was the only issue, the test should succeed.
# For the Navon task, I added logic to screen out diffs that consist of lines starting with stimOut and
# vary only in the order of items within the line. So that one is suppressed without reference to this file
# ------------------------------------- append diffs below: -------------------------------------
# example:
NavonTask.psyexp.py load-save difference in resulting .py files: ---------------
@@ -226,7 +226,7 @@
practiceTrials.saveAsPickle(filename+'practiceTrials')
practiceTrials.saveAsExcel(filename+'.xlsx', sheetName='practiceTrials',
- stimOut=['xPos', 'congruence', 'yPos', 'location', 'stimFile', 'corrAns', ],
+ stimOut=['xPos', 'congruence', 'yPos', 'corrAns', 'stimFile', 'location', ],
dataOut=['n','all_mean','all_std', 'all_raw'])
#update component parameters for each repeat
@@ -308,7 +308,7 @@
trials.saveAsPickle(filename+'trials')
trials.saveAsExcel(filename+'.xlsx', sheetName='trials',
- stimOut=['xPos', 'congruence', 'yPos', 'location', 'stimFile', 'corrAns', ],
+ stimOut=['xPos', 'congruence', 'yPos', 'corrAns', 'stimFile', 'location', ],
dataOut=['n','all_mean','all_std', 'all_raw'])
#update component parameters for each repeat
--------------------------------------------------------------------------------
| 2,729
|
Python
|
.py
| 38
| 68.789474
| 126
| 0.653428
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,479
|
test_experiment.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_experiment.py
|
from psychopy import experiment
from psychopy.tests.utils import TESTS_DATA_PATH
from pathlib import Path
import esprima
class TestExperiment:
def test_resources(self):
def getResources(handled):
"""
Get a list of resources which appear in the JS file.
Parameters
----------
handled : bool
If True, include a Routine with a Resource Manager in.
"""
# make experiment with handled resources
exp = experiment.Experiment()
exp.loadFromXML(Path(TESTS_DATA_PATH) / "test_resources.psyexp")
# if not handled, remove handling routine
if not handled:
exp.flow.pop(0)
# compile JS
script = exp.writeScript(target="PsychoJS")
# parse JS to get resource spec
tree = esprima.tokenize(script)
for i, node in enumerate(tree):
# we're looking for the "start" call specifically
if all((
node.type == "Identifier", node.value == "start",
tree[i-1].type == "Punctuator", tree[i-1].value == ".",
tree[i-2].type == "Identifier", tree[i-2].value == "psychoJS"
)):
startIndex = i
break
# within the start call, find the declaration of "resources"
for i, node in enumerate(tree[startIndex:]):
i += startIndex
if all((
node.type == "Identifier", node.value == "resources",
tree[i+1].type == "Punctuator", tree[i+1].value == ":"
)):
startIndex = i + 3
break
# get everything inside resources
resources = []
for i, node in enumerate(tree[startIndex:]):
# break on closing
if node.type == "Punctuator" and node.value == "]":
break
# append node
resources.append(node.value)
# unparse back to raw code
resources = "".join(resources)
return resources
"""
Case structure
==============
value : str
Value to look for
handled : bool
Whether or not this value should be present when handled
unhandled : bool
Whether or not this value should be present when unhandled
"""
cases = [
# default stim should always be present
{'value': "pavlovia.org/assets/default/default.png", 'handled': True, 'unhandled': True},
{'value': "pavlovia.org/assets/default/default.mp3", 'handled': True, 'unhandled': True},
{'value': "pavlovia.org/assets/default/default.mp4", 'handled': True, 'unhandled': True},
{'value': "pavlovia.org/assets/default/creditCard.png", 'handled': True, 'unhandled': True},
{'value': "pavlovia.org/assets/default/USB.png", 'handled': True, 'unhandled': True},
{'value': "pavlovia.org/assets/default/USB-C.png", 'handled': True, 'unhandled': True},
# regular stim should only be present when unhandled
{'value': "testpixels.png", 'handled': False, 'unhandled': True},
{'value': "testMovie.mp4", 'handled': False, 'unhandled': True},
{'value': "Electronic_Chime-KevanGC-495939803.wav", 'handled': False, 'unhandled': True},
# survey ID and lib should always be present
{'value': "1906fa4a-e009-49aa-b63d-798d8bf46c22", 'handled': True, 'unhandled': True},
{'value': "'surveyLibrary':true", 'handled': True, 'unhandled': True},
]
# get resources present when handled
handledResources = getResources(True)
# get resources present when unhandled
unhandledResources = getResources(False)
for case in cases:
# check presence in handled resources
if case['handled']:
assert case['value'] in handledResources
else:
assert case['value'] not in handledResources
# check presence in unhandled resources
if case['unhandled']:
assert case['value'] in unhandledResources
else:
assert case['value'] not in unhandledResources
| 4,439
|
Python
|
.py
| 94
| 33.957447
| 104
| 0.550046
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,480
|
test_component_compile_js.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_component_compile_js.py
|
import os
import shutil
from tempfile import mkdtemp
from psychopy.experiment import getAllComponents, Experiment
from psychopy.tests.utils import compareTextFiles, TESTS_DATA_PATH
from psychopy.scripts import psyexpCompile
class TestComponentCompilerJS():
"""A class for testing the JS code compiler for all components"""
def setup_method(self):
self.temp_dir = mkdtemp()
self.allComp = getAllComponents(fetchIcons=False)
self.exp = Experiment() # create once, not every test
# Create correctScript subdir for holding correct scripts
if not os.path.isdir(os.path.join(TESTS_DATA_PATH, "correctScript", "js")):
os.mkdir(os.path.join(TESTS_DATA_PATH, "correctScript", "js"))
def teardown_method(self):
shutil.rmtree(self.temp_dir)
def test_all_components(self):
"""Test all component code outputs, except for Settings and Unknown"""
for compName in self.allComp:
if compName not in ['SettingsComponent', 'UnknownComponent']:
# reset exp
self.reset_experiment(compName)
# Add components
psychoJSComponent = self.add_components(compName)
# Create output script if component is a PsychoJS target
if psychoJSComponent:
self.create_component_output(compName)
# Get correct script path
# correctPath = os.path.join(TESTS_DATA_PATH, "correctScript", "js", 'correct{}.js'.format(compName))
# Compare files, raising assertions on fails above tolerance (%)
# try:
# compareTextFiles('new{}.js'.format(compName), correctPath, tolerance=3)
# except IOError as err:
# compareTextFiles('new{}.js'.format(compName), correctPath, tolerance=3)
def reset_experiment(self, compName):
"""Resets the exp object for each component"""
self.exp = Experiment() # create once, not every test
self.exp.addRoutine('trial')
self.exp.flow.addRoutine(self.exp.routines['trial'], pos=0)
self.exp.filename = compName
def add_components(self, compName):
"""Add components to routine if they have a PsychoJS target"""
thisComp = self.allComp[compName](parentName='trial', exp=self.exp)
if 'PsychoJS' in thisComp.targets:
self.exp.routines['trial'].addComponent(thisComp)
return True
return False
def create_component_output(self, compName):
"""Create the JS script"""
jsFilePath = os.path.join(self.temp_dir, 'new{}.js'.format(compName))
psyexpCompile.compileScript(infile=self.exp, outfile=jsFilePath)
| 2,775
|
Python
|
.py
| 52
| 42.769231
| 121
| 0.648012
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,481
|
test_component_compile_python.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_component_compile_python.py
|
import os
import shutil
from pathlib import Path
from tempfile import mkdtemp
from psychopy.experiment import getAllComponents, Experiment
from psychopy.tests.utils import compareTextFiles, TESTS_DATA_PATH
from psychopy.scripts import psyexpCompile
from psychopy import constants
class _TestBoilerplateMixin:
"""
Mixin for tests of classes in the PsychoPy library to check they are able to work with the compiled code from
Builder.
"""
obj = None
def test_input_params(self):
"""
All classes called from boilerplate should accept name and autoLog as input params
"""
if self.obj is None:
return
# Define list of names which need to be accepted by init
required = (
"name",
"autoLog"
)
# Get names of input variables
varnames = type(self.obj).__init__.__code__.co_varnames
# Make sure required names are accepted
for name in required:
assert name in varnames, (
f"{type(self.obj)} init function should accept {name}, but could not be found in list of kw args."
)
def test_status(self):
"""
All classes called from boilerplate should have a settable status attribute which accepts psychopy constants
"""
if self.obj is None:
return
# Check that status can be NOT_STARTED without error
self.obj.status = constants.NOT_STARTED
# Check that status can be STARTED without error
self.obj.status = constants.STARTED
# Check that status can be FINISHED without error
self.obj.status = constants.FINISHED
# Set back to NOT_STARTED for other tests
self.obj.status = constants.NOT_STARTED
# Define classes to skip depth tests on
depthExceptions = ("NoneType", "PanoramaStim")
# Error string for how to mark depth exempt
exemptInstr = (
"If this component is a special case, you can mark it as exempt by adding its class name to the "
"`depthExceptions` variable in this test."
)
def test_can_accept_depth(self):
# Get class name
compName = type(self.obj).__name__
# Skip if exception
if compName in self.depthExceptions:
return
# Get accepted varnames for init function
varnames = type(self.obj).__init__.__code__.co_varnames
# Check whether depth is in there
assert "depth" in varnames, (
f"Init function for class {compName} cannot accept `depth` as an input, only accepts:\n"
f"{varnames}\n"
f"Any component drawn to the screen should be given a `depth` on init. {self.exemptInstr}\n"
)
def test_depth_attr(self):
# Get class name
compName = type(self.obj).__name__
# Skip if exception
if compName in self.depthExceptions:
return
# Check that created object has a depth
assert hasattr(self.obj, "depth"), (
f"Could not find depth attribute in {compName}.\n"
f"\n"
f"Any component drawn to the screen should have a `depth` attribute. {self.exemptInstr}\n"
)
class TestComponentCompilerPython():
"""A class for testing the Python code compiler for all components"""
def setup_method(self):
self.temp_dir = mkdtemp()
self.allComp = getAllComponents(fetchIcons=False)
self.exp = Experiment() # create once, not every test
self.exp.addRoutine('trial')
self.exp.flow.addRoutine(self.exp.routines['trial'], pos=0)
# Create correctScript subdir for holding correct scripts
if not os.path.isdir(os.path.join(TESTS_DATA_PATH, "correctScript", "python")):
os.mkdir(os.path.join(TESTS_DATA_PATH, "correctScript", "python"))
def teardown_method(self):
shutil.rmtree(self.temp_dir)
def test_all_components(self):
"""Test all component code outputs, except for Settings and Unknown"""
for compName in self.allComp:
if compName not in ['SettingsComponent', 'UnknownComponent']:
# reset exp
self.reset_experiment()
# Add components
self.add_components(compName)
# Create output script
self.create_component_output(compName)
# Get correct script path
# correctPath = os.path.join(TESTS_DATA_PATH, "correctScript", "python", 'correct{}.py'.format(compName))
# Compare files, raising assertions on fails above tolerance (%)
# try:
# compareTextFiles('new{}.py'.format(compName), correctPath, tolerance=5)
# except IOError as err:
# compareTextFiles('new{}.py'.format(compName), correctPath, tolerance=5)
def reset_experiment(self):
"""Resets the exp object for each component"""
self.exp = Experiment()
self.exp.addRoutine('trial')
self.exp.flow.addRoutine(self.exp.routines['trial'], pos=0)
def add_components(self, compName):
"""Add components to routine"""
thisComp = self.allComp[compName](parentName='trial', exp=self.exp)
if compName == 'StaticComponent':
# Create another component to trigger param updates for static
textStim = self.allComp['TextComponent'](parentName='trial', exp=self.exp)
textStim.params['color'].allowedUpdates.append('set during: trial.ISI')
textStim.params['color'].updates = 'set during: trial.ISI'
self.exp.routines['trial'].addComponent(textStim)
# Create static component
thisComp.addComponentUpdate('trial', 'text', 'color')
thisComp.params['code'].val = "customStaticCode = True" # Add the custom code
self.exp.routines['trial'].addComponent(thisComp)
else:
self.exp.routines['trial'].addComponent(thisComp)
def create_component_output(self, compName):
"""Create the Python script"""
pyFilePath = os.path.join(self.temp_dir, 'new{}.py'.format(compName))
psyexpCompile.compileScript(infile=self.exp, outfile=pyFilePath)
def test_component_type_in_experiment(self):
for compName, compObj in self.allComp.items():
if (compName not in [
'SettingsComponent', 'UnknownComponent',
'UnknownPluginComponent', 'RoutineSettingsComponent'
] and "PsychoPy" in compObj.targets):
# reset exp
self.reset_experiment()
# Add components
self.add_components(compName)
# Check component in exp
component = compName.split('Component')[0]
assert self.exp.getComponentFromType(component), (
f"Could not find component of type {compName} in: {self.exp.flow}"
)
| 7,002
|
Python
|
.py
| 148
| 37.195946
| 121
| 0.631564
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,482
|
test_loops.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_loops.py
|
import codecs
import shutil
import sys
from pathlib import Path
from tempfile import mkdtemp
import numpy as np
import pandas as pd
from ..utils import TESTS_DATA_PATH
from psychopy import experiment, core, logging
from psychopy import prefs, core
prefs.hardware['audioLib'] = ['ptb', 'sounddevice']
class TestLoops:
@classmethod
def setup_class(cls):
"""
Load and run various experiments just once and use the objects / output in later tests
"""
# Setup temporary dir
try:
cls.tempDir = mkdtemp(dir=Path(__file__).root, prefix='psychopy-tests-loops')
except (PermissionError, OSError):
# can't write to root on Linux
cls.tempDir = mkdtemp(prefix='psychopy-tests-loops')
# List of filenames for experiments to run
filenames = [
'testLoopsBlocks',
'testStaircase',
'test_current_loop_attr'
]
# Run each experiment to get data
cls.cases = {}
for filename in filenames:
# Copy file to temp dir so it's in the same folder as we want data to output to
ogExpFile = Path(TESTS_DATA_PATH) / "test_loops" / f"{filename}.psyexp"
expFile = Path(cls.tempDir) / f"{filename}.psyexp"
shutil.copy(ogExpFile, expFile)
# Load experiment from file
exp = experiment.Experiment()
exp.loadFromXML(expFile)
# Change data file output to temp dir
datafile = (Path(cls.tempDir) / "data" / f"{filename}.csv")
exp.settings.params['Data filename'].val = f"'data' + os.sep + '{filename}'"
# Write scripts
pyScript = exp.writeScript(target="PsychoPy")
# jsScript = exp.writeScript(target="PsychoJS") # disabled until all loops work in JS
# Save Python script to temp dir
pyScriptFile = Path(cls.tempDir) / f"{filename}.py"
with codecs.open(str(pyScriptFile), 'w', 'utf-8-sig') as f:
f.write(pyScript)
# Run Python script to generate data file
stdout, stderr = core.shellCall([sys.executable, str(pyScriptFile)], stderr=True)
# print stdout so the test suite can see it
print(stdout)
# log any errors so the test suite can see them
if stderr:
logging.error(stderr)
# error if data didn't save
if not datafile.is_file():
raise RuntimeError("Data file wasn't saved. PsychoPy StdErr below:\n" + stderr)
# Load data file
data = pd.read_csv(str(datafile)).values.tolist()
# Store
cls.cases[filename] = {
'exp': exp,
'pyScript': pyScript,
# 'jsScript': jsScript, # disabled until all loops work in JS
'data': data,
'stdout': stdout,
'stderr': stderr,
}
def teardown_class(cls):
# delete temp folder
shutil.rmtree(cls.tempDir)
def test_output_length(self):
"""
Check that experiments with loops produce data of the correct length
"""
# Define desired length for each case
answers = {
'testLoopsBlocks': 8, # because 4 'blocks' with 2 trials each (3 stims per trial)
'testStaircase': 6, # 5 reps + row for start time of final run
}
# Test each case
for filename, case in self.cases.items():
if filename in answers:
assert len(case['data']) == answers[filename], (
f"Expected array {answers[filename]} long, received:\n"
f"{case['data']}"
)
def test_current_loop_attr(self):
assert "___FAILURE___" not in self.cases['test_current_loop_attr']['stderr'], (
self.cases['test_current_loop_attr']['stderr']
)
| 3,978
|
Python
|
.py
| 93
| 31.989247
| 98
| 0.581503
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,483
|
test_py2js.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_py2js.py
|
from psychopy.experiment.py2js_transpiler import translatePythonToJavaScript
import psychopy.experiment.py2js as py2js
from psychopy.experiment import Experiment
from psychopy.experiment.components.code import CodeComponent
from psychopy.experiment.routines import Routine
class TestTranspiler:
def runTranspile(self, py, js):
transpiledCode = translatePythonToJavaScript(py)
assert (js == transpiledCode)
def test_assignment(self):
py = ("a = 1")
js = ("var a;\na = 1;\n")
self.runTranspile(py, js)
def test_name(self):
# Some typical cases
exemplars = [
{'py': "normalName",
'js': "normalName;\n"}
]
# Some problem cases
tykes = [
{'py': "variableName",
'js': "variableName;\n"} # Name containing "var" (should no longer return blank as of #4336)
]
for case in exemplars + tykes:
self.runTranspile(case['py'], case['js'])
def test_if_statement(self):
py = ("if True:\n True")
js = ("if (true) {\n true;\n}\n")
self.runTranspile(py, js)
def test_print(self):
py = ("print(True)")
js = ("console.log(true);\n")
self.runTranspile(py, js)
def test_function(self):
py = ("def fun(a):\n print(a)")
js = ("function fun(a) {\n console.log(a);\n}\n")
self.runTranspile(py, js)
def test_status(self):
py = "status = STOPPED"
js = "var status;\nstatus = PsychoJS.Status.STOPPED;\n"
self.runTranspile(py, js)
def test_substitutions(self):
# Define some cases which should be handled
cases = [
{'py': "a.append(4)", 'js': "a.push(4);\n"},
{'py': "a.split()", 'js': 'a.split(" ");\n'},
{'py': "a.split('.')", 'js': 'a.split(".");\n'},
{'py': "a.sort(reverse=True)", 'js': "a.reverse();\n"},
{'py': "a.sort()", 'js': "a.sort();\n"},
{'py': "a.insert(0, 5)", 'js': "a.splice(0, 0, 5);\n"},
{'py': "a.insert(-1, x)", 'js': "a.splice((- 1), 0, x);\n"},
{'py': "' '.join(a)", 'js': 'a.join(" ");\n'},
{'py': "a.index(2)", 'js': "util.index(a, 2);\n"},
{'py': "a.count(2)", 'js': "util.count(a, 2);\n"},
{'py': "a.lower()", 'js': "a.toLowerCase();\n"},
{'py': "a.upper()", 'js': "a.toUpperCase();\n"},
{'py': "a.extend([4, 5, 6])", 'js': "a.concat([4, 5, 6]);\n"},
{'py': "a.pop(0)", 'js': "a.splice(0, 1);\n"},
{'py': "a.pop()", 'js': "a.splice((a.length - 1), 1);\n"},
]
# Try each case
for case in cases:
self.runTranspile(case['py'], case['js'])
def test_util_substitutions(self):
# Define some cases which should be handled
cases = [
{'py': "shuffle(a)", 'js': "util.shuffle(a);\n"},
{'py': "sum(a)", 'js': "util.sum(a);\n"},
{'py': "average(a)", 'js': "util.average(a);\n"},
{'py': "core.Clock()", 'js': "new util.Clock();\n"},
]
# Try each case
for case in cases:
self.runTranspile(case['py'], case['js'])
def test_var_defs(self):
cases = [
# Docstring at line 1
{'py': (
"""'''
Docstring at line 1
'''
continueRoutine = False"""
),
'var': False},
# Comment at line 1
{'py': (
"""# Comment at line 1
continueRoutine = False"""
),
'var': False},
# PsychoPy keyword (just one)
{'py': (
"""continueRoutine = False"""
),
'var': False},
# PsychoPy keywords
{'py': (
"""continueRoutine = False
expInfo = {}"""
),
'var': False},
# Numpy keywords
{'py': (
"""sin = None
pi = 3.14"""
),
'var': False},
# Package names
{'py': (
"""visual = psychopy.visual
np = numpy"""
),
'var': False},
# Component name
{'py': (
"""testComponent = None"""
),
'var': False},
# Routine name
{'py': (
"""testRoutine = None"""
),
'var': False},
# Valid var def
{'py': (
"""newVariable = 0"""
),
'var': True},
# One valid one invalid
{'py': (
"""continueRoutine = False
newVariable = {}"""
),
'var': True},
# Valriable from Code component
{'py': (
"""extantVariable = 0"""
),
'var': True},
]
# Setup experiment
exp = Experiment()
rt = Routine("testRoutine", exp)
comp = CodeComponent(exp, parentName="testRoutine", name="testComponent", beforeExp="extantVariable = 1")
rt.addComponent(comp)
exp.addRoutine("testRoutine", rt)
exp.flow.addRoutine(rt, 0)
# Add comp and routine names to namespace (this is usually done from Builder
exp.namespace.add("testRoutine")
exp.namespace.add("testComponent")
# Run cases
for case in cases:
# Translate with exp namespace
jsCode = py2js.translatePythonToJavaScript(case['py'], namespace=exp.namespace.all)
# Check whether var statements are present
if case['var']:
assert "var " in jsCode, (
f"Could not find desired var def in:\n"
f"{jsCode}"
)
else:
assert "var " not in jsCode, (
f"Found undesired var def in:\n"
f"{jsCode}"
)
class Test_PY2JS_Compile:
"""
Test class for py2js code conversion
"""
def test_Py2js_Expression2js(self):
"""Test that converts a short expression (e.g. a Component Parameter) Python to JS"""
input = ['sin(t)',
'cos(t)',
'tan(t)',
'floor(t)',
'ceil(t)',
'pi',
'rand',
'random',
't*5',
'(3, 4)',
'(5*-2)',
'(1,(2,3))',
'2*(2, 3)',
'[1, (2*2)]',
'(.7, .7)',
'(-.7, .7)',
'[-.7, -.7]',
'[-.7, (-.7 * 7)]']
output = ['Math.sin(t)',
'Math.cos(t)',
'Math.tan(t)',
'Math.floor(t)',
'Math.ceil(t)',
'Math.PI',
'Math.random',
'Math.random',
'(t * 5)',
'[3, 4]',
'(5 * (- 2))',
'[1, [2, 3]]',
'(2 * [2, 3])',
'[1, (2 * 2)]',
'[0.7, 0.7]',
'[(- 0.7), 0.7]',
'[(- 0.7), (- 0.7)]',
'[(- 0.7), ((- 0.7) * 7)]']
for idx, expr in enumerate(input):
# check whether direct match or at least a match when spaces removed
assert (py2js.expression2js(expr) == output[idx] or
py2js.expression2js(expr).replace(" ", "") == output[idx].replace(" ", ""))
| 7,477
|
Python
|
.py
| 212
| 23.853774
| 113
| 0.439906
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,484
|
test_params.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_params.py
|
import re
import inspect
from pathlib import Path
from ..utils import _q, _lb, _rb, _d, _sl
from psychopy import experiment
from psychopy.experiment import Param, utils as exputils
class TestStyle:
"""
Tests for grammar, spelling, case conventions & PsychoPy-isms in user-facing
strings
"""
keywords = {
# PsychoPy keywords
'routine': "Routine",
'component': "Component",
'param': "Param",
'parameter': "Parameter",
'standalone routine': "Standalone Routine",
'Standalone routine': "Standalone Routine",
# our brand names
'psychopy': "PsychoPy",
'psychojs': "PsychoJS",
'pavlovia': "Pavlovia",
'surveyjs': "SurveyJS",
# other brand names
'python': "Python",
'excel': "Excel",
'gazepoint': "GazePoint",
'eyelink': "EyeLink",
'opengl': "OpenGL",
# initialisms
'json': "JSON",
'rtl': "RTL",
'ltr': "LTR",
'url': "URL",
'html': "HTML",
'js': "JS",
'ip': "IP",
'rt': "RT",
}
# add sentence start versions
for kw in keywords.copy():
keywords[kw.capitalize()] = keywords[kw]
def setup_class(self):
# dummy experiment to dump class instances in
exp = experiment.Experiment()
# list of dicts:
# - 'name': element name
# - 'instance': element instance
# - 'class': element class
# - 'file': def file
self.cases = []
# populate cases list
for name, cls in experiment.getAllElements().items():
# create basic instance of class
try:
emt = cls(exp=exp)
except TypeError:
emt = cls(exp=exp, parentName="")
# get file in which class was defined
file = Path(inspect.getfile(cls))
# append to cases
self.cases.append({
'name': name,
'instance': emt,
'class': cls,
'file': file
})
@staticmethod
def capitalizeKeywords(phrase):
"""
Appropriately capitalize any uses of keywords (e.g. PsychoPy rather
than psychopy) in a given phrase
Parameters
----------
phrase : str, re.Match
Phrase to process. If called from `re.sub`, will extract first match.
"""
# if being called from re.sub, use the first match
if isinstance(phrase, re.Match):
phrase = phrase[1]
for pattern, repl in TestStyle.keywords.items():
# replace any keywords which are an entire word
phrase = re.sub(pattern=(
f"(?<= )({pattern})(?= )" # space before and after
f"|(?<= )({pattern})$" # space before and line end after
f"|(?<= )({pattern})(?=[^\w\s]+)" # space before and punctuation after
f"|^({pattern})(?= )" # line start before and space after
f"|^({pattern})(?=[^\w\s]+)" # line start before and punctuation after
f"|^({pattern})$" # line start before and line end after
), string=phrase, repl=repl)
return phrase
def test_case(self):
"""
Labels should all be in `Sentence case` - first word (and first word after
full stop) capitalized, the rest lower. Apart from keywords.
"""
def _validate(compName, paramName, value, sanitized):
# # uncomment this and comment the assertion to make substitutions now
# content = case['file'].read_text()
# content = re.sub(
# pattern=(
# r"(?<=_translate\()[\"']"
# + re.escape(value) +
# r"[\"'](?=\))"
# ),
# string=content,
# repl='"' + sanitized + '"'
# )
# case['file'].write_text(content)
# check value
assert value == sanitized, (
f"Found incorrect case in label/hint for param {paramName} "
f"of {compName}: wanted '{sanitized}', got '{value}'."
)
for case in self.cases:
# iterate through params from instance
for paramName, param in case['instance'].params.items():
# check that hint has keywords capitalized
sanitizedHint = self.capitalizeKeywords(param.hint)
_validate(
compName=case['name'],
paramName=paramName,
value=param.hint,
sanitized=sanitizedHint,
)
# check that label is in sentence case with keywords capitalized
sanitizedLabel = self.capitalizeKeywords(param.label.capitalize())
_validate(
compName=case['name'],
paramName=paramName,
value=param.label,
sanitized=sanitizedLabel,
)
def test_localized_deprecation(self):
"""
Make sure that new components are using _translate rather than _localized
"""
for case in self.cases:
# get file contents
content = case['file'].read_text()
# look for _localized
isLocalized = re.compile(
r"(_localized\[)"
r"([^\]]*)"
r"(\])"
)
# make sure we don't use _localize
assert not re.findall(
pattern=isLocalized,
string=content
), "Use of _localized found in %(file)s." % case
def test_param_str():
"""
Test that params convert to str as expected in both Python and JS
"""
sl = "\\"
cases = [
# Regular string
{"obj": Param("Hello there", "str"),
"py": f"{_q}Hello there{_q}",
"js": f"{_q}Hello there{_q}"},
# Enforced string
{"obj": Param("\\, | or /", "str", canBePath=False),
"py": f"{_q}{_sl}, \| or /{_q}",
"js": f"{_q}{_sl}, \| or /{_q}"},
# Dollar string
{"obj": Param("$win.color", "str"),
"py": f"win.color",
"js": f"psychoJS.window.color"},
# Integer
{"obj": Param("1", "int"),
"py": f"1",
"js": f"1"},
# Float
{"obj": Param("1", "num"),
"py": f"1.0",
"js": f"1.0"},
# File path
{"obj": Param("C:/Downloads/file.ext", "file"),
"py": f"{_q}C:/Downloads/file.ext{_q}",
"js": f"{_q}C:/Downloads/file.ext{_q}"},
# Table path
{"obj": Param("C:/Downloads/file.csv", "table"),
"py": f"{_q}C:/Downloads/file.csv{_q}",
"js": f"{_q}C:/Downloads/file.csv{_q}"},
# Color
{"obj": Param("red", "color"),
"py": f"{_q}red{_q}",
"js": f"{_q}red{_q}"},
# RGB Color
{"obj": Param("0.7, 0.7, 0.7", "color"),
"py": f"{_lb}0.7, 0.7, 0.7{_rb}",
"js": f"{_lb}0.7, 0.7, 0.7{_rb}"},
# Code
{"obj": Param("win.color", "code"),
"py": f"win.color",
"js": f"psychoJS.window.color"},
# Extended code
{"obj": Param("for x in y:\n\tprint(y)", "extendedCode"),
"py": f"for x in y:\n\tprint{_lb}y{_rb}",
"js": f"for x in y:\n\tprint{_lb}y{_rb}"}, # this will change when snipped2js is fully working
# List
{"obj": Param("1, 2, 3", "list"),
"py": f"{_lb}1, 2, 3{_rb}",
"js": f"{_lb}1, 2, 3{_rb}"},
# Extant file path marked as str
{"obj": Param(__file__, "str"),
"py": f"{_q}{__file__.replace(sl, '/')}{_q}",
"js": f"{_q}{__file__.replace(sl, '/')}{_q}"},
# Nonexistent file path marked as str
{"obj": Param("C:\\\\Downloads\\file.csv", "str"),
"py": f"{_q}C:/Downloads/file.csv{_q}",
"js": f"{_q}C:/Downloads/file.csv{_q}"},
# Underscored file path marked as str
{"obj": Param("C:\\\\Downloads\\_file.csv", "str"),
"py": f"{_q}C:/Downloads/_file.csv{_q}",
"js": f"{_q}C:/Downloads/_file.csv{_q}"},
# Escaped $ in str
{"obj": Param("This costs \\$4.20", "str"),
"py": f"{_q}This costs {_d}4.20{_q}",
"js": f"{_q}This costs {_d}4.20{_q}"},
# Unescaped \ in str
{"obj": Param("This \\ that", "str"),
"py": f"{_q}This {_sl} that{_q}",
"js": f"{_q}This {_sl} that{_q}"},
# Name containing "var" (should no longer return blank as of #4336)
{"obj": Param("variableName", "code"),
"py": f"variableName",
"js": f"variableName"},
# Color param with a $
{"obj": Param("$letterColor", "color"),
"py": f"letterColor",
"js": f"letterColor"},
# Double quotes naked list
{'obj': Param("\"left\", \"down\", \"right\"", "list"),
'py': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}",
'js': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}"},
# Single quotes naked list
{'obj': Param("\'left\', \'down\', \'right\'", "list"),
'py': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}",
'js': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}"},
# Single quotes tuple syntax
{'obj': Param("(\'left\', \'down\', \'right\')", "list"),
'py': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}",
'js': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}"},
# Single quotes list syntax
{'obj': Param("[\'left\', \'down\', \'right\']", "list"),
'py': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}",
'js': f"{_lb}{_q}left{_q}, {_q}down{_q}, {_q}right{_q}{_rb}"},
# Single value
{'obj': Param("\"left\"", "list"),
'py': f"{_lb}{_q}left{_q}{_rb}"},
# Single value list syntax
{'obj': Param("[\"left\"]", "list"),
'py': f"{_lb}{_q}left{_q}{_rb}"},
# Variable name
{'obj': Param("$left", "list"),
'py': r"left",
'js': r"left"},
]
# Take note of what the script target started as
initTarget = exputils.scriptTarget
# Try each case
for case in cases:
# Test Python
if "py" in case:
exputils.scriptTarget = "PsychoPy"
assert re.fullmatch(case['py'], str(case['obj'])), \
f"`{repr(case['obj'])}` should match the regex `{case['py']}`, but it was `{case['obj']}`"
# Test JS
if "js" in case:
exputils.scriptTarget = "PsychoJS"
assert re.fullmatch(case['js'], str(case['obj'])), \
f"`{repr(case['obj'])}` should match the regex `{case['js']}`, but it was `{case['obj']}`"
# Set script target back to init
exputils.scriptTarget = initTarget
def test_dollar_sign_syntax():
# Define some param values, along with values which Param.dollarSyntax should return
cases = [
# Valid dollar and redundant dollar
{'val': f"$hello $there",
'ans': f"hello {_d}there",
'valid': False},
# Valid dollar and scaped dollar
{'val': "$hello \\$there",
'ans': r"hello \\\$there",
'valid': False},
# Just redundant dollar
{'val': "hello $there",
'ans': f"hello {_d}there",
'valid': False},
# Just escaped dollar
{'val': "\\$hello there",
'ans': r"\\\$hello there",
'valid': True},
# Dollar in comment
{'val': "#$hello there",
'ans': r"#\$hello there",
'valid': False},
# Comment after dollar
{'val': "$#hello there",
'ans': r"#hello there",
'valid': True},
# Dollar and comment
{'val': "$hello #there",
'ans': r"hello #there",
'valid': True},
# Valid dollar and redundtant dollar in comment
{'val': "$hello #$there",
'ans': r"hello #\$there",
'valid': True},
# Valid dollar and escaped dollar in escaped d quotes
{'val': "$hello \"\\$there\"",
'ans': f"hello {_q}" + r"\\\$" + f"there{_q}",
'valid': True},
# Valid dollar and escaped dollar in escaped s quotes
{'val': "$hello \'\\$there\'",
'ans': f"hello {_q}" + r"\\\$" + f"there{_q}",
'valid': True},
]
# Run dollar syntax on each case
for case in cases:
# Make str param from val
param = Param(case['val'], "str")
# Run dollar syntax method
valid, ans = param.dollarSyntax()
# Is the output correct?
assert re.fullmatch(case['ans'], ans), (
f"Dollar syntax for {repr(param)} should return `{case['ans']}`, but instead returns `{ans}`"
)
assert valid == case['valid'], (
f"Dollar syntax function should consider validity of {repr(param)} to be {case['valid']}, but instead "
f"received {valid}"
)
| 13,172
|
Python
|
.py
| 335
| 29.122388
| 115
| 0.490407
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,485
|
test_ResourceManagerComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_ResourceManagerComponent.py
|
from pathlib import Path
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests, _find_global_resource_in_js_experiment
from psychopy.experiment.components.resourceManager import ResourceManagerComponent
from psychopy import experiment
from ...utils import TESTS_DATA_PATH
class TestResourceManagerComponent(BaseComponentTests):
comp = ResourceManagerComponent
def test_handled_resources_removed(self):
"""
Check that resources handled by a resource manager are removed from the start of the experiment
"""
cases = [
# Resource handled by resource manager component, no loop present
{'exp': "handledbyrm_noloop",
'seek': [],
'avoid': ['blue.png', 'white.png', 'yellow.png', 'groups.csv', 'groupA.csv', 'groupB.csv']},
# Resource handled by resource manager component, loop defined by constructed string
{'exp': "handledbyrm_strloop",
'seek': ['groupA.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png', 'groupB.csv', 'groups.csv']},
# Resource handled by resource manager component, loop defined by constructed string
{'exp': "handledbyrm_constrloop",
'seek': ['groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png']},
# Resource handled by resource manager component, loop defined by constructed string from loop
{'exp': "handledbyrm_recurloop",
'seek': ['groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png']},
]
exp = experiment.Experiment()
for case in cases:
# Load experiment
exp.loadFromXML(Path(TESTS_DATA_PATH) / "test_get_resources" / (case['exp'] + ".psyexp"))
# Write to JS
script = exp.writeScript(target="PsychoJS")
# Check that all "seek" phrases are included
for phrase in case['seek']:
assert _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was not found in resources for {case['exp']}.psyexp"
)
# Check that all "avoid" phrases are excluded
for phrase in case['avoid']:
assert not _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was found in resources for {case['exp']}.psyexp"
)
| 2,533
|
Python
|
.py
| 45
| 44.888889
| 138
| 0.614332
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,486
|
test_CodeComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_CodeComponent.py
|
from pathlib import Path
from tempfile import mkdtemp
from psychopy import experiment
from . import BaseComponentTests
from psychopy.experiment.loops import TrialHandler
from psychopy.experiment.routines import Routine
from psychopy.experiment.components.code import CodeComponent
from psychopy.tests.utils import TESTS_DATA_PATH
class TestCodeComponent(BaseComponentTests):
"""
Test that Code coponents have the correct params and write as expected.
"""
comp = CodeComponent
@classmethod
def setup_class(cls):
try:
cls.tempDir = mkdtemp(dir=Path(__file__).root, prefix='psychopy-tests-app')
except (PermissionError, OSError):
# can't write to root on Linux
cls.tempDir = mkdtemp(prefix='psychopy-tests-app')
def test_all_code_component_tabs(self):
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# Names of each tab in a Code component
tabs = {
'Before Experiment': '___before_experiment___',
'Begin Experiment': '___begin_experiment___',
'Begin Routine': '___begin_routine___',
'Each Frame': '___each_frame___',
'End Routine': '___end_routine___',
'End Experiment': '___end_experiment___',
}
# Add markers to component
for paramName, marker in tabs.items():
jsParamName = paramName.replace(" ", " JS ")
comp.params[paramName].val = comp.params[jsParamName].val = " = ".join([self.comp.__name__, comp.name, marker])
# Write script
pyScript = exp.writeScript(target="PsychoPy")
jsScript = exp.writeScript(target="PsychoJS")
# Check that code from each tab exists in compiled script
for lang, script in {"Python": pyScript, "JS": jsScript}.items():
for paramName, marker in tabs.items():
try:
assert marker in script, (
f"Could not find {marker} in {lang} script."
)
except AssertionError as err:
# If test fails here, save the file for easy access
ext = ".py" if lang == "Python" else ".js"
with open(Path(TESTS_DATA_PATH) / ("test_all_code_component_tabs_local" + ext), "w") as f:
f.write(script)
raise err
if lang == "Python":
# Check py code is in the right order in Python (not applicable to JS as it's non-linear)
assert script.find('___before_experiment___') < script.find('___begin_experiment___') < script.find(
'___begin_routine___') < script.find('___each_frame___') < script.find('___end_routine___') < script.find(
'___end_experiment___')
assert script.find('___before_experiment___') < script.find('visual.Window') < script.find(
'___begin_experiment___') < script.find('continueRoutine = True')
assert script.find('continueRoutine = True') < script.find('___begin_routine___') < script.find(
'while continueRoutine:') < script.find('___each_frame___')
assert script.find('thisComponent.setAutoDraw(False)') < script.find('___end_routine___') < script.find(
'routineTimer.reset()') < script.find('___end_experiment___')
| 3,460
|
Python
|
.py
| 63
| 43.079365
| 126
| 0.586431
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,487
|
test_SettingsComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_SettingsComponent.py
|
from pathlib import Path
from .test_base_components import _find_global_resource_in_js_experiment
from psychopy import experiment
from ...utils import TESTS_DATA_PATH
class TestSettingsComponent:
def test_unhandled_resources_js(self):
"""
Check that resources not otherwise handled are present at the start of the experiment
"""
cases = [
# Resource not handled, no loop present
{'exp': "unhandled_noloop",
'seek': ['blue.png'],
'avoid': ['white.png', 'yellow.png', 'groups.csv', 'groupA.csv', 'groupB.csv']},
# Resource not handled, loop defined by string
{'exp': "unhandled_strloop",
'seek': ['blue.png', 'white.png', 'groupA.csv'],
'avoid': ['yellow.png', 'groupB.csv', 'groups.csv']},
# Resource not handled, loop defined by constructed string
{'exp': "unhandled_constrloop",
'seek': ['blue.png', 'white.png', 'yellow.png', 'groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': []},
# Resource not handled, loop defined by constructed string from loop
{'exp': "unhandled_recurloop",
'seek': ['blue.png', 'white.png', 'yellow.png', 'groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': []},
]
exp = experiment.Experiment()
for case in cases:
# Load experiment
exp.loadFromXML(Path(TESTS_DATA_PATH) / "test_get_resources" / (case['exp'] + ".psyexp"))
# Write to JS
script = exp.writeScript(target="PsychoJS")
# Check that all "seek" phrases are included
for phrase in case['seek']:
assert _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was not found in resources for {case['exp']}.psyexp"
)
# Check that all "avoid" phrases are excluded
for phrase in case['avoid']:
assert not _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was found in resources for {case['exp']}.psyexp"
)
def test_get_info(self):
# List of values for expInfo fields, with expected compiled values for python and js
cases = [
# Function call with multiple inputs
{'val': 'randint(0, 999)',
'py': "randint(0, 999)",
'js': "util.randint(0, 999)"}
]
# Construct exp with one big expInfo string from cases
exp = experiment.Experiment()
exp.settings.params['Experiment info'].val = "{"
i = 0
for case in cases:
exp.settings.params['Experiment info'].val += f"'{i}': '{case['val']}',"
i += 1
exp.settings.params['Experiment info'].val += "}"
# Compile to py
pyScript = exp.writeScript(target="PsychoPy")
# Check py
expInfoStr = pyScript.split("expInfo = {")[1]
expInfoStr = expInfoStr.split("}")[0]
i = 0
for case in cases:
wanted = f"'{i}': {case['py']},"
assert wanted in expInfoStr, (
f"Could not find `{wanted}` in ```\n"
f"{expInfoStr}\n"
f"```"
)
i += 1
| 3,338
|
Python
|
.py
| 73
| 34.191781
| 103
| 0.545734
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,488
|
test_GratingComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_GratingComponent.py
|
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests, _TestLibraryClassMixin
from psychopy.experiment.components.grating import GratingComponent
from psychopy.visual import GratingStim
class TestGratingComponent(BaseComponentTests, _TestLibraryClassMixin):
comp = GratingComponent
libraryClass = GratingStim
| 363
|
Python
|
.py
| 6
| 58
| 122
| 0.873596
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,489
|
test_ButtonBoxComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_ButtonBoxComponent.py
|
import itertools
import re
import tempfile
import subprocess
import sys
from pathlib import Path
from psychopy.session import Session
from psychopy.experiment import Experiment
from psychopy.hardware.button import ButtonResponse
from psychopy.experiment.routines import Routine
from psychopy.experiment.components.buttonBox import ButtonBoxComponent
from psychopy.experiment.components.code import CodeComponent
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests
from psychopy.hardware.button import ButtonBox
class TestButtonBoxComponent(BaseComponentTests):
comp = ButtonBoxComponent
libraryClass = ButtonBox
def test_values(self):
"""
Test that a variety of different values work when run from Builder.
"""
# define some fields and possible values
fields = {
'forceEndRoutine': [True, False],
'store': [True, False],
'allowedButtons': [
[0, 1, 2],
],
'storeCorrect': [True, False],
'correctAns': [
0, 1,
],
'resps': [
[
ButtonResponse(t=0, value=True, channel=0),
ButtonResponse(t=0, value=False, channel=0),
],
[
ButtonResponse(t=0, value=True, channel=1),
ButtonResponse(t=0, value=False, channel=1),
],
],
}
# make keys and values into two lists
keys = list(fields.keys())
values = list(fields.values())
# iterate through all combinations of values
cases = []
for vals in itertools.product(*values):
# make a case
thisCase = {}
# populate with values from this iteration
for i, val in enumerate(vals):
thisCase[keys[i]] = val
# add case
cases.append(thisCase)
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# configure experiment
exp.requireImport("ButtonResponse", importFrom="psychopy.hardware.button")
exp.settings.params['Full-screen window'].val = False
exp.settings.params['Show info dlg'].val = False
exp.settings.params['Window size (pixels)'].val = "[120, 120]"
# add a Routine for each case
for i, case in enumerate(cases):
# pop response to separate from params
resps = case.pop("resps")
if not isinstance(resps, (list, tuple)):
resps = [resps]
# add timeout
rt.settings.params['stopVal'].val = 0.2
# make a Code Component to send responses
code = (
"if frameN > 1:\n"
)
for resp in resps:
code += (
" {name}.device.receiveMessage(\n"
" ButtonResponse(t=t, value={value}, channel={channel})\n"
" )\n"
).format(
name=comp.name, value=resp.value, channel=resp.channel
)
codeComp = CodeComponent(
exp, parentName=comp.name + "_code", eachFrame=code
)
rt.addComponent(codeComp)
# save exp in temp directory
tmpDir = Path(tempfile.mkdtemp())
tmpExp = tmpDir / "testButtonBox.psyexp"
tmpPy = tmpDir / "testButtonBox.py"
exp.saveToXML(str(tmpExp), makeLegacy=False)
# write code
script = exp.writeScript(target="PsychoPy")
tmpPy.write_text(script, encoding="utf-8")
# assign ranges of code to cases by their Routine name
errRanges = {
0: None
}
for n, case in enumerate(cases):
i = script.find(
f"# --- Run Routine \"rt{n}\" ---"
)
errRanges[i] = case
# try to run
try:
subprocess.run(
args=[sys.executable, '-u', str(tmpPy)],
capture_output=True,
check=True,
)
except subprocess.CalledProcessError as err:
# if we get any errors, check their line number against error ranges
matches = re.findall(
pattern=r"testButtonBox.py\", line (\d*),",
string=err.stderr
)
# if no matches, raise error as is
if not matches:
raise err
# otherwise, get the last line number in the traceback
line = int(matches[-1])
# find matching case
lastCase = None
for start, case in errRanges.items():
if start <= line:
lastCase = case
else:
break
# construct new error with case details
msg = (
f"Error in Routine with following params:\n"
f"{lastCase}\n"
f"Original traceback:\n"
f"{err.stdout}"
)
raise ValueError(msg)
def fullCases():
"""
Generate an array covering a more complete set of values. Takes far too long to run for this
to be worth doing every time.
Returns
-------
list[dict]
List of case dicts for TestButtonBoxComponent.test_values
"""
# define some fields and possible values
fields = {
'forceEndRoutine': [True, False],
'store': [True, False],
'allowedButtons': [
[0, 1, 2],
"[0, 1, 2]",
],
'storeCorrect': [True, False],
'correctAns': [
0, 1, "0", "1"
],
'resps': [
[
ButtonResponse(t=0, value=True, channel=0),
ButtonResponse(t=0, value=False, channel=0),
],
[
ButtonResponse(t=0, value=True, channel=1),
ButtonResponse(t=0, value=False, channel=1),
],
[
ButtonResponse(t=0, value=True, channel=1),
],
[
ButtonResponse(t=0, value=True, channel=1),
],
],
}
# make keys and values into two lists
keys = list(fields.keys())
values = list(fields.values())
# iterate through all combinations of values
cases = []
for vals in itertools.product(*values):
# make a case
thisCase = {}
# populate with values from this iteration
for i, val in enumerate(vals):
thisCase[keys[i]] = val
# add case
cases.append(thisCase)
return cases
| 6,748
|
Python
|
.py
| 189
| 24.582011
| 98
| 0.540636
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,490
|
test_RoutineSettingsComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_RoutineSettingsComponent.py
|
import pytest
from pathlib import Path
from psychopy.experiment.components.routineSettings import RoutineSettingsComponent
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests
from psychopy.tests import utils
class TestRoutineSettingsComponent(BaseComponentTests):
comp = RoutineSettingsComponent
def test_disabled_code_muting(self):
"""
RoutineSettings doesn't work like a normal Component w/r/t disabling, so skip this test
"""
pytest.skip()
| 538
|
Python
|
.py
| 12
| 39.833333
| 98
| 0.799228
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,491
|
test_all_components.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_all_components.py
|
from psychopy.experiment.exports import IndentingBuffer
from . import BaseComponentTests
from psychopy import experiment
import inspect
class _Generic(BaseComponentTests):
def __init__(self, compClass):
self.exp = experiment.Experiment()
self.rt = experiment.routines.Routine(exp=self.exp, name="testRoutine")
self.exp.addRoutine("testRoutine", self.rt)
self.exp.flow.addRoutine(self.rt, 0)
self.comp = compClass(exp=self.exp, parentName="testRoutine", name=f"test{compClass.__name__}")
self.rt.addComponent(self.comp)
def test_all_components():
for compName, compClass in experiment.getAllComponents().items():
if compName == "SettingsComponent":
continue
# make a generic testing object for this component
tester = BaseComponentTests()
# make sure it has a comp class assigned
tester.comp = compClass
# Run each method from BaseComponentTests on tester
for attr, meth in BaseComponentTests.__dict__.items():
if inspect.ismethod(meth):
meth(tester)
def test_all_have_depth():
# Define components which shouldn't have depth
exceptions = ("PanoramaComponent",)
# Create experiment
exp = experiment.Experiment()
rt = experiment.routines.Routine(exp=exp, name="testRoutine")
exp.addRoutine("testRoutine", rt)
exp.flow.addRoutine(rt, 0)
# Add one of each component to the routine
for compName, compClass in experiment.getAllComponents().items():
# Settings components don't count so don't include one at all
if compName in ("SettingsComponent",):
continue
comp = compClass(exp=exp, parentName="testRoutine", name=f"test{compClass.__name__}")
rt.addComponent(comp)
# For each component...
for comp in rt:
compName = type(comp).__name__
# This won't be relevant for non-visual stimuli
if compName in exceptions or not isinstance(comp, experiment.components.BaseVisualComponent):
continue
for target in ("PsychoPy", "PsychoJS"):
# Skip if target isn't applicable
if target not in comp.targets:
continue
# Crate buffer to get component code
buff = IndentingBuffer(target=target)
# Write init code
if target == "PsychoJS":
comp.writeInitCodeJS(buff)
sought = "depth:"
else:
comp.writeInitCode(buff)
sought = "depth="
script = buff.getvalue()
# Unless excepted, check that depth is in the output
assert sought in script.replace(" ", ""), (
f"Could not find any reference to depth in {target} init code for {compName}:\n"
f"{script}\n"
f"Any component drawn to the screen should be given a `depth` on init. If this component is a special "
f"case, you can mark it as exempt by adding it to the `exceptions` variable in this test.\n"
)
def test_visual_set_autodraw():
"""
Check that any components derived from BaseVisualComponent make some reference to `.autoDraw` in their each
frame code
"""
# List of components to skip
skipComponents = ["ApertureComponent"]
for compName, compClass in experiment.getAllComponents().items():
# Skip component if marked to skip
if compName in skipComponents:
continue
# Skip if component isn't derived from BaseVisual
if not issubclass(compClass, experiment.components.BaseVisualComponent):
continue
# Make a generic testing object for this component
tester = _Generic(compClass).comp
if 'startVal' in tester.params:
tester.params['startVal'].val = 0
if 'stopVal' in tester.params:
tester.params['stopVal'].val = 1
# Create text buffer to write to
buff = IndentingBuffer(target="PsychoPy")
# Write each frame code
tester.writeFrameCode(buff)
code = buff.getvalue()
# Look for autoDraw refs
assert ".autoDraw = " in code or ".setAutoDraw(" in code, (
f"{compName} does not set autoDraw in its Each Frame code. If this is acceptable, add the component name "
f"to `skipComponents`."
)
| 4,403
|
Python
|
.py
| 96
| 36.572917
| 119
| 0.643871
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,492
|
test_PolygonComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_PolygonComponent.py
|
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests, _TestLibraryClassMixin
from psychopy.experiment.components.polygon import PolygonComponent
from psychopy.visual.polygon import Polygon
class TestPolygonComponent(BaseComponentTests, _TestLibraryClassMixin):
"""
Test that Polygon coponents have the correct params and write as expected.
"""
comp = PolygonComponent
libraryClass = Polygon
def test_vertices_usage(self):
"""
Test that vertices values are used only under the correct conditions
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# Define values to look for and avoid in code according to value of shape
cases = [
# Shape is a line
{'val': "line",
'seek': ["visual.Line("],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "triangle",
'seek': ["visual.ShapeStim("],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "rectangle",
'seek': ["visual.Rect("],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "circle",
'seek': ["visual.ShapeStim(", "vertices='circle'"],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "cross",
'seek': ["visual.ShapeStim(", "vertices='cross'"],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "star",
'seek': ["visual.ShapeStim(", "vertices='star7'"],
'avoid': ["___nVertices___", "___vertices___"]},
{'val': "regular polygon...",
'seek': ["___nVertices___", "visual.Polygon("],
'avoid': ["___vertices___"]},
{'val': "custom polygon...",
'seek': ["___vertices___", "visual.ShapeStim("],
'avoid': ["___nVertices___"]},
]
# Setup component with markers for nVertices and vertices
comp.params['nVertices'].val = "___nVertices___"
comp.params['vertices'].val = "___vertices___"
# Test each case
for case in cases:
# Set shape
comp.params['shape'].val = case['val']
# Write experiment
pyScript = exp.writeScript(target="PsychoPy")
# Look for sought values in experiment script
for seekVal in case['seek']:
assert seekVal in pyScript, (
f"Could not find wanted value `{seekVal}` in experiment when polygon shape was {case['val']}."
)
# Look for avoid values in experiment script
for avoidVal in case['avoid']:
assert avoidVal not in pyScript, (
f"Found unwanted value `{avoidVal}` in experiment when polygon shape was {case['val']}."
)
| 2,954
|
Python
|
.py
| 62
| 36.209677
| 122
| 0.539633
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,493
|
test_StaticComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_StaticComponent.py
|
from pathlib import Path
from . import BaseComponentTests
from .test_base_components import _find_global_resource_in_js_experiment
from psychopy.experiment.components.static import StaticComponent
from psychopy import experiment, data
from ...utils import TESTS_DATA_PATH
class TestStaticComponent(BaseComponentTests):
comp = StaticComponent
def test_handled_resources_removed(self):
"""
Check that resources handled by a static component are removed from the start of the experiment
"""
cases = [
# Resource handled by static component, no loop present
{'exp': "handledbystatic_noloop",
'seek': [],
'avoid': ['blue.png', 'white.png', 'yellow.png', 'groups.csv', 'groupA.csv', 'groupB.csv']},
# Resource handled by static component, loop defined by string
{'exp': "handledbystatic_strloop",
'seek': ['groupA.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png', 'groupB.csv', 'groups.csv']},
# Resource handled by static component, loop defined by constructed string
{'exp': "handledbystatic_constrloop",
'seek': ['groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png']},
# Resource handled by static component, loop defined by constructed string from loop
{'exp': "handledbystatic_recurloop",
'seek': ['groupA.csv', 'groupB.csv', 'groups.csv'],
'avoid': ['blue.png', 'white.png', 'yellow.png']},
]
exp = experiment.Experiment()
for case in cases:
# Load experiment
exp.loadFromXML(Path(TESTS_DATA_PATH) / "test_get_resources" / (case['exp'] + ".psyexp"))
# Write to JS
script = exp.writeScript(target="PsychoJS")
# Check that all "seek" phrases are included
for phrase in case['seek']:
assert _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was not found in resources for {case['exp']}.psyexp"
)
# Check that all "avoid" phrases are excluded
for phrase in case['avoid']:
assert not _find_global_resource_in_js_experiment(script, phrase), (
f"'{phrase}' was found in resources for {case['exp']}.psyexp"
)
| 2,434
|
Python
|
.py
| 46
| 41.73913
| 105
| 0.600671
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,494
|
test_base_components.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_base_components.py
|
import ast
import esprima
import re
from pathlib import Path
import esprima.error_handler
import pytest
import tempfile
from psychopy import experiment
from psychopy.experiment.loops import TrialHandler
from psychopy.experiment.components import BaseComponent
from psychopy.experiment.exports import IndentingBuffer
from psychopy.constants import FOREVER
from psychopy.tests import utils
def _find_global_resource_in_js_experiment(script, resource):
# If given multiple resources...
if isinstance(resource, (list, tuple)):
# Start off with a blank array
present = []
for res in resource:
# For each resource, run this function recursively and append the result
present.append(
_find_global_resource_in_js_experiment(script, res)
)
# Return array of bools
return present
# Extract resources def at start of experiment
resourcesStr = re.search("(?<=resources: \[)[^\]]*", script).group(0)
# Return bool for whether specified resource is present
return resource in resourcesStr
class BaseComponentTests:
# component class to test
comp = None
# --- Utility methods ---
def make_minimal_experiment(self):
"""
Make a minimal experiment with just one routine containing just one component, of the same class as the current component but with all default params.
"""
# make blank experiment
exp = experiment.Experiment()
exp.name = "Test" + self.comp.__name__ + "MinimalExp"
# add a Routine
rt = exp.addRoutine(routineName='TestRoutine')
exp.flow.addRoutine(rt, 0)
# add a loop around the Routine
loop = TrialHandler(exp=exp, name="testLoop")
exp.flow.addLoop(loop, 0, -1)
# create instance of this test's Component with all default params
comp = self.comp(exp=exp, parentName='TestRoutine', name=f"test{self.comp.__name__}")
rt.append(comp)
# return experiment, Routine and Component
return comp, rt, exp
@pytest.fixture(autouse=True)
def assert_comp_class(self):
"""
Make sure this test object has an associated Component class - and skip the test if not. This is run before each test by default.
"""
# skip whole test if there is no Component connected to test class
if self.comp is None:
pytest.skip()
# continue with the test as normal
yield
# --- Heritable tests ---
def test_syntax_errors(self):
"""
Create a basic implementation of this Component with everything set to defaults and check
whether the resulting code has syntax errors
"""
# create minimal experiment
comp, rt, exp = self.make_minimal_experiment()
# check syntax
utils.checkSyntax(exp, targets=self.comp.targets)
def test_icons(self):
"""
Check that Component has icons for each app theme and that these point to real files
"""
# pathify icon file path
icon = Path(self.comp.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(), (
f"Could not find file: {file}"
)
def test_indentation_consistency(self):
"""
No component should exit any of its write methods at a different indent level as it entered, as this would break subsequent components / routines.
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# skip if component doesn't have a start/stop time
if "startVal" not in comp.params or "stopVal" not in comp.params:
pytest.skip()
# create a text buffer to write to
buff = IndentingBuffer(target="PsychoPy")
# template message for if test fails
errMsgTemplate = "Writing {} code for {} changes indent level by {} when start is `{}` and stop is `{}`."
# setup flow for writing
exp.flow.writeStartCode(buff)
# combinations of start/stop being set/unset to try
cases = [
{"startVal": "0", "stopVal": "1"},
{"startVal": "", "stopVal": "1"},
{"startVal": "0", "stopVal": ""},
{"startVal": "", "stopVal": ""},
]
for case in cases:
# update error message for this case
errMsg = errMsgTemplate.format(
"{}", type(comp).__name__, "{}", case['startVal'], case['stopVal']
)
# set start/stop types
comp.params["startType"].val = "time (s)"
comp.params["stopType"].val = "time (s)"
# set start/stop values
for param, val in case.items():
comp.params[param].val = val
# write init code
comp.writeInitCode(buff)
# check indent
assert buff.indentLevel == 0, errMsg.format(
"init", buff.indentLevel
)
# write routine start code
comp.writeRoutineStartCode(buff)
# check indent
assert buff.indentLevel == 0, errMsg.format(
"routine start", buff.indentLevel
)
# write each frame code
comp.writeFrameCode(buff)
# check indent
assert buff.indentLevel == 0, errMsg.format(
"each frame", buff.indentLevel
)
# write end routine code
comp.writeRoutineEndCode(buff)
# check indent
assert buff.indentLevel == 0, errMsg.format(
"routine end", buff.indentLevel
)
# write end experiment code
comp.writeExperimentEndCode(buff)
# check indent
assert buff.indentLevel == 0, errMsg.format(
"experiment end", buff.indentLevel
)
def test_blank_timing(self):
"""
Check that this Component can handle blank start/stop values.
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# skip if Component doesn't have the relevant params (e.g. Code Component)
for key in ("startVal", "startType", "stopVal", "stopType"):
if key not in comp.params:
pytest.skip()
# StaticComponent has entirely bespoke start/stop tests so skip it here
if type(comp).__name__ == "StaticComponent":
pytest.skip()
# make sure start and stop are as times
comp.params['startType'].val = "time (s)"
comp.params['stopType'].val = "duration (s)"
# define cases and expected start/dur
cases = [
# blank start
{'name': "NoStart", 'startVal': "", 'stopVal': "1", 'startTime': None, 'duration': 1},
# blank stop
{'name': "NoStop", 'startVal': "0", 'stopVal': "", 'startTime': 0, 'duration': FOREVER},
# blank both
{'name': "NoStartStop", 'startVal': "", 'stopVal': "", 'startTime': None, 'duration': FOREVER},
]
# run all cases
for case in cases:
# apply values from case
comp.params['startVal'].val = case['startVal']
comp.params['stopVal'].val = case['stopVal']
# get values from start and duration method
startTime, duration, nonSlipSafe = comp.getStartAndDuration()
# check against expected
assert startTime == case['startTime']
assert duration == case['duration']
# check that it's never non-slip safe
assert not nonSlipSafe
# update experiment name to indicate what case we're in
case['name'] = self.comp.__name__ + case['name']
exp.name = "Test%(name)sExp" % case
# check that it still writes syntactially valid code
try:
utils.checkSyntax(exp, targets=self.comp.targets)
except SyntaxError as err:
# raise error
case['err'] = err
raise AssertionError(
"Syntax error in compiled Builder code when startVal was '%(startVal)s' and "
"stopVal was '%(stopVal)s'. Failed script saved in psychopy/tests/fails. "
"Original error: %(err)s" % case
)
def test_disabled_default_val(self):
"""
Test that components created with default params are not disabled
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# check whether it can be disabled
assert 'disabled' in comp.params, (
f"{type(comp).__name__} does not have a 'disabled' attribute."
)
# check that disabled defaults to False
assert comp.params['disabled'].val is False, f"{type(comp).__name__} is defaulting to disabled."
def test_disabled_code_muting(self):
"""
Test that components are only written when enabled and targets match.
"""
# Code Component is never referenced by name, so skip it for this test
if self.comp.__name__ == "CodeComponent":
pytest.skip()
# Make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# Write experiment and check that component is written
pyScript = exp.writeScript(target="PsychoPy")
if "PsychoPy" in type(comp).targets:
assert comp.name in pyScript, (
f"{type(comp).__name__} not found in compiled Python script when enabled and PsychoPy in targets."
)
else:
assert comp.name not in pyScript, (
f"{type(comp).__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(comp).targets:
# assert comp.name in jsScript, (
# f"{type(comp).__name__} not found in compiled Python script when enabled and PsychoJS in targets."
# )
# else:
# assert comp.name not in jsScript, (
# f"{type(comp).__name__} found in compiled Python script when enabled but PsychoJS not in targets."
# )
# disable component then do same tests but assert not present
comp.params['disabled'].val = True
pyScript = exp.writeScript(target="PsychoPy")
if "PsychoPy" in type(comp).targets:
assert comp.name not in pyScript, (
f"{type(comp).__name__} found in compiled Python script when disabled but PsychoPy in targets."
)
else:
assert comp.name not in pyScript, (
f"{type(comp).__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(comp).targets:
# assert comp.name not in jsScript, (
# f"{type(comp).__name__} found in compiled Python script when disabled but PsychoJS in targets."
# )
# else:
# assert comp.name not in jsScript, (
# f"{type(comp).__name__} found in compiled Python script when disabled and PsychoJS not in targets."
# )
def test_disabled_components_stay_in_routine(self):
"""
Test that disabled components aren't removed from their routine when experiment is written.
"""
comp, rt, exp = self.make_minimal_experiment()
# Disable component
comp.params['disabled'].val = True
# Writing the script drops the component but, if working properly, only from a copy of the routine, not the
# original!
exp.writeScript()
assert comp in rt, f"Disabling {type(comp).name} appears to remove it from its routine on compile."
class _TestLibraryClassMixin:
# class in the PsychoPy libraries (visual, sound, hardware, etc.) corresponding to this component
libraryClass = None
# --- Utility methods ---
@pytest.fixture(autouse=True)
def assert_lib_class(self):
"""
Make sure this test object has an associated library class - and skip the test if not. This is run before each test by default.
"""
# skip whole test if there is no Component connected to test class
if self.libraryClass is None:
pytest.skip()
# continue with the test as normal
yield
# --- Heritable tests ---
def test_device_class_refs(self):
"""
Check that any references to device classes in this Routine object point to classes which
exist.
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# skip test if this element doesn't point to any hardware class
if not hasattr(comp, "deviceClasses"):
pytest.skip()
return
# get device manager
from psychopy.hardware import DeviceManager
# iterate through device classes
for deviceClass in comp.deviceClasses:
# resolve any aliases
deviceClass = DeviceManager._resolveAlias(deviceClass)
# try to import class
DeviceManager._resolveClassString(deviceClass)
def test_params_used(self):
# Make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# Try with PsychoPy and PsychoJS
for target in ("PsychoPy", "PsychoJS"):
## Skip PsychoJS until can write script without saving
if target == "PsychoJS":
continue
# Skip if not valid for this target
if target not in comp.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 paramName, param in experiment.getInitVals(comp.params, target).items():
# Conditions to skip...
if not param.direct:
# Marked as not direct
continue
if any(paramName in depend['param'] for depend in comp.depends):
# Dependent on another param
continue
if param.val in [
"from exp settings", "win.units", # units and color space, aliased
'default', # most of the time will be aliased
]:
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(comp).__name__} not found in {target} script."
)
def test_param_settable(self):
"""
Check that all params which are settable each frame/repeat have a set method in the corresponding class.
"""
# Make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# Check each param
for paramName, param in comp.params.items():
if not param.direct:
# Skip if param is not directly used
continue
if param.allowedUpdates is None:
# Skip if no allowed updates
continue
# Check whether param is settable each frame/repeat
settable = {
"repeat": "set every repeat" in param.allowedUpdates,
"frame": "set every frame" in param.allowedUpdates
}
if any(settable.values()):
# Get string for settable type
settableList = []
for key in settable:
if settable[key]:
settableList.append(f"every {key}")
settableStr = " or ".join(settableList)
# Work out what method name should be
methodName = "set" + BaseComponent._getParamCaps(comp, paramName)
# If settable, check for a set method in library class
assert hasattr(self.libraryClass, methodName), (
f"Parameter {paramName} can be set {settableStr}, but does not have a method {methodName}"
)
class _TestDepthMixin:
def test_depth(self):
# Make minimal experiment
comp, rt, exp = self.make_minimal_experiment()
# Get class we're currently working with
compClass = type(comp)
# Add index to component name
baseCompName = comp.name
comp.name = baseCompName + str(0)
# Add more components
for i in range(3):
comp = compClass(exp=exp, parentName='TestRoutine', name=baseCompName + str(i + 1))
rt.append(comp)
# Do test for Py
script = exp.writeScript(target="PsychoPy")
# Parse script to get each object def as a node
tree = ast.parse(script)
for node in tree.body:
# If current node is an assignment, investigate
if isinstance(node, ast.Assign):
# Get name
name = node.targets[0]
if isinstance(name, ast.Name):
# If name matches component names, look for depth keyword
if baseCompName in name.id:
for key in node.value.keywords:
if key.arg == "depth":
if isinstance(key.value, ast.Constant):
# If depth is positive, get value as is
depth = int(key.value.value)
elif isinstance(key.value, ast.UnaryOp):
# If depth is negative, get value*-1
depth = int(key.value.operand.value)
else:
# If it's anything else, something is wrong
raise TypeError(
f"Expected depth value in script to be a number, instead it is {type(key.value)}")
# Make sure depth matches what we expect
assert baseCompName + str(depth) == name.id, (
"Depth of {compClass} did not match expected: {name.id} should have a depth "
"matching the value in its name * -1, instead had depth of -{depth}."
)
# Do test for JS
script = exp.writeScript(target="PsychoJS")
# Parse JS script
tree = esprima.tokenize(script) # ideally we'd use esprima.parseScript, but this throws an error with PsychoJS scripts
inInit = False
thisCompName = ""
for i, node in enumerate(tree):
# Detect start of inits
if node.type == "Identifier" and baseCompName in node.value:
inInit = True
thisCompName = node.value
# Detect end of inits
if node.type == "Punctuator" and node.value == "}":
inInit = False
thisCompName = ""
if inInit:
# If we're in the init, detect start of param
if node.type == "Identifier" and node.value == "depth":
# 2 nodes ahead of param start will be param value...
depth = tree[i+2].value
if depth == "-":
# ...unless negative, in which case the value is 3 nodes ahead
depth = tree[i+3].value
depth = int(float(depth))
# Make sure depth matches what we expect
assert baseCompName + str(depth) == thisCompName, (
"Depth of {compClass} did not match expected: {thisCompName} should have a depth "
"matching the value in its name * -1, instead had depth of -{depth}."
)
| 20,924
|
Python
|
.py
| 446
| 34.632287
| 158
| 0.574974
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,495
|
test_ImageComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_ImageComponent.py
|
from psychopy.experiment.components.image import ImageComponent
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests, _TestDepthMixin, _TestLibraryClassMixin
from psychopy.visual.image import ImageStim
class TestImage(BaseComponentTests, _TestLibraryClassMixin):
comp = ImageComponent
libraryClass = ImageStim
| 366
|
Python
|
.py
| 6
| 58.333333
| 139
| 0.863128
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,496
|
test_KeyboardComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_KeyboardComponent.py
|
from pathlib import Path
from psychopy.experiment.components.keyboard import KeyboardComponent
from psychopy.hardware.keyboard import Keyboard, KeyboardDevice
from psychopy.tests import utils
from psychopy.tests.test_experiment.test_components import BaseComponentTests
from psychopy import session
class TestKeyboardComponent(BaseComponentTests):
comp = KeyboardComponent
libraryClass = Keyboard
def setup_class(self):
# make a Session
self.session = session.Session(
root=Path(utils.TESTS_DATA_PATH) / "test_components",
)
# setup default window
self.session.setupWindowFromParams({})
def testKeyboardClear(self):
"""
Test that KeyPress responses are cleared at the start of each Routine
"""
# add keyboard clear experiment
self.session.addExperiment("testClearKeyboard/testClearKeyboard.psyexp", "keyboardClear")
# run keyboard clear experiment (will error if assertion not met)
self.session.runExperiment("keyboardClear")
| 1,054
|
Python
|
.py
| 24
| 37.583333
| 97
| 0.745614
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,497
|
test_MouseComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_MouseComponent.py
|
from pathlib import Path
from . import BaseComponentTests
from psychopy.experiment.loops import TrialHandler
from psychopy.experiment.components.mouse import MouseComponent
from psychopy.experiment.components.polygon import PolygonComponent
from psychopy.tests.utils import TESTS_DATA_PATH
from psychopy.hardware.mouse import Mouse
class TestMouseComponent(BaseComponentTests):
"""
Test that Mouse coponents have the correct params and write as expected.
"""
comp = MouseComponent
libraryClass = Mouse
def test_click_save_end_clickable_cases(self):
"""
Test all combinations of options for what to save, what can be clicked on & what kind of clicks to end the
routine on.
"""
# make minimal experiment just for this test
comp, rt, exp = self.make_minimal_experiment()
# make a rect for when we need something to click on
target = PolygonComponent(exp=exp, parentName=rt.name, name="testPolygon")
saveMouseStateCases = [
{'val': "final",
'want': [f"thisExp.addData('{comp.name}.x', x)"], # should contain code for adding final value of x
'avoid': [f"{comp.name}.x.append(x)"]}, # should not contain code to update testMouse.x in frame loop
{'val': "on click",
'want': [f"thisExp.addData('{comp.name}.x', {comp.name}.x)", # should add testMouse.x at the end
f"{comp.name}.x.append(x)"], # should contain code to update testMouse.x in frame loop
'avoid': [f"thisExp.addData('{comp.name}.x', x)"]}, # should not add final value of x
{'val': "on valid click",
'want': [f"thisExp.addData('{comp.name}.x', {comp.name}.x)", # should add testMouse.x at the end
f"{comp.name}.x.append(x)", # should contain code to update testMouse.x in frame loop
"if gotValidClick:"], # should check for valid clicks
'avoid': [f"thisExp.addData('{comp.name}.x', x)"]}, # should not add final value of x
{'val': "every frame",
'want': [f"thisExp.addData('{comp.name}.x', {comp.name}.x)", # should add testMouse.x at the end
f"{comp.name}.x.append(x)"], # should contain code to update testMouse.x in frame loop
'avoid': [f"thisExp.addData('{comp.name}.x', x)"]}, # should not add final value of x
{'val': "never",
'want': [],
'avoid': [f"thisExp.addData('{comp.name}.x', {comp.name}.x)", # should not add testMouse.x at the end
f"{comp.name}.x.append(x)", # should not contain code to update testMouse.x in frame loop
f"thisExp.addData('{comp.name}.x', x)"]}, # should not add final value of x]},
]
forceEndRoutineOnPressCases = [
{'val': "never",
'want': [],
'avoid': ["# end routine on response", # should not include code to end routine
"# end routine on response"]},
{'val': "any click",
'want': ["# end routine on response"], # should include code to end routine on response
'avoid': []},
{'val': "valid click",
'want': ["# end routine on response", # should include code to end routine on response
"if gotValidClick:"], # should check for valid clicks
'avoid': []},
]
clickableCases = [
{'val': "[]",
'want': [],
'avoid': ["clickableList = [testPolygon]"]}, # should not define a populated clickables list
{'val': "[testPolygon]",
'want': [],
'avoid': ["clickableList = []"]}, # should not define a blank clickables list
]
# Iterate through saveMouseState cases
for SMScase in saveMouseStateCases:
# Set saveMouseState
comp.params['saveMouseState'].val = SMScase['val']
for FEROPcase in forceEndRoutineOnPressCases:
# Set forceEndRoutineOnPress
comp.params['forceEndRoutineOnPress'].val = FEROPcase['val']
for Ccase in clickableCases:
# Set clickable
comp.params['clickable'].val = Ccase['val']
# Compile script
script = exp.writeScript(target="PsychoPy")
try:
# Look for wanted phrases
for phrase in SMScase['want']:
assert phrase in script, (
f"{phrase} not found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
for phrase in FEROPcase['want']:
assert phrase in script, (
f"{phrase} not found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
for phrase in Ccase['want']:
assert phrase in script, (
f"{phrase} not found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
# Check there's no avoid phrases
for phrase in SMScase['avoid']:
assert phrase not in script, (
f"{phrase} found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
for phrase in FEROPcase['avoid']:
assert phrase not in script, (
f"{phrase} found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
for phrase in Ccase['avoid']:
assert phrase not in script, (
f"{phrase} found in script when saveMouseState={comp.params['saveMouseState']}, "
f"forceEndRoutineOnPress={comp.params['forceEndRoutineOnPress']} and "
f"clickable={comp.params['clickable']}"
)
except AssertionError as err:
# If any assertion fails, save script to view
filename = Path(TESTS_DATA_PATH) / f"{__class__.__name__}_clicks_cases_local.py"
with open(filename, "w") as f:
f.write(script)
# Append ref to saved script in error message
print(
f"\n"
f"Case: {SMScase} {FEROPcase} {Ccase}\n"
f"Script saved at: {filename}\n"
)
# Raise original error
raise err
| 7,876
|
Python
|
.py
| 130
| 41.607692
| 117
| 0.518365
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,498
|
test_UnknownPluginComponent.py
|
psychopy_psychopy/psychopy/tests/test_experiment/test_components/test_UnknownPluginComponent.py
|
from psychopy.tests.test_experiment.test_components.test_base_components import BaseComponentTests
from psychopy.experiment.components.unknownPlugin import UnknownPluginComponent
from psychopy.experiment import Experiment
from psychopy.tests import utils
from pathlib import Path
class TestUnknownPluginComponent(BaseComponentTests):
comp = UnknownPluginComponent
def test_load_resave(self):
"""
Test that loading an experiment with an unrecognised plugin Component retains the original
name and source plugin for that Component.
"""
# load experiment from file which has an unrecognised plugin component in
testExp = Path(utils.TESTS_DATA_PATH) / "TestUnknownPluginComponent_load_resave.psyexp"
exp = Experiment.fromFile(testExp)
# get unrecognised component
comp = exp.routines['trial'][-1]
# check its type and plugin values
assert comp.type == "TestFromPluginComponent"
assert comp.plugin == "psychopy-plugin-which-doesnt-exist"
# get its xml
xml = comp._xml
# check its tag and plugin attribute are retained
assert xml.tag == "TestFromPluginComponent"
assert comp.plugin == "psychopy-plugin-which-doesnt-exist"
| 1,267
|
Python
|
.py
| 25
| 43.64
| 99
| 0.737055
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|
5,499
|
genComponsTemplate.py
|
psychopy_psychopy/psychopy/tests/test_experiment/needs_wx/genComponsTemplate.py
|
import sys
import os
import io
from packaging.version import Version
import wx
if Version(wx.__version__) < Version('2.9'):
tmpApp = wx.PySimpleApp()
else:
tmpApp = wx.App(False)
from psychopy import experiment
from psychopy.experiment.components import getAllComponents
# usage: generate or compare all Component.param settings & options
# motivation: catch deviations introduced during refactoring
# use --out to re-generate componsTemplate.txt
# ignore attributes that are there because inherit from object
ignoreObjectAttribs = True
# should not need a wx.App with fetchIcons=False
try:
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
allComp = getAllComponents(fetchIcons=False)
exp = experiment.Experiment()
relPath = os.path.join(os.path.split(__file__)[0], 'componsTemplate.txt')
if not '--out' in sys.argv:
with io.open(relPath, 'r', encoding='utf-8-sig') 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
else:
outfile = open(relPath,'w')
param = experiment.Param('', '') # want its namespace
ignore = ['__doc__', '__init__', '__module__', '__str__', 'next']
if '--out' not in sys.argv:
# these are for display only (cosmetic) but no harm in gathering initially:
ignore += ['hint',
'label', # comment-out to not ignore labels when checking
'categ'
]
for field in dir(param):
if field.startswith("__"):
ignore.append(field)
fields = set(dir(param)).difference(ignore)
mismatches = []
for compName in sorted(allComp):
comp = allComp[compName](parentName='x', exp=exp)
order = '%s.order:%s' % (compName, eval("comp.order"))
out = [order]
if '--out' in sys.argv:
outfile.write(order+'\n')
elif not order+'\n' in target:
tag = order.split(':', 1)[0]
try:
err = order + ' <== ' + targetTag[tag]
except IndexError: # missing
err = order + ' <==> NEW (no matching param in original)'
print(err)
mismatches.append(err)
for parName in sorted(comp.params):
# default is what you get from param.__str__, which returns its value
default = '%s.%s.default:%s' % (compName, parName, comp.params[parName])
out.append(default)
lineFields = []
for field in sorted(fields):
if parName == 'name' and field == 'updates':
continue
# ignore: never want to change the name *during an experiment*
# the default name.updates value varies across components
# skip private attributes
if field.startswith("_"):
continue
# get value of the field
fieldValue = str(eval("comp.params[parName].%s" % field))
# remove memory address from the string representation
if "at 0x" in fieldValue:
fieldValue = fieldValue.split(" at 0x")[0] + ">"
f = '%s.%s.%s:%s' % (compName, parName, field, fieldValue)
lineFields.append(f)
for line in [default] + lineFields:
if '--out' in sys.argv:
if not ignoreObjectAttribs:
outfile.write(line+'\n')
else:
if (not ":<built-in method __" in line and
not ":<method-wrapper '__" in line and
not ":<bound method " in line):
outfile.write(line+'\n')
elif not line+'\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:
err = line + ' <== ' + targetTag[tag]
except KeyError: # missing
err = line + ' <==> NEW (no matching param in original)'
print(err)
mismatches.append(err)
# return mismatches
| 4,676
|
Python
|
.py
| 115
| 31.556522
| 80
| 0.58623
|
psychopy/psychopy
| 1,662
| 900
| 218
|
GPL-3.0
|
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
|