How to use the psychopy.logging.error function in psychopy

To help you get started, we’ve selected a few psychopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github psychopy / psychopy / psychopy / visual / ratingscale.py View on Github external
if len(list(self.acceptKeys)) == 0:
                # make sure there is in fact a way to respond using a
                # key-press:
                self.acceptKeys = ['return']
            if self.mouseOnly and not self.singleClick:
                # then there's no way to respond, so deny mouseOnly / enable
                # using keys:
                self.mouseOnly = False
                msg = ("RatingScale %s: ignoring mouseOnly (because "
                       "showAccept and singleClick are False)")
                logging.warning(msg % self.name)

        # 'choices' is a list of non-numeric (unordered) alternatives:
        if choices and len(list(choices)) < 2:
            msg = "RatingScale %s: choices requires 2 or more items"
            logging.error(msg % self.name)
        if choices and len(list(choices)) >= 2:
            low = 0
            high = len(list(choices)) - 1
            self.precision = 1  # a fractional choice makes no sense
            self.choices = choices
            self.labelTexts = choices
        else:
            self.choices = False
        if marker == 'hover' and not self.choices:
            logging.error("RatingScale: marker='hover' requires "
                          "a set of choices.")
            core.quit()

        # Anchors need to be well-behaved [do after choices]:
        try:
            self.low = int(low)
github psychopy / psychopy / psychopy / event.py View on Github external
win=None):
        super(Mouse, self).__init__()
        self.visible = visible
        self.lastPos = None
        self.prevPos = None  # used for motion detection and timing
        if win:
            self.win = win
        else:
            try:
                # to avoid circular imports, core.openWindows is defined
                # by visual.py and updated in core namespace;
                # it's circular to "import visual" here in event
                self.win = psychopy.core.openWindows[0]()
                logging.info('Mouse: using default window')
            except (NameError, IndexError):
                logging.error('Mouse: failed to get a default visual.Window'
                              ' (need to create one first)')
                self.win = None
        # for builder: set status to STARTED, NOT_STARTED etc
        self.status = None
        self.mouseClock = psychopy.core.Clock()
        self.movedistance = 0.0
        # if pygame isn't initialised then we must use pyglet
        global usePygame
        if havePygame and not pygame.display.get_init():
            usePygame = False
        if not usePygame:
            global mouseButtons
            mouseButtons = [0, 0, 0]
        self.setVisible(visible)
        if newPos is not None:
            self.setPos(newPos)
github psychopy / psychopy / psychopy / hardware / joystick / __init__.py View on Github external
joys = []
            for joy in range(glfw.JOYSTICK_1, glfw.JOYSTICK_LAST):
                if glfw.joystick_present(joy):
                    joys.append(joy)

            # error checks
            if not joys:  # if the list is empty, no joysticks were found
                error_msg = ("No joysticks were found by the GLFW runtime. "
                             "Check connections and try again.")
                logging.error(error_msg)
                raise RuntimeError(error_msg)
            elif id not in joys:
                error_msg = ("You don't have that many joysticks attached "
                             "(remember that the first joystick has id=0 "
                             "etc...)")
                logging.error(error_msg)
                raise RuntimeError(error_msg)

            self._device = id  # just need the ID for GLFW
            self.name = glfw.get_joystick_name(self._device).decode("utf-8")

            if len(visual.openWindows) == 0:
                logging.error(
                    "You need to open a window before creating your joystick")
            else:
                for win in visual.openWindows:
                    # sending the raw ID to the window.
                    win()._eventDispatchers.append(self._device)

        else:
            pygame.joystick.init()
            self._device = pygame.joystick.Joystick(id)
