How to use the psychopy.logging 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 / demos / coder / timing / timeByFramesEx.py View on Github external
# logging.console.setLevel(logging.INFO)  # uncomment to print log every frame

fliptimes = numpy.zeros(nIntervals + 1)

win.recordFrameIntervals = True
for frameN in range(nIntervals + 1):
    progBar.setSize([2.0 * frameN / nIntervals, 0.05])
    progBar.draw()
    myStim.setPhase(0.1, '+')
    myStim.setOri(1, '+')
    myStim.draw()
    if event.getKeys():
        print('stopped early')
        break
    win.logOnFlip(msg='frame=%i' % frameN, level=logging.EXP)
    fliptimes[frameN] = win.flip()

if disable_gc:
    gc.enable()
core.rush(False)

win.close()

# calculate some values
intervalsMS = pylab.array(win.frameIntervals) * 1000
m = pylab.mean(intervalsMS)
sd = pylab.std(intervalsMS)
# se=sd/pylab.sqrt(len(intervalsMS)) # for CI of the mean

nTotal = len(intervalsMS)
nDropped = sum(intervalsMS > (1.5 * m))
github psychopy / psychopy / psychopy / tools / attributetools.py View on Github external
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:
        if value is None:
            value = getattr(obj, attrib)

        # Log on next flip
        message = "%s: %s = %s" % (obj.name, attrib, value.__repr__())
        try:
            obj.win.logOnFlip(message, level=logging.EXP, obj=obj)
        except AttributeError:
            # this is probably a Window, having no "win" attribute
            logging.log(message, level=logging.EXP, obj=obj)
github psychopy / psychopy / psychopy / data / utils.py View on Github external
def _attemptImport(fileName, sep=',', dec='.'):
        """Attempts to import file with specified settings and raises
        ConditionsImportError if fails due to invalid format

        :param filename: str
        :param sep: str indicating the separator for cells (',', ';' etc)
        :param dec: str indicating the decimal point ('.', '.')
        :return: trialList, fieldNames
        """
        if fileName.endswith(('.csv', '.tsv')):
            trialsArr = pd.read_csv(fileName, encoding='utf-8-sig',
                                    sep=sep, decimal=dec)
            logging.debug(u"Read csv file with pandas: {}".format(fileName))
        elif fileName.endswith(('.xlsx', '.xls', '.xlsm')):
            trialsArr = pd.read_excel(fileName)
            logging.debug(u"Read Excel file with pandas: {}".format(fileName))
        # then try to convert array to trialList and fieldnames
        unnamed = trialsArr.columns.to_series().str.contains('^Unnamed: ')
        trialsArr = trialsArr.loc[:, ~unnamed]  # clear unnamed cols
        logging.debug(u"Clearing unnamed columns from {}".format(fileName))
        trialList, fieldNames = pandasToDictList(trialsArr)

        return trialList, fieldNames
github psychopy / psychopy / psychopy / sound / __init__.py View on Github external
elif thisLibName == 'pygame':
            from . import backend_pygame as backend
            Sound = backend.SoundPygame
        elif thisLibName == 'pysoundcard':
            from . import backend_pysound as backend
            Sound = backend.SoundPySoundCard
        else:
            msg = ("audioLib pref should be one of {!r}, not {!r}"
                   .format(_audioLibs, thisLibName))
            raise ValueError(msg)
        # if we got this far we were successful in loading the lib
        audioLib = thisLibName
        init = backend.init
        if hasattr(backend, 'getDevices'):
            getDevices = backend.getDevices
        logging.info('sound is using audioLib: %s' % audioLib)
        break
    except exceptions.DependencyError:
        msg = '%s audio lib was requested but not loaded: %s'
        logging.warning(msg % (thisLibName, sys.exc_info()[1]))
        continue  # to try next audio lib

if audioLib is None:
    raise exceptions.DependencyError(
            "No sound libs could be loaded. Tried: {}\n"
            "Check whether the necessary sound libs are installed"
            .format(prefs.hardware['audioLib']))
elif audioLib.lower() is not 'ptb':
    if constants.PY3 and not bits32:  # Could be running PTB, just aren't?
        logging.warning("We strongly recommend you activate the PTB sound "
                        "engine in PsychoPy prefs as the preferred audio "
                        "engine. Its timing is vastly superior. Your prefs "
github psychopy / psychopy / psychopy / monitors / calibTools.py View on Github external
# make sure that all necessary settings have some value
        super(Monitor, self).__init__()
        self.__type__ = 'psychoMonitor'
        self.name = name
        self.autoLog = autoLog
        self.currentCalib = currentCalib or {}
        self.currentCalibName = strFromDate(time.mktime(time.localtime()))
        self.calibs = {}
        self.calibNames = []
        self._gammaInterpolator = None
        self._gammaInterpolator2 = None
        self._loadAll()
        if len(self.calibNames) > 0:
            self.setCurrent(-1)  # will fetch previous vals if monitor exists
            if self.autoLog:
                logging.info('Loaded monitor calibration from %s' %
                             self.calibNames)
        else:
            self.newCalib()
            logging.warning("Monitor specification not found. "
                            "Creating a temporary one...")

        # overide current monitor settings with the vals given
        if width:
            self.setWidth(width)
        if distance:
            self.setDistance(distance)
        if gamma:
            self.setGamma(gamma)
        if notes:
            self.setNotes(notes)
        if useBits != None:
github psychopy / psychopy / psychopy / visual / rift.py View on Github external
ovr.capi.setRenderSwapChain(ovr.capi.ovrEye_Right, None)

        # Use MSAA if more than one sample is specified. If enabled, a render
        # buffer will be created.
        #
        max_samples = GL.GLint()
        GL.glGetIntegerv(GL.GL_MAX_SAMPLES, max_samples)
        if isinstance(self._samples, int):
            if (self._samples & (self._samples - 1)) != 0:
                # power of two?
                logging.warning(
                    'Invalid number of MSAA samples provided, must be '
                    'power of two. Disabling.')
            elif 0 > self._samples > max_samples.value:
                # check if within range
                logging.warning(
                    'Invalid number of MSAA samples provided, outside of valid '
                    'range. Disabling.')
        elif isinstance(self._samples, str):
            if self._samples == 'max':
                self._samples = max_samples.value

        # create an MSAA render buffer if self._samples > 1
        self.frameBufferMsaa = GL.GLuint()  # is zero if not configured
        if self._samples > 1:
            # multi-sample FBO and rander buffer
            GL.glGenFramebuffers(1, ctypes.byref(self.frameBufferMsaa))
            GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.frameBufferMsaa)

            # we don't need a multi-sample texture
            rb_color_msaa_id = GL.GLuint()
            GL.glGenRenderbuffers(1, ctypes.byref(rb_color_msaa_id))
github psychopy / psychopy / psychopy / visual / form.py View on Github external
def _checkHeaders(fields):
            """A nested function for testing the names of fields in any given set of items

            Raises NameError if fields do not match required survey fields
            """
            surveyFields = ['index', 'responseWidth', 'layout', 'questionText', 'type', 'questionWidth', 'options']
            if not set(surveyFields) == set(fields):
                msg = "Use the following fields/column names for Forms...\n{}".format(surveyFields)
                if self.autoLog:
                    psychopy.logging.error(msg)
                raise NameError(msg)
github psychopy / psychopy / psychopy / web.py View on Github external
if tryProxy(proxies) is True:
            if log:
                msg = 'Using %s (from prefs)'
                logging.debug(msg % prefs.connections['proxy'])
            # this will now be used globally for ALL urllib opening
            opener = urllib.request.build_opener(proxies)
            urllib.request.install_opener(opener)
            return 1
        else:
            if log:
                logging.debug("Found a previous proxy but it didn't work")

    # try finding/using a proxy.pac file
    pacURLs = getPacFiles()
    if log:
        logging.debug("Found proxy PAC files: %s" % pacURLs)
    proxies = proxyFromPacFiles(pacURLs)  # installs opener, if successful
    if (proxies and
            hasattr(proxies, 'proxies') and
            len(proxies.proxies['http']) > 0):
        # save that proxy for future
        prefs.connections['proxy'] = proxies.proxies['http']
        prefs.saveUserPrefs()
        if log:
            msg = 'Using %s (from proxy PAC file)'
            logging.debug(msg % prefs.connections['proxy'])
        return 1

    # try finding/using 'auto-detect proxy'
    pacURLs = getWpadFiles()
    proxies = proxyFromPacFiles(pacURLs)  # installs opener, if successful
    if (proxies and
github psychopy / psychopy / psychopy / app / connections / sendusage.py View on Github external
if len(systemInfo) > 30:  # if it's too long PHP/SQL fails to store!?
            systemInfo = systemInfo[0:30]
    elif sys.platform == 'win32':
        systemInfo = "win32_v" + platform.version()
    else:
        systemInfo = platform.system() + platform.release()
    u = "http://usage.psychopy.org/submit.php?date=%s&sys=%s&version=%s&misc=%s"
    URL = u % (dateNow, systemInfo, v, miscInfo)
    try:
        req = web.urllib.request.Request(URL)
        if certifi:
            page = web.urllib.request.urlopen(req, cafile=certifi.where())
        else:
            page = web.urllib.request.urlopen(req)
    except Exception:
        logging.warning("Couldn't connect to psychopy.org\n"
                        "Check internet settings (and proxy "
github psychopy / psychopy / psychopy / data / utils.py View on Github external
try:
                    assert n == int(n)
                except AssertionError:
                    raise TypeError("importConditions() was given some "
                                    "`indices` but could not parse them")

    # the selection might now be a slice or a series of indices
    if isinstance(selection, slice):
        trialList = trialList[selection]
    elif len(selection) > 0:
        allConds = trialList
        trialList = []
        for ii in selection:
            trialList.append(allConds[int(round(ii))])

    logging.exp('Imported %s as conditions, %d conditions, %d params' %
                (fileName, len(trialList), len(fieldNames)))
    if returnFieldNames:
        return (trialList, fieldNames)
    else:
        return trialList