本文整理汇总了Python中psychopy.logging.warn函数的典型用法代码示例。如果您正苦于以下问题:Python warn函数的具体用法?Python warn怎么用?Python warn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: writeWindowCode
def writeWindowCode(self, buff):
"""Setup the window code.
"""
buff.writeIndentedLines("\n# Setup the Window\n")
# get parameters for the Window
fullScr = self.params['Full-screen window'].val
# if fullscreen then hide the mouse, unless its requested explicitly
allowGUI = (not bool(fullScr)) or bool(self.params['Show mouse'].val)
allowStencil = False
# NB routines is a dict:
for thisRoutine in list(self.exp.routines.values()):
# a single routine is a list of components:
for thisComp in thisRoutine:
if thisComp.type == 'Aperture':
allowStencil = True
if thisComp.type == 'RatingScale':
allowGUI = True # to have a mouse
requestedScreenNumber = int(self.params['Screen'].val)
nScreens = 10
# try:
# nScreens = wx.Display.GetCount()
# except Exception:
# # will fail if application hasn't been created (e.g. in test
# # environments)
# nScreens = 10
if requestedScreenNumber > nScreens:
logging.warn("Requested screen can't be found. Writing script "
"using first available screen.")
screenNumber = 0
else:
# computer has 1 as first screen
screenNumber = requestedScreenNumber - 1
size = self.params['Window size (pixels)']
code = ("win = visual.Window(\n size=%s, fullscr=%s, screen=%s,"
"\n allowGUI=%s, allowStencil=%s,\n")
vals = (size, fullScr, screenNumber, allowGUI, allowStencil)
buff.writeIndented(code % vals)
code = (" monitor=%(Monitor)s, color=%(color)s, "
"colorSpace=%(colorSpace)s,\n")
if self.params['blendMode'].val:
code += " blendMode=%(blendMode)s, useFBO=True,\n"
if self.params['Units'].val != 'use prefs':
code += " units=%(Units)s"
code = code.rstrip(', \n') + ')\n'
buff.writeIndentedLines(code % self.params)
if 'microphone' in self.exp.psychopyLibs: # need a pyo Server
buff.writeIndentedLines("\n# Enable sound input/output:\n"
"microphone.switchOn()\n")
code = ("# store frame rate of monitor if we can measure it\n"
"expInfo['frameRate'] = win.getActualFrameRate()\n"
"if expInfo['frameRate'] != None:\n"
" frameDur = 1.0 / round(expInfo['frameRate'])\n"
"else:\n"
" frameDur = 1.0 / 60.0 # could not measure, so guess\n")
buff.writeIndentedLines(code)
示例2: setMouseType
def setMouseType(self, name='arrow'):
"""Change the appearance of the cursor for this window. Cursor types
provide contextual hints about how to interact with on-screen objects.
The graphics used 'standard cursors' provided by the operating system.
They may vary in appearance and hot spot location across platforms. The
following names are valid on most platforms:
'arrow' : Default pointer
'ibeam' : Indicates text can be edited
'crosshair' : Crosshair with hot-spot at center
'hand' : A pointing hand
'hresize' : Double arrows pointing horizontally
'vresize' : Double arrows pointing vertically
Note, on Windows the 'crosshair' option is XORed with the background
color. It will not be visible when placed over 50% grey fields.
:param name: str, type of standard cursor to use
:return:
"""
try:
glfw.set_cursor(self.winHandle, _CURSORS_[name])
except KeyError:
logging.warn(
"Invalid cursor type name '{}', using default.".format(type))
glfw.set_cursor(self.winHandle, _CURSORS_['arrow'])
示例3: _bestDriver
def _bestDriver(devNames, devIDs):
"""Find ASIO or Windows sound drivers
"""
preferredDrivers = prefs.general['audioDriver']
outputID = None
audioDriver = None
osEncoding = sys.getfilesystemencoding()
for prefDriver in preferredDrivers:
logging.info('Looking for {}'.format(prefDriver))
if prefDriver.lower() == 'directsound':
prefDriver = u'Primary Sound'
# look for that driver in available devices
for devN, devString in enumerate(devNames):
logging.info('Examining for {}'.format(devString))
try:
ds = devString.decode(osEncoding).encode('utf-8').lower()
if prefDriver.encode('utf-8').lower() in ds:
audioDriver = devString.decode(osEncoding).encode('utf-8')
outputID = devIDs[devN]
logging.info('Success: {}'.format(devString))
# we found a driver don't look for others
return audioDriver, outputID
except (UnicodeDecodeError, UnicodeEncodeError):
logging.info('Failed: {}'.format(devString))
logging.warn('find best sound driver - could not '
'interpret unicode in driver name')
else:
return None, None
示例4: flac2wav
def flac2wav(path, keep=True):
"""Uncompress: convert .flac file (on disk) to .wav format (new file).
If `path` is a directory name, convert all .flac files in the directory.
`keep` to retain the original .flac file(s), default `True`.
"""
flac_path = _getFlacPath()
flac_files = []
if path.endswith('.flac'):
flac_files = [path]
elif type(path) == str and os.path.isdir(path):
flac_files = glob.glob(os.path.join(path, '*.flac'))
if len(flac_files) == 0:
logging.warn('failed to find .flac file(s) from %s' % path)
return None
wav_files = []
for flacfile in flac_files:
wavname = flacfile.strip('.flac') + '.wav'
flac_cmd = [flac_path, "-d", "--totally-silent",
"-f", "-o", wavname, flacfile]
_junk, se = core.shellCall(flac_cmd, stderr=True)
if se:
logging.error(se)
if not keep:
os.unlink(flacfile)
wav_files.append(wavname)
if len(wav_files) == 1:
return wav_files[0]
else:
return wav_files
示例5: setMouseType
def setMouseType(self, name='arrow'):
"""Change the appearance of the cursor for this window. Cursor types
provide contextual hints about how to interact with on-screen objects.
The graphics used 'standard cursors' provided by the operating system.
They may vary in appearance and hot spot location across platforms. The
following names are valid on most platforms:
* ``arrow`` : Default pointer
* ``ibeam`` : Indicates text can be edited
* ``crosshair`` : Crosshair with hot-spot at center
* ``hand`` : A pointing hand
* ``hresize`` : Double arrows pointing horizontally
* ``vresize`` : Double arrows pointing vertically
Requires the GLFW backend, otherwise this function does nothing! Note,
on Windows the ``crosshair`` option is negated with the background
color. It will not be visible when placed over 50% grey fields.
Parameters
----------
name : str
Type of standard cursor to use.
"""
try:
glfw.set_cursor(self.winHandle, _CURSORS_[name])
except KeyError:
logging.warn(
"Invalid cursor type name '{}', using default.".format(type))
glfw.set_cursor(self.winHandle, _CURSORS_['arrow'])
示例6: __init__
def __init__(self, project_file=None, root_path=None, osf=None,
name='', autosave=True):
self.autosave = autosave # try to save file automatically on __del__
self.project_file = project_file
self.root_path = root_path # overwrite previous (indexed) location
self.name = name # not needed but allows storing a short descr name
# these will be update from project file loading if it exists
self.index = []
self.username = None
self.project_id = None
self.connected = False # have we gone online yet?
# load the project file (if exists) for info about previous sync
if project_file:
self.load(project_file)
# check/set root_path
if self.root_path is None:
self.root_path = root_path # use what we just loaded
elif root_path not in [None, self.root_path]:
logging.warn("The requested root_path and the previous root_path "
"differ. Using the requested path."
"given: {}"
"stored: {}".format(root_path, self.root_path))
if self.root_path is None:
logging.warn("Project file failed to load a root_path "
"for the local files and none was provided")
self.osf = osf # the self.osf is as property set on-access
示例7: __init__
def __init__(self, win, size, pos=(0,0), ori=0, nVert=120, shape='circle', units=None,
name='', autoLog=True):
#what local vars are defined (these are the init params) for use by __repr__
self._initParams = dir()
self._initParams.remove('self')
#set self params
self.autoLog=False #set this False first and change after attribs are set
self.win=win
self.name = name
self.ori = ori
#unit conversions
if units!=None and len(units):
self.units = units
else:
self.units = win.units
# ugly hack for setting vertices using combination of shape and nVerts
if type(nVert) == int:
self.nVert = nVert
regularPolygon = True
self.shape = shape
unrecognized = False
if shape is None:
pass #just use the nVert we were given
elif type(shape) in [str, unicode]:
if shape.lower() == 'circle':
pass #just use the nVert we were given
elif shape.lower() == 'square':
regularPolygon = False # if we use polygon then we have to hack the orientation
vertices = [[0.5,-0.5],[-0.5,-0.5],[-0.5,0.5],[0.5,0.5]]
elif shape.lower() == 'triangle':
regularPolygon = False # if we use polygon then we have to hack the orientation
vertices = [[0.5,-0.5],[0,0.5],[-0.5,-0.5]]
else:
unrecognized = True
elif type(shape) in [tuple, list, numpy.ndarray]:
regularPolygon = False
vertices = shape
else:
unrecognized = True
if unrecognized:
logging.warn("Unrecognized shape for aperture. Expected 'circle', 'square', 'triangle', vertices or None but got %s" %(repr(shape)))
if regularPolygon:
self._shape = polygon.Polygon(win=self.win, edges=self.nVert,
fillColor=1, lineColor=None,
interpolate=False,
pos=pos,
size=size)
else:
self._shape = ShapeStim(win=self.win, vertices=vertices,
fillColor=1, lineColor=None,
interpolate=False,
pos=pos,
size=size)
self._needVertexUpdate = True
self._reset()#implicitly runs an self.enable()
self.autoLog= autoLog
if autoLog:
logging.exp("Created %s = %s" %(self.name, str(self)))
示例8: setGammaRamp
def setGammaRamp(pygletWindow, newRamp, nAttempts=3):
"""Sets the hardware look-up table, using platform-specific ctypes functions.
For use with pyglet windows only (pygame has its ow routines for this).
Ramp should be provided as 3x256 or 3x1024 array in range 0:1.0
On windows the first attempt to set the ramp doesn't always work. The parameter nAttemps
allows the user to determine how many attempts should be made before failing
"""
if newRamp.shape[0]!=3 and newRamp.shape[1]==3:
newRamp= numpy.ascontiguousarray(newRamp.transpose())
if sys.platform=='win32':
newRamp= (255.0*newRamp).astype(numpy.uint16)
newRamp.byteswap(True)#necessary, according to pyglet post from Martin Spacek
for n in range(nAttempts):
success = windll.gdi32.SetDeviceGammaRamp(0xFFFFFFFF & pygletWindow._dc, newRamp.ctypes) # FB 504
if success:
break
assert success, 'SetDeviceGammaRamp failed'
if sys.platform=='darwin':
newRamp= (newRamp).astype(numpy.float32)
LUTlength=newRamp.shape[1]
error =carbon.CGSetDisplayTransferByTable(pygletWindow._screen.id, LUTlength,
newRamp[0,:].ctypes, newRamp[1,:].ctypes, newRamp[2,:].ctypes)
assert not error, 'CGSetDisplayTransferByTable failed'
if sys.platform.startswith('linux') and not _TravisTesting:
newRamp= (65535*newRamp).astype(numpy.uint16)
success = xf86vm.XF86VidModeSetGammaRamp(pygletWindow._x_display, pygletWindow._x_screen_id, 256,
newRamp[0,:].ctypes, newRamp[1,:].ctypes, newRamp[2,:].ctypes)
assert success, 'XF86VidModeSetGammaRamp failed'
elif _TravisTesting:
logging.warn("It looks like we're running in the Travis-CI testing environment. Hardware gamma table cannot be set")
示例9: load
def load(self, filename=None):
"""If name is None then we'll try to save to
"""
def parseLUTLine(line):
return line.replace('[','').replace(']','').split(',')
if filename is None:
from psychopy import prefs
filename = os.path.join(prefs.paths['userPrefsDir'], 'crs_bits.cfg')
if os.path.exists(filename):
config = configparser.RawConfigParser()
with open(filename) as f:
config.readfp(f)
self.os = config.get('system','os')
self.gfxCard = config.get('system','gfxCard')
self.identityLUT = np.ones([256,3])
self.identityLUT[:,0] = parseLUTLine(config.get('identityLUT','r'))
self.identityLUT[:,1] = parseLUTLine(config.get('identityLUT','g'))
self.identityLUT[:,2] = parseLUTLine(config.get('identityLUT','b'))
return True
else:
logging.warn('no config file yet for %s' %self.bits)
self.identityLUT = None
self.gfxCard = None
self.os = None
return False
示例10: wav2flac
def wav2flac(path, keep=True):
"""Lossless compression: convert .wav file (on disk) to .flac format.
If `path` is a directory name, convert all .wav files in the directory.
`keep` to retain the original .wav file(s), default `True`.
"""
flac_path = _getFlacPath()
wav_files = []
if path.endswith(".wav"):
wav_files = [path]
elif type(path) == str and os.path.isdir(path):
wav_files = glob.glob(os.path.join(path, "*.wav"))
if len(wav_files) == 0:
logging.warn("failed to find .wav file(s) from %s" % path)
return None
flac_files = []
for wavfile in wav_files:
flacfile = wavfile.strip(".wav") + ".flac"
flac_cmd = [flac_path, "-8", "-f", "--totally-silent", "-o", flacfile, wavfile]
__, se = core.shellCall(flac_cmd, stderr=True)
if se or not os.path.isfile(flacfile): # just try again
# ~2% incidence when recording for 1s, 650+ trials
# never got two in a row; core.wait() does not help
logging.warn("Failed to convert to .flac; trying again")
__, se = core.shellCall(flac_cmd, stderr=True)
if se:
logging.error(se)
if not keep:
os.unlink(wavfile)
flac_files.append(flacfile)
if len(wav_files) == 1:
return flac_files[0]
else:
return flac_files
示例11: run_event
def run_event(self):
if self.event == 'exit':
logging.info("Exiting. . .")
self.window.close()
core.quit()
if self.event in ['nothing', 'continue']:
pass
else:
logging.warn("Event not recognized. Doing nothing.")
示例12: setUseShaders
def setUseShaders(self, val=True):
"""Set this stimulus to use shaders if possible.
"""
if val==True and self.win._haveShaders==False:
logging.warn("Shaders were requested but aren;t available. Shaders need OpenGL 2.0+ drivers")
if val!=self.useShaders:
self.useShaders=val
self._needSetText=True
self._needUpdate = True
示例13: resample
def resample(self, newRate=16000, keep=True, log=True):
"""Re-sample the saved file to a new rate, return the full path.
Can take several visual frames to resample a 2s recording.
The default values for resample() are for google-speech, keeping the
original (presumably recorded at 48kHz) to archive.
A warning is generated if the new rate not an integer factor / multiple of the old rate.
To control anti-aliasing, use pyo.downsamp() or upsamp() directly.
"""
if not self.savedFile or not os.path.isfile(self.savedFile):
msg = "%s: Re-sample requested but no saved file" % self.loggingId
logging.error(msg)
raise ValueError(msg)
if newRate <= 0 or type(newRate) != int:
msg = "%s: Re-sample bad new rate = %s" % (self.loggingId, repr(newRate))
logging.error(msg)
raise ValueError(msg)
# set-up:
if self.rate >= newRate:
ratio = float(self.rate) / newRate
info = "-ds%i" % ratio
else:
ratio = float(newRate) / self.rate
info = "-us%i" % ratio
if ratio != int(ratio):
logging.warn("%s: old rate is not an integer factor of new rate" % self.loggingId)
ratio = int(ratio)
newFile = info.join(os.path.splitext(self.savedFile))
# use pyo's downsamp or upsamp based on relative rates:
if not ratio:
logging.warn("%s: Re-sample by %sx is undefined, skipping" % (self.loggingId, str(ratio)))
elif self.rate >= newRate:
t0 = core.getTime()
downsamp(self.savedFile, newFile, ratio) # default 128-sample anti-aliasing
if log and self.autoLog:
logging.exp(
"%s: Down-sampled %sx in %.3fs to %s" % (self.loggingId, str(ratio), core.getTime() - t0, newFile)
)
else:
t0 = core.getTime()
upsamp(self.savedFile, newFile, ratio) # default 128-sample anti-aliasing
if log and self.autoLog:
logging.exp(
"%s: Up-sampled %sx in %.3fs to %s" % (self.loggingId, str(ratio), core.getTime() - t0, newFile)
)
# clean-up:
if not keep:
os.unlink(self.savedFile)
self.savedFile = newFile
self.rate = newRate
return os.path.abspath(newFile)
示例14: quickCheck
def quickCheck(self):
"""Check whether the current graphics card and OS match those of the last saved LUT
"""
if self._getGfxCardString() != self.gfxCard:
logging.warn("The graphics card or its driver has changed. We'll re-check the identity LUT for the card")
return 0
if self._getOSstring() != self.os:
logging.warn("The OS has been changed/updated. We'll re-check the identity LUT for the card")
return 0
return 1 #all seems the same as before
示例15: _warnTesting
def _warnTesting(self):
msg = "We need to run some tests on your graphics card (hopefully just once). " + \
"The BitsSharp will go into status mode while this is done. " + \
"It can take a minute or two."
logging.warn(msg)
logging.flush()
msgOnScreen = visual.TextStim(self.win, msg)
msgOnScreen.draw()
self.win.flip()
core.wait(1.0)
self.win.flip()