github psychopy / psychopy / psychopy / visual / basevisual.py View on Github external
try:
                    im = Image.open(filename)
                    im = im.transpose(Image.FLIP_TOP_BOTTOM)
                except IOError:
                    msg = "Found file '%s', failed to load as an image"
                    logging.error(msg % (filename))
                    logging.flush()
                    msg = "Found file '%s' [= %s], failed to load as an image"
                    raise IOError(msg % (tex, os.path.abspath(tex)))
            else:
                # can't be a file; maybe its an image already in memory?
                try:
                    im = tex.copy().transpose(Image.FLIP_TOP_BOTTOM)
                except AttributeError:  # nope, not an image in memory
                    msg = "Couldn't make sense of requested image."
                    logging.error(msg)
                    logging.flush()
                    raise AttributeError(msg)
            # at this point we have a valid im
            stim._origSize = im.size
            wasImage = True
            # is it 1D?
            if im.size[0] == 1 or im.size[1] == 1:
                logging.error("Only 2D textures are supported at the moment")
            else:
                maxDim = max(im.size)
                powerOf2 = int(2**numpy.ceil(numpy.log2(maxDim)))
                if im.size[0] != powerOf2 or im.size[1] != powerOf2:
                    if not forcePOW2:
                        notSqr = True
                    elif globalVars.nImageResizes < reportNImageResizes:
                        msg = ("Image '%s' was not a square power-of-two ' "
github psychopy / psychopy / psychopy / visual / helpers.py View on Github external
else:  # OK to update current color
        if colorSpace == 'named':
            # operations don't make sense for named
            obj.__dict__[colorAttrib] = color
        else:
            setAttribute(obj, colorAttrib, color, log=False,
                         operation=operation, stealth=True)
    # get window (for color conversions)
    if colorSpace in ['dkl', 'lms']:  # only needed for these spaces
        if hasattr(obj, 'dkl_rgb'):
            win = obj  # obj is probably a Window
        elif hasattr(obj, 'win'):
            win = obj.win  # obj is probably a Stimulus
        else:
            win = None
            logging.error("_setColor() is being applied to something"
                          " that has no known Window object")
    # convert new obj.color to rgb space
    newColor = getattr(obj, colorAttrib)
    if colorSpace in ['rgb', 'rgb255']:
        setattr(obj, rgbAttrib, newColor)
    elif colorSpace == 'dkl':
        if (win.dkl_rgb is None or
                np.all(win.dkl_rgb == np.ones([3, 3]))):
            dkl_rgb = None
        else:
            dkl_rgb = win.dkl_rgb
        setattr(obj, rgbAttrib, colors.dkl2rgb(
            np.asarray(newColor).transpose(), dkl_rgb))
    elif colorSpace == 'lms':
        if (win.lms_rgb is None or
                np.all(win.lms_rgb == np.ones([3, 3]))):
github psychopy / psychopy / psychopy / sound / backend_pysound.py View on Github external
def _setSndFromFile(self, fileName):
        # load the file
        if not path.isfile(fileName):
            msg = "Sound file %s could not be found." % fileName
            logging.error(msg)
            raise ValueError(msg)
        self.fileName = fileName
        # in case a tone with inf loops had been used before
        self.loops = self.requestedLoops
        try:
            self.sndFile = sndfile.SoundFile(fileName)
            sndArr = self.sndFile.read()
            self.sndFile.close()
            self._setSndFromArray(sndArr)

        except Exception:
            msg = "Sound file %s could not be opened using pysoundcard for sound."
            logging.error(msg % fileName)
            raise ValueError(msg % fileName)
github psychopy / psychopy / psychopy / sound / backend_pygame.py View on Github external
def _setSndFromFile(self, fileName):
        # load the file
        if not path.isfile(fileName):
            msg = "Sound file %s could not be found." % fileName
            logging.error(msg)
            raise ValueError(msg)
        self.fileName = fileName
        # in case a tone with inf loops had been used before
        self.loops = self.requestedLoops
        try:
            self._snd = mixer.Sound(self.fileName)
        except Exception:
            msg = "Sound file %s could not be opened using pygame for sound."
            logging.error(msg % fileName)
            raise ValueError(msg % fileName)
github psychopy / psychopy / psychopy / hardware / iolabs.py View on Github external
"""
# Part of the PsychoPy library
# Copyright (C) 2013 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from numpy import ubyte
from psychopy import core, logging
try:
    import ioLabs
except:
    msg="""Failed to import the ioLabs library. If you're using your own copy of
        python (not the Standalone distribution of PsychoPy) then try installing it with:
           > pip install ioLabs
        """.replace('    ', '')
    logging.error(msg)


class BBox(ioLabs.USBBox):
    """Simplified interface to ioLabs.USBBox.

    Author: Jonathan Roberts
    PsychoPy integration (voice key untested): Jeremy Gray
    """
    def __init__(self):
        ioLabs.USBBox.__init__(self)

        #disable all buttons and lights
        self.buttons.enabled = 0x00  # 8 bit pattern 0=disabled 1=enabled
        self.port2.state = 0xFF  # port2 is the lights on the bbox - 8 bit pattern 0=on 1=off
        self.keyevents = []
github psychopy / psychopy / psychopy / sound / __init__.py View on Github external
# Set the device according to user prefs (if current lib allows it)
if hasattr(backend, 'defaultOutput'):
    pref = prefs.hardware['audioDevice']
    # is it a list or a simple string?
    if type(prefs.hardware['audioDevice'])==list:
        # multiple options so use zeroth
        dev = prefs.hardware['audioDevice'][0]
    else:
        # a single option
        dev = prefs.hardware['audioDevice']
    # is it simply "default" (do nothing)
    if dev=='default' or travisCI:
        pass  # do nothing
    elif dev not in backend.getDevices(kind='output'):
        devNames = sorted(backend.getDevices(kind='output').keys())
        logging.error(u"Requested audio device '{}' that is not available on "
                        "this hardware. The 'audioDevice' preference should be one of "
                        "{}".format(dev, devNames))
    else:
        setDevice(dev, kind='output')
github psychopy / psychopy / psychopy / sound / backend_pyo.py View on Github external
def _setSndFromFile(self, fileName):
        # want mono sound file played to both speakers, not just left / 0
        self.fileName = fileName
        self._sndTable = pyo.SndTable(initchnls=self.channels)
        # in case a tone with inf loops had been used before
        self.loops = self.requestedLoops
        # mono file loaded to all chnls:
        try:
            self._sndTable.setSound(self.fileName,
                                    start=self.startTime, stop=self.stopTime)
        except Exception:
            msg = (u'Could not open sound file `%s` using pyo; not found '
                   'or format not supported.')
            logging.error(msg % fileName)
            raise TypeError(msg % fileName)
        self._updateSnd()
        self.duration = self._sndTable.getDur()