index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
57,740
logging
__init__
Initialize with the specified logger being a child of this placeholder.
def __init__(self, alogger): """ Initialize with the specified logger being a child of this placeholder. """ self.loggerMap = { alogger : None }
(self, alogger)
57,741
logging
append
Add the specified logger as a child of this placeholder.
def append(self, alogger): """ Add the specified logger as a child of this placeholder. """ if alogger not in self.loggerMap: self.loggerMap[alogger] = None
(self, alogger)
57,742
logging
RootLogger
A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy.
class RootLogger(Logger): """ A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level) def __reduce__(self): return getLogger, ()
(level)
57,743
logging
__init__
Initialize the logger with the name "root".
def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level)
(self, level)
57,744
logging
__reduce__
null
def __reduce__(self): return getLogger, ()
(self)
57,770
logging
StrFormatStyle
null
class StrFormatStyle(PercentStyle): default_format = '{message}' asctime_format = '{asctime}' asctime_search = '{asctime' fmt_spec = re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\d+|{\w+})?[,_]?(\.(\d+|{\w+}))?[bcdefgnosx%]?$', re.I) field_spec = re.compile(r'^(\d+|\w+)(\.\w+|\[[^]]+\])*$') def _format(self, record): if defaults := self._defaults: values = defaults | record.__dict__ else: values = record.__dict__ return self._fmt.format(**values) def validate(self): """Validate the input format, ensure it is the correct string formatting style""" fields = set() try: for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt): if fieldname: if not self.field_spec.match(fieldname): raise ValueError('invalid field name/expression: %r' % fieldname) fields.add(fieldname) if conversion and conversion not in 'rsa': raise ValueError('invalid conversion: %r' % conversion) if spec and not self.fmt_spec.match(spec): raise ValueError('bad specifier: %r' % spec) except ValueError as e: raise ValueError('invalid format: %s' % e) if not fields: raise ValueError('invalid format: no fields')
(fmt, *, defaults=None)
57,772
logging
_format
null
def _format(self, record): if defaults := self._defaults: values = defaults | record.__dict__ else: values = record.__dict__ return self._fmt.format(**values)
(self, record)
57,775
logging
validate
Validate the input format, ensure it is the correct string formatting style
def validate(self): """Validate the input format, ensure it is the correct string formatting style""" fields = set() try: for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt): if fieldname: if not self.field_spec.match(fieldname): raise ValueError('invalid field name/expression: %r' % fieldname) fields.add(fieldname) if conversion and conversion not in 'rsa': raise ValueError('invalid conversion: %r' % conversion) if spec and not self.fmt_spec.match(spec): raise ValueError('bad specifier: %r' % spec) except ValueError as e: raise ValueError('invalid format: %s' % e) if not fields: raise ValueError('invalid format: no fields')
(self)
57,776
logging
StreamHandler
A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used.
class StreamHandler(Handler): """ A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. """ terminator = '\n' def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream def flush(self): """ Flushes the stream. """ self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() finally: self.release() def emit(self, record): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ try: msg = self.format(record) stream = self.stream # issue 35046: merged two stream.writes into one. stream.write(msg + self.terminator) self.flush() except RecursionError: # See issue 36272 raise except Exception: self.handleError(record) def setStream(self, stream): """ Sets the StreamHandler's stream to the specified value, if it is different. Returns the old stream, if the stream was changed, or None if it wasn't. """ if stream is self.stream: result = None else: result = self.stream self.acquire() try: self.flush() self.stream = stream finally: self.release() return result def __repr__(self): level = getLevelName(self.level) name = getattr(self.stream, 'name', '') # bpo-36015: name can be an int name = str(name) if name: name += ' ' return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
(stream=None)
57,777
logging
__init__
Initialize the handler. If stream is not specified, sys.stderr is used.
def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream
(self, stream=None)
57,778
logging
__repr__
null
def __repr__(self): level = getLevelName(self.level) name = getattr(self.stream, 'name', '') # bpo-36015: name can be an int name = str(name) if name: name += ' ' return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
(self)
57,784
logging
emit
Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream.
def emit(self, record): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ try: msg = self.format(record) stream = self.stream # issue 35046: merged two stream.writes into one. stream.write(msg + self.terminator) self.flush() except RecursionError: # See issue 36272 raise except Exception: self.handleError(record)
(self, record)
57,797
logging
StringTemplateStyle
null
class StringTemplateStyle(PercentStyle): default_format = '${message}' asctime_format = '${asctime}' asctime_search = '${asctime}' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._tpl = Template(self._fmt) def usesTime(self): fmt = self._fmt return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_search) >= 0 def validate(self): pattern = Template.pattern fields = set() for m in pattern.finditer(self._fmt): d = m.groupdict() if d['named']: fields.add(d['named']) elif d['braced']: fields.add(d['braced']) elif m.group(0) == '$': raise ValueError('invalid format: bare \'$\' not allowed') if not fields: raise ValueError('invalid format: no fields') def _format(self, record): if defaults := self._defaults: values = defaults | record.__dict__ else: values = record.__dict__ return self._tpl.substitute(**values)
(*args, **kwargs)
57,798
logging
__init__
null
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._tpl = Template(self._fmt)
(self, *args, **kwargs)
57,799
logging
_format
null
def _format(self, record): if defaults := self._defaults: values = defaults | record.__dict__ else: values = record.__dict__ return self._tpl.substitute(**values)
(self, record)
57,801
logging
usesTime
null
def usesTime(self): fmt = self._fmt return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_search) >= 0
(self)
57,802
logging
validate
null
def validate(self): pattern = Template.pattern fields = set() for m in pattern.finditer(self._fmt): d = m.groupdict() if d['named']: fields.add(d['named']) elif d['braced']: fields.add(d['braced']) elif m.group(0) == '$': raise ValueError('invalid format: bare \'$\' not allowed') if not fields: raise ValueError('invalid format: no fields')
(self)
57,808
logging
_StderrHandler
This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time.
class _StderrHandler(StreamHandler): """ This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time. """ def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level) @property def stream(self): return sys.stderr
(level=0)
57,809
logging
__init__
Initialize the handler.
def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level)
(self, level=0)
57,829
logging
_acquireLock
Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock().
def _acquireLock(): """ Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock(). """ if _lock: _lock.acquire()
()
57,830
logging
_addHandlerRef
Add a handler to the internal cleanup list using a weak reference.
def _addHandlerRef(handler): """ Add a handler to the internal cleanup list using a weak reference. """ _acquireLock() try: _handlerList.append(weakref.ref(handler, _removeHandlerRef)) finally: _releaseLock()
(handler)
57,831
logging
_after_at_fork_child_reinit_locks
null
def _after_at_fork_child_reinit_locks(): for handler in _at_fork_reinit_lock_weakset: handler._at_fork_reinit() # _acquireLock() was called in the parent before forking. # The lock is reinitialized to unlocked state. _lock._at_fork_reinit()
()
57,832
logging
_checkLevel
null
def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in _nameToLevel: raise ValueError("Unknown level: %r" % level) rv = _nameToLevel[level] else: raise TypeError("Level not an integer or a valid string: %r" % (level,)) return rv
(level)
57,865
logging
_register_at_fork_reinit_lock
null
def _register_at_fork_reinit_lock(instance): _acquireLock() try: _at_fork_reinit_lock_weakset.add(instance) finally: _releaseLock()
(instance)
57,866
logging
_releaseLock
Release the module-level lock acquired by calling _acquireLock().
def _releaseLock(): """ Release the module-level lock acquired by calling _acquireLock(). """ if _lock: _lock.release()
()
57,867
logging
_removeHandlerRef
Remove a handler reference from the internal cleanup list.
def _removeHandlerRef(wr): """ Remove a handler reference from the internal cleanup list. """ # This function can be called during module teardown, when globals are # set to None. It can also be called from another thread. So we need to # pre-emptively grab the necessary globals and check if they're None, # to prevent race conditions and failures during interpreter shutdown. acquire, release, handlers = _acquireLock, _releaseLock, _handlerList if acquire and release and handlers: acquire() try: if wr in handlers: handlers.remove(wr) finally: release()
(wr)
57,868
logging
_showwarning
Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING.
def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s)
(message, category, filename, lineno, file=None, line=None)
57,869
logging
addLevelName
Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting.
def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelToName[level] = levelName _nameToLevel[levelName] = level finally: _releaseLock()
(level, levelName)
57,871
logging
basicConfig
Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured, unless the keyword argument *force* is set to ``True``. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. force If this keyword is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments. encoding If specified together with a filename, this encoding is passed to the created FileHandler, causing it to be used when the file is opened. errors If specified together with a filename, this value is passed to the created FileHandler, causing it to be used when the file is opened in text mode. If not specified, the default value is `backslashreplace`. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. .. versionchanged:: 3.8 Added the ``force`` parameter. .. versionchanged:: 3.9 Added the ``encoding`` and ``errors`` parameters.
def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured, unless the keyword argument *force* is set to ``True``. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. force If this keyword is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments. encoding If specified together with a filename, this encoding is passed to the created FileHandler, causing it to be used when the file is opened. errors If specified together with a filename, this value is passed to the created FileHandler, causing it to be used when the file is opened in text mode. If not specified, the default value is `backslashreplace`. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. .. versionchanged:: 3.8 Added the ``force`` parameter. .. versionchanged:: 3.9 Added the ``encoding`` and ``errors`` parameters. """ # Add thread safety in case someone mistakenly calls # basicConfig() from multiple threads _acquireLock() try: force = kwargs.pop('force', False) encoding = kwargs.pop('encoding', None) errors = kwargs.pop('errors', 'backslashreplace') if force: for h in root.handlers[:]: root.removeHandler(h) h.close() if len(root.handlers) == 0: handlers = kwargs.pop("handlers", None) if handlers is None: if "stream" in kwargs and "filename" in kwargs: raise ValueError("'stream' and 'filename' should not be " "specified together") else: if "stream" in kwargs or "filename" in kwargs: raise ValueError("'stream' or 'filename' should not be " "specified together with 'handlers'") if handlers is None: filename = kwargs.pop("filename", None) mode = kwargs.pop("filemode", 'a') if filename: if 'b' in mode: errors = None else: encoding = io.text_encoding(encoding) h = FileHandler(filename, mode, encoding=encoding, errors=errors) else: stream = kwargs.pop("stream", None) h = StreamHandler(stream) handlers = [h] dfs = kwargs.pop("datefmt", None) style = kwargs.pop("style", '%') if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) fs = kwargs.pop("format", _STYLES[style][1]) fmt = Formatter(fs, dfs, style) for h in handlers: if h.formatter is None: h.setFormatter(fmt) root.addHandler(h) level = kwargs.pop("level", None) if level is not None: root.setLevel(level) if kwargs: keys = ', '.join(kwargs.keys()) raise ValueError('Unrecognised argument(s): %s' % keys) finally: _releaseLock()
(**kwargs)
57,872
logging
captureWarnings
If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations.
def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
(capture)
57,874
logging
critical
Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.critical(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,875
logging
<lambda>
null
currentframe = lambda: sys._getframe(3)
()
57,876
logging
debug
Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,877
logging
disable
Disable all logging calls of severity 'level' and below.
def disable(level=CRITICAL): """ Disable all logging calls of severity 'level' and below. """ root.manager.disable = level root.manager._clear_cache()
(level=50)
57,878
logging
error
Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,879
logging
exception
Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format.
def exception(msg, *args, exc_info=True, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ error(msg, *args, exc_info=exc_info, **kwargs)
(msg, *args, exc_info=True, **kwargs)
57,880
logging
fatal
Don't use this function, use critical() instead.
def fatal(msg, *args, **kwargs): """ Don't use this function, use critical() instead. """ critical(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,881
logging
getLevelName
Return the textual or numeric representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. If a string representation of the level is passed in, the corresponding numeric value is returned. If no matching numeric or string value is passed in, the string 'Level %s' % level is returned.
def getLevelName(level): """ Return the textual or numeric representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. If a string representation of the level is passed in, the corresponding numeric value is returned. If no matching numeric or string value is passed in, the string 'Level %s' % level is returned. """ # See Issues #22386, #27937 and #29220 for why it's this way result = _levelToName.get(level) if result is not None: return result result = _nameToLevel.get(level) if result is not None: return result return "Level %s" % level
(level)
57,882
logging
getLogRecordFactory
Return the factory to be used when instantiating a log record.
def getLogRecordFactory(): """ Return the factory to be used when instantiating a log record. """ return _logRecordFactory
()
57,883
logging
getLogger
Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger.
def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if not name or isinstance(name, str) and name == root.name: return root return Logger.manager.getLogger(name)
(name=None)
57,884
logging
getLoggerClass
Return the class to be used when instantiating a logger.
def getLoggerClass(): """ Return the class to be used when instantiating a logger. """ return _loggerClass
()
57,885
logging
info
Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,887
logging
log
Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def log(level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.log(level, msg, *args, **kwargs)
(level, msg, *args, **kwargs)
57,888
logging
makeLogRecord
Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.
def makeLogRecord(dict): """ Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. """ rv = _logRecordFactory(None, None, "", 0, "", (), None, None) rv.__dict__.update(dict) return rv
(dict)
57,891
logging
setLogRecordFactory
Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record.
def setLogRecordFactory(factory): """ Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. """ global _logRecordFactory _logRecordFactory = factory
(factory)
57,892
logging
setLoggerClass
Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__()
def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass
(klass)
57,893
logging
shutdown
Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit.
def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for wr in reversed(handlerList[:]): #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: h = wr() if h: try: h.acquire() h.flush() h.close() except (OSError, ValueError): # Ignore errors which might be caused # because handlers have been closed but # references to them are still around at # application exit. pass finally: h.release() except: # ignore everything, as we're shutting down if raiseExceptions: raise #else, swallow
(handlerList=[<weakref at 0x7f7bf5c369d0; to '_StderrHandler' at 0x7f7bf5c33190>, <weakref at 0x7f7bf5ca71a0; to '_StderrHandler' at 0x7f7bf5e145b0>])
57,898
logging
warn
null
def warn(msg, *args, **kwargs): warnings.warn("The 'warn' function is deprecated, " "use 'warning' instead", DeprecationWarning, 2) warning(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,899
logging
warning
Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.warning(msg, *args, **kwargs)
(msg, *args, **kwargs)
57,911
laminci._env
get_package_name
null
def get_package_name(root_directory: Optional[Path] = None) -> Optional[str]: if Path("lamin-project.yaml").exists(): config = load_project_yaml(root_directory=root_directory) if "package_name" in config: return config["package_name"] else: return None elif Path("pyproject.toml").exists(): with open("pyproject.toml") as f: d = toml.load(f) return d["project"]["name"].replace("-", "_") else: return None
(root_directory: Optional[pathlib.Path] = None) -> Optional[str]
57,912
laminci._env
get_schema_handle
null
def get_schema_handle() -> Optional[str]: package_name = get_package_name() if package_name is not None: if package_name.startswith("lnschema_"): return package_name.replace("lnschema_", "") else: return None else: raise ValueError( "Could not infer python package, add pyproject.toml or update" " lamin-project.yaml" )
() -> Optional[str]
57,913
laminci._docs
move_built_docs_to_docs_slash_project_slug
null
def move_built_docs_to_docs_slash_project_slug(): if os.environ["GITHUB_EVENT_NAME"] != "push": return yaml = load_project_yaml() shutil.move("_build/html", f"_build/{yaml['project_slug']}") os.makedirs("_build/html/docs") shutil.move(f"_build/{yaml['project_slug']}", "_build/html/docs")
()
57,914
laminci._docs
move_built_docs_to_slash_project_slug
null
def move_built_docs_to_slash_project_slug(): if os.environ["GITHUB_EVENT_NAME"] != "push": return yaml = load_project_yaml() shutil.move("_build/html", "_build/html_tmp") os.makedirs("_build/html") shutil.move("_build/html_tmp", f"_build/html/{yaml['project_slug']}")
()
57,916
laminci._artifacts
upload_docs_artifact
null
def upload_docs_artifact(aws: bool = False) -> None: if os.getenv("GITHUB_EVENT_NAME") not in {"push", "repository_dispatch"}: logger.info("Only upload docs artifact for push event.") return None if aws: upload_docs_artifact_aws() else: try: # this is super ugly but necessary right now # we might need to close the current instance as it might be corrupted import lamindb_setup lamindb_setup.close() import lamindb as ln # noqa upload_docs_artifact_lamindb() except ImportError: warnings.warn("Fall back to AWS") upload_docs_artifact_aws()
(aws: bool = False) -> NoneType
57,918
modelcards.card_data
CardData
CardData(language: Union[str, List[str], NoneType] = None, license: Optional[str] = None, library_name: Optional[str] = None, tags: Optional[List[str]] = None, datasets: Union[str, List[str], NoneType] = None, metrics: Union[str, List[str], NoneType] = None, eval_results: Optional[List[modelcards.card_data.EvalResult]] = None, model_name: Optional[str] = None, **kwargs)
class CardData: def __init__( self, language: Optional[Union[str, List[str]]] = None, license: Optional[str] = None, library_name: Optional[str] = None, tags: Optional[List[str]] = None, datasets: Optional[Union[str, List[str]]] = None, metrics: Optional[Union[str, List[str]]] = None, eval_results: Optional[List[EvalResult]] = None, model_name: Optional[str] = None, **kwargs, ): """Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md Args: language (`Union[str, List[str]]`, *optional*): Language of model's training data or metadata. Example: `'en'`. Defaults to `None`. license (`str`, *optional*): License of this model. Example: apache-2.0 or any license from https://hf.co/docs/hub/model-repos#list-of-license-identifiers. Defaults to None. library_name (`str`, *optional*): Name of library used by this model. Example: keras or any library from https://github.com/huggingface/hub-docs/blob/main/js/src/lib/interfaces/Libraries.ts. Defaults to None. tags (`List[str]`, *optional*): List of tags to add to your model that can be used when filtering on the Hugging Face Hub. Defaults to None. datasets (`Union[str, List[str]]`, *optional*): Dataset or list of datasets that were used to train this model. Should be a dataset ID found on https://hf.co/datasets. Defaults to None. metrics (`Union[str, List[str]]`, *optional*): List of metrics used to evaluate this model. Should be a metric name that can be found at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. eval_results (`Union[List[EvalResult], EvalResult]`, *optional*): List of `modelcards.EvalResult` that define evaluation results of the model. If provided, `model_name` kwarg must be provided. Defaults to `None`. model_name (`str`, *optional*): A name for this model. Required if you provide `eval_results`. It is used along with `eval_results` to construct the `model-index` within the card's metadata. The name you supply here is what will be used on PapersWithCode's leaderboards. Defaults to None. kwargs (`dict`, *optional*): Additional metadata that will be added to the model card. Defaults to None. Example: >>> from modelcards.card_data import CardData >>> card_data = CardData( ... language="en", ... license="mit", ... library_name="timm", ... tags=['image-classification', 'resnet'], ... ) >>> card_data.to_dict() {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']} """ self.language = language self.license = license self.library_name = library_name self.tags = tags self.datasets = datasets self.metrics = metrics self.eval_results = eval_results self.model_name = model_name self.__dict__.update(kwargs) if self.eval_results: if type(self.eval_results) == EvalResult: self.eval_results = [self.eval_results] if self.model_name is None: raise ValueError("`eval_results` requires `model_name` to be set.") def to_dict(self): """Converts CardData to a dict. It also formats the internal eval_results to be compatible with the model-index format. Returns: `dict`: CardData represented as a dictionary ready to be dumped to a YAML block for inclusion in a README.md file. """ data_dict = copy.deepcopy(self.__dict__) if self.eval_results is not None: data_dict["model-index"] = eval_results_to_model_index( self.model_name, self.eval_results ) del data_dict["eval_results"], data_dict["model_name"] return _remove_none(data_dict) def to_yaml(self): """Dumps CardData to a YAML block for inclusion in a README.md file.""" return yaml.dump(self.to_dict(), sort_keys=False).strip() def __repr__(self): return self.to_yaml()
(language: Union[str, List[str], NoneType] = None, license: Optional[str] = None, library_name: Optional[str] = None, tags: Optional[List[str]] = None, datasets: Union[str, List[str], NoneType] = None, metrics: Union[str, List[str], NoneType] = None, eval_results: Optional[List[modelcards.card_data.EvalResult]] = None, model_name: Optional[str] = None, **kwargs)
57,919
modelcards.card_data
__eq__
null
import copy from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union import yaml @dataclass class EvalResult: """ Flattened representation of individual evaluation results found in model-index. """ # Required # The task identifier # Example: automatic-speech-recognition task_type: str # The dataset identifier # Example: common_voice. Use dataset id from https://hf.co/datasets dataset_type: str # A pretty name for the dataset. # Example: Common Voice (French) dataset_name: str # The metric identifier # Example: wer. Use metric id from https://hf.co/metrics metric_type: str # Value of the metric. # Example: 20.0 or "20.0 ± 1.2" metric_value: Any # Optional # A pretty name for the task. # Example: Speech Recognition task_name: Optional[str] = None # The name of the dataset configuration used in `load_dataset()`. # Example: fr in `load_dataset("common_voice", "fr")`. # See the `datasets` docs for more info: # https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name dataset_config: Optional[str] = None # The split used in `load_dataset()`. # Example: test dataset_split: Optional[str] = None # The revision (AKA Git Sha) of the dataset used in `load_dataset()`. # Example: 5503434ddd753f426f4b38109466949a1217c2bb dataset_revision: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 dataset_args: Optional[Dict[str, Any]] = None # A pretty name for the metric. # Example: Test WER metric_name: Optional[str] = None # The name of the metric configuration used in `load_metric()`. # Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. # See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations metric_config: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 metric_args: Optional[Dict[str, Any]] = None # If true, indicates that evaluation was generated by Hugging Face (vs. self-reported). verified: Optional[bool] = None
(self, other)
57,920
modelcards.card_data
__init__
Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md Args: language (`Union[str, List[str]]`, *optional*): Language of model's training data or metadata. Example: `'en'`. Defaults to `None`. license (`str`, *optional*): License of this model. Example: apache-2.0 or any license from https://hf.co/docs/hub/model-repos#list-of-license-identifiers. Defaults to None. library_name (`str`, *optional*): Name of library used by this model. Example: keras or any library from https://github.com/huggingface/hub-docs/blob/main/js/src/lib/interfaces/Libraries.ts. Defaults to None. tags (`List[str]`, *optional*): List of tags to add to your model that can be used when filtering on the Hugging Face Hub. Defaults to None. datasets (`Union[str, List[str]]`, *optional*): Dataset or list of datasets that were used to train this model. Should be a dataset ID found on https://hf.co/datasets. Defaults to None. metrics (`Union[str, List[str]]`, *optional*): List of metrics used to evaluate this model. Should be a metric name that can be found at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. eval_results (`Union[List[EvalResult], EvalResult]`, *optional*): List of `modelcards.EvalResult` that define evaluation results of the model. If provided, `model_name` kwarg must be provided. Defaults to `None`. model_name (`str`, *optional*): A name for this model. Required if you provide `eval_results`. It is used along with `eval_results` to construct the `model-index` within the card's metadata. The name you supply here is what will be used on PapersWithCode's leaderboards. Defaults to None. kwargs (`dict`, *optional*): Additional metadata that will be added to the model card. Defaults to None. Example: >>> from modelcards.card_data import CardData >>> card_data = CardData( ... language="en", ... license="mit", ... library_name="timm", ... tags=['image-classification', 'resnet'], ... ) >>> card_data.to_dict() {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}
def __init__( self, language: Optional[Union[str, List[str]]] = None, license: Optional[str] = None, library_name: Optional[str] = None, tags: Optional[List[str]] = None, datasets: Optional[Union[str, List[str]]] = None, metrics: Optional[Union[str, List[str]]] = None, eval_results: Optional[List[EvalResult]] = None, model_name: Optional[str] = None, **kwargs, ): """Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md Args: language (`Union[str, List[str]]`, *optional*): Language of model's training data or metadata. Example: `'en'`. Defaults to `None`. license (`str`, *optional*): License of this model. Example: apache-2.0 or any license from https://hf.co/docs/hub/model-repos#list-of-license-identifiers. Defaults to None. library_name (`str`, *optional*): Name of library used by this model. Example: keras or any library from https://github.com/huggingface/hub-docs/blob/main/js/src/lib/interfaces/Libraries.ts. Defaults to None. tags (`List[str]`, *optional*): List of tags to add to your model that can be used when filtering on the Hugging Face Hub. Defaults to None. datasets (`Union[str, List[str]]`, *optional*): Dataset or list of datasets that were used to train this model. Should be a dataset ID found on https://hf.co/datasets. Defaults to None. metrics (`Union[str, List[str]]`, *optional*): List of metrics used to evaluate this model. Should be a metric name that can be found at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. eval_results (`Union[List[EvalResult], EvalResult]`, *optional*): List of `modelcards.EvalResult` that define evaluation results of the model. If provided, `model_name` kwarg must be provided. Defaults to `None`. model_name (`str`, *optional*): A name for this model. Required if you provide `eval_results`. It is used along with `eval_results` to construct the `model-index` within the card's metadata. The name you supply here is what will be used on PapersWithCode's leaderboards. Defaults to None. kwargs (`dict`, *optional*): Additional metadata that will be added to the model card. Defaults to None. Example: >>> from modelcards.card_data import CardData >>> card_data = CardData( ... language="en", ... license="mit", ... library_name="timm", ... tags=['image-classification', 'resnet'], ... ) >>> card_data.to_dict() {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']} """ self.language = language self.license = license self.library_name = library_name self.tags = tags self.datasets = datasets self.metrics = metrics self.eval_results = eval_results self.model_name = model_name self.__dict__.update(kwargs) if self.eval_results: if type(self.eval_results) == EvalResult: self.eval_results = [self.eval_results] if self.model_name is None: raise ValueError("`eval_results` requires `model_name` to be set.")
(self, language: Union[str, List[str], NoneType] = None, license: Optional[str] = None, library_name: Optional[str] = None, tags: Optional[List[str]] = None, datasets: Union[str, List[str], NoneType] = None, metrics: Union[str, List[str], NoneType] = None, eval_results: Optional[List[modelcards.card_data.EvalResult]] = None, model_name: Optional[str] = None, **kwargs)
57,921
modelcards.card_data
__repr__
null
def __repr__(self): return self.to_yaml()
(self)
57,922
modelcards.card_data
to_dict
Converts CardData to a dict. It also formats the internal eval_results to be compatible with the model-index format. Returns: `dict`: CardData represented as a dictionary ready to be dumped to a YAML block for inclusion in a README.md file.
def to_dict(self): """Converts CardData to a dict. It also formats the internal eval_results to be compatible with the model-index format. Returns: `dict`: CardData represented as a dictionary ready to be dumped to a YAML block for inclusion in a README.md file. """ data_dict = copy.deepcopy(self.__dict__) if self.eval_results is not None: data_dict["model-index"] = eval_results_to_model_index( self.model_name, self.eval_results ) del data_dict["eval_results"], data_dict["model_name"] return _remove_none(data_dict)
(self)
57,923
modelcards.card_data
to_yaml
Dumps CardData to a YAML block for inclusion in a README.md file.
def to_yaml(self): """Dumps CardData to a YAML block for inclusion in a README.md file.""" return yaml.dump(self.to_dict(), sort_keys=False).strip()
(self)
57,924
modelcards.card_data
EvalResult
Flattened representation of individual evaluation results found in model-index.
class EvalResult: """ Flattened representation of individual evaluation results found in model-index. """ # Required # The task identifier # Example: automatic-speech-recognition task_type: str # The dataset identifier # Example: common_voice. Use dataset id from https://hf.co/datasets dataset_type: str # A pretty name for the dataset. # Example: Common Voice (French) dataset_name: str # The metric identifier # Example: wer. Use metric id from https://hf.co/metrics metric_type: str # Value of the metric. # Example: 20.0 or "20.0 ± 1.2" metric_value: Any # Optional # A pretty name for the task. # Example: Speech Recognition task_name: Optional[str] = None # The name of the dataset configuration used in `load_dataset()`. # Example: fr in `load_dataset("common_voice", "fr")`. # See the `datasets` docs for more info: # https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name dataset_config: Optional[str] = None # The split used in `load_dataset()`. # Example: test dataset_split: Optional[str] = None # The revision (AKA Git Sha) of the dataset used in `load_dataset()`. # Example: 5503434ddd753f426f4b38109466949a1217c2bb dataset_revision: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 dataset_args: Optional[Dict[str, Any]] = None # A pretty name for the metric. # Example: Test WER metric_name: Optional[str] = None # The name of the metric configuration used in `load_metric()`. # Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. # See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations metric_config: Optional[str] = None # The arguments passed during `Metric.compute()`. # Example for `bleu`: max_order: 4 metric_args: Optional[Dict[str, Any]] = None # If true, indicates that evaluation was generated by Hugging Face (vs. self-reported). verified: Optional[bool] = None
(task_type: str, dataset_type: str, dataset_name: str, metric_type: str, metric_value: Any, task_name: Optional[str] = None, dataset_config: Optional[str] = None, dataset_split: Optional[str] = None, dataset_revision: Optional[str] = None, dataset_args: Optional[Dict[str, Any]] = None, metric_name: Optional[str] = None, metric_config: Optional[str] = None, metric_args: Optional[Dict[str, Any]] = None, verified: Optional[bool] = None) -> None
57,927
modelcards.card_data
__repr__
null
def model_index_to_eval_results(model_index: List[Dict[str, Any]]): """Takes in a model index and returns a list of `modelcards.EvalResult` objects. A detailed spec of the model index can be found here: https://github.com/huggingface/hub-docs/blob/main/modelcard.md Args: model_index (`List[Dict[str, Any]]`): A model index data structure, likely coming from a README.md file on the Hugging Face Hub. Returns: - model_name (`str`): The name of the model as found in the model index. This is used as the identifier for the model on leaderboards like PapersWithCode. - eval_results (`List[EvalResult]`): A list of `modelcards.EvalResult` objects containing the metrics reported in the provided model_index. Example: >>> from modelcards.card_data import model_index_to_eval_results >>> # Define a minimal model index >>> model_index = [ ... { ... "name": "my-cool-model", ... "results": [ ... { ... "task": { ... "type": "image-classification" ... }, ... "dataset": { ... "type": "beans", ... "name": "Beans" ... }, ... "metrics": [ ... { ... "type": "accuracy", ... "value": 0.9 ... } ... ] ... } ... ] ... } ... ] >>> model_name, eval_results = model_index_to_eval_results(model_index) >>> model_name 'my-cool-model' >>> eval_results[0].task_type 'image-classification' >>> eval_results[0].metric_type 'accuracy' """ eval_results = [] for elem in model_index: name = elem["name"] results = elem["results"] for result in results: task_type = result["task"]["type"] task_name = result["task"].get("name") dataset_type = result["dataset"]["type"] dataset_name = result["dataset"]["name"] dataset_config = result["dataset"].get("config") dataset_split = result["dataset"].get("split") dataset_revision = result["dataset"].get("revision") dataset_args = result["dataset"].get("args") for metric in result["metrics"]: metric_type = metric["type"] metric_value = metric["value"] metric_name = metric.get("name") metric_args = metric.get("args") verified = metric.get("verified") eval_result = EvalResult( task_type=task_type, # Required dataset_type=dataset_type, # Required dataset_name=dataset_name, # Required metric_type=metric_type, # Required metric_value=metric_value, # Required task_name=task_name, dataset_config=dataset_config, dataset_split=dataset_split, dataset_revision=dataset_revision, dataset_args=dataset_args, metric_name=metric_name, metric_args=metric_args, verified=verified, ) eval_results.append(eval_result) return name, eval_results
(self)
57,928
modelcards.cards
ModelCard
null
class ModelCard(RepoCard): @classmethod def from_template( cls, card_data: CardData, template_path: Optional[str] = TEMPLATE_MODELCARD_PATH, **template_kwargs, ): """Initialize a ModelCard from a template. By default, it uses the default template. Templates are Jinja2 templates that can be customized by passing keyword arguments. Args: card_data (`modelcards.CardData`): A modelcards.CardData instance containing the metadata you want to include in the YAML header of the model card on the Hugging Face Hub. template_path (`str`, *optional*): A path to a markdown file with optional Jinja template variables that can be filled in with `template_kwargs`. Defaults to the default template which can be found here: https://github.com/nateraw/modelcards/blob/main/modelcards/modelcard_template.md Returns: `modelcards.ModelCard`: A ModelCard instance with the specified card data and content from the template. Example: >>> from modelcards import ModelCard, CardData, EvalResult >>> # Using the Default Template >>> card_data = CardData( ... language='en', ... license='mit', ... library_name='timm', ... tags=['image-classification', 'resnet'], ... datasets='beans', ... metrics=['accuracy'], ... ) >>> card = ModelCard.from_template( ... card_data, ... model_description='This model does x + y...' ... ) >>> # Including Evaluation Results >>> card_data = CardData( ... language='en', ... tags=['image-classification', 'resnet'], ... eval_results=[ ... EvalResult( ... task_type='image-classification', ... dataset_type='beans', ... dataset_name='Beans', ... metric_type='accuracy', ... metric_value=0.9, ... ), ... ], ... model_name='my-cool-model', ... ) >>> card = ModelCard.from_template(card_data) >>> # Using a Custom Template >>> card_data = CardData( ... language='en', ... tags=['image-classification', 'resnet'] ... ) >>> card = ModelCard.from_template( ... card_data=card_data, ... template_path='./modelcards/modelcard_template.md', ... custom_template_var='custom value', # will be replaced in template if it exists ... ) """ content = jinja2.Template(Path(template_path).read_text()).render( card_data=card_data.to_yaml(), **template_kwargs ) return cls(content)
(content: str)
57,929
modelcards.cards
__init__
Initialize a RepoCard from string content. The content should be a Markdown file with a YAML block at the beginning and a Markdown body. Args: content (`str`): The content of the Markdown file. Raises: ValueError: When the content of the repo card metadata is not found. ValueError: When the content of the repo card metadata is not a dictionary.
def __init__(self, content: str): """Initialize a RepoCard from string content. The content should be a Markdown file with a YAML block at the beginning and a Markdown body. Args: content (`str`): The content of the Markdown file. Raises: ValueError: When the content of the repo card metadata is not found. ValueError: When the content of the repo card metadata is not a dictionary. """ self.content = content match = REGEX_YAML_BLOCK.search(content) if match: # Metadata found in the YAML block yaml_block = match.group(1) self.text = match.group(2) data_dict = yaml.safe_load(yaml_block) # The YAML block's data should be a dictionary if not isinstance(data_dict, dict): raise ValueError("repo card metadata block should be a dict") else: # Model card without metadata... create empty metadata logger.warning( "Repo card metadata block was not found. Setting CardData to empty." ) data_dict = {} self.text = content model_index = data_dict.pop("model-index", None) if model_index: try: model_name, eval_results = model_index_to_eval_results(model_index) data_dict["model_name"] = model_name data_dict["eval_results"] = eval_results except KeyError: logger.warning( "Invalid model-index. Not loading eval results into CardData." ) self.data = CardData(**data_dict)
(self, content: str)
57,930
modelcards.cards
__str__
null
def __str__(self): return f"---\n{self.data.to_yaml()}\n---\n{self.text}"
(self)
57,931
modelcards.cards
push_to_hub
Push a RepoCard to a Hugging Face Hub repo. Args: repo_id (`str`): The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". token (`str`, *optional*): Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". commit_message (`str`, *optional*): The summary / title / first line of the generated commit commit_description (`str`, *optional*) The description of the generated commit revision (`str`, *optional*): The git revision to commit from. Defaults to the head of the `"main"` branch. create_pr (`bool`, *optional*): Whether or not to create a Pull Request with this commit. Defaults to `False`. Returns: `str`: URL of the commit which updated the card metadata.
def push_to_hub( self, repo_id, token=None, repo_type=None, commit_message=None, commit_description=None, revision=None, create_pr=None, ): """Push a RepoCard to a Hugging Face Hub repo. Args: repo_id (`str`): The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". token (`str`, *optional*): Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". commit_message (`str`, *optional*): The summary / title / first line of the generated commit commit_description (`str`, *optional*) The description of the generated commit revision (`str`, *optional*): The git revision to commit from. Defaults to the head of the `"main"` branch. create_pr (`bool`, *optional*): Whether or not to create a Pull Request with this commit. Defaults to `False`. Returns: `str`: URL of the commit which updated the card metadata. """ repo_name = repo_id.split("/")[-1] if self.data.model_name and self.data.model_name != repo_name: logger.warning( f"Set model name {self.data.model_name} in CardData does not match " f"repo name {repo_name}. Updating model name to match repo name." ) self.data.model_name = repo_name # Validate card before pushing to hub self.validate(repo_type=repo_type) with tempfile.TemporaryDirectory() as tmpdir: tmp_path = Path(tmpdir) / "README.md" tmp_path.write_text(str(self)) url = upload_file( path_or_fileobj=str(tmp_path), path_in_repo="README.md", repo_id=repo_id, token=token, repo_type=repo_type, identical_ok=True, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, revision=revision, ) return url
(self, repo_id, token=None, repo_type=None, commit_message=None, commit_description=None, revision=None, create_pr=None)
57,932
modelcards.cards
save
Save a RepoCard to a file. Args: filepath (`Union[Path, str]`): Filepath to the markdown file to save. Example: >>> from modelcards import RepoCard >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") >>> card.save("/tmp/test.md")
def save(self, filepath: Union[Path, str]): r"""Save a RepoCard to a file. Args: filepath (`Union[Path, str]`): Filepath to the markdown file to save. Example: >>> from modelcards import RepoCard >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") >>> card.save("/tmp/test.md") """ filepath = Path(filepath) filepath.parent.mkdir(parents=True, exist_ok=True) filepath.write_text(str(self), encoding="utf-8")
(self, filepath: Union[pathlib.Path, str])
57,933
modelcards.cards
validate
Validates card against Hugging Face Hub's model card validation logic. Using this function requires access to the internet, so it is only called internally by `modelcards.ModelCard.push_to_hub`. Args: repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space".
def validate(self, repo_type="model"): """Validates card against Hugging Face Hub's model card validation logic. Using this function requires access to the internet, so it is only called internally by `modelcards.ModelCard.push_to_hub`. Args: repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". """ if repo_type is None: repo_type = "model" # TODO - compare against repo types constant in huggingface_hub if we move this object there. if repo_type not in ["model", "space", "dataset"]: raise RuntimeError( "Provided repo_type '{repo_type}' should be one of ['model', 'space'," " 'dataset']." ) body = { "repoType": repo_type, "content": str(self), } headers = {"Accept": "text/plain"} try: r = requests.post( "https://huggingface.co/api/validate-yaml", body, headers=headers ) r.raise_for_status() except requests.exceptions.HTTPError as exc: if r.status_code == 400: raise RuntimeError(r.text) else: raise exc
(self, repo_type='model')
57,934
modelcards.cards
RepoCard
null
class RepoCard: def __init__(self, content: str): """Initialize a RepoCard from string content. The content should be a Markdown file with a YAML block at the beginning and a Markdown body. Args: content (`str`): The content of the Markdown file. Raises: ValueError: When the content of the repo card metadata is not found. ValueError: When the content of the repo card metadata is not a dictionary. """ self.content = content match = REGEX_YAML_BLOCK.search(content) if match: # Metadata found in the YAML block yaml_block = match.group(1) self.text = match.group(2) data_dict = yaml.safe_load(yaml_block) # The YAML block's data should be a dictionary if not isinstance(data_dict, dict): raise ValueError("repo card metadata block should be a dict") else: # Model card without metadata... create empty metadata logger.warning( "Repo card metadata block was not found. Setting CardData to empty." ) data_dict = {} self.text = content model_index = data_dict.pop("model-index", None) if model_index: try: model_name, eval_results = model_index_to_eval_results(model_index) data_dict["model_name"] = model_name data_dict["eval_results"] = eval_results except KeyError: logger.warning( "Invalid model-index. Not loading eval results into CardData." ) self.data = CardData(**data_dict) def __str__(self): return f"---\n{self.data.to_yaml()}\n---\n{self.text}" def save(self, filepath: Union[Path, str]): r"""Save a RepoCard to a file. Args: filepath (`Union[Path, str]`): Filepath to the markdown file to save. Example: >>> from modelcards import RepoCard >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") >>> card.save("/tmp/test.md") """ filepath = Path(filepath) filepath.parent.mkdir(parents=True, exist_ok=True) filepath.write_text(str(self), encoding="utf-8") @classmethod def load(cls, repo_id_or_path: Union[str, Path], repo_type=None, token=None): """Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath. Args: repo_id_or_path (`Union[str, Path]`): The repo ID associated with a Hugging Face Hub repo or a local filepath. repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". token (`str`, *optional*): Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. Returns: `modelcards.RepoCard`: The RepoCard (or subclass) initialized from the repo's README.md file or filepath. Example: >>> from modelcards import RepoCard >>> card = RepoCard.load("nateraw/food") >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"] """ if Path(repo_id_or_path).exists(): card_path = Path(repo_id_or_path) else: card_path = hf_hub_download( repo_id_or_path, "README.md", repo_type=repo_type, use_auth_token=token ) return cls(Path(card_path).read_text(encoding="utf-8")) def validate(self, repo_type="model"): """Validates card against Hugging Face Hub's model card validation logic. Using this function requires access to the internet, so it is only called internally by `modelcards.ModelCard.push_to_hub`. Args: repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". """ if repo_type is None: repo_type = "model" # TODO - compare against repo types constant in huggingface_hub if we move this object there. if repo_type not in ["model", "space", "dataset"]: raise RuntimeError( "Provided repo_type '{repo_type}' should be one of ['model', 'space'," " 'dataset']." ) body = { "repoType": repo_type, "content": str(self), } headers = {"Accept": "text/plain"} try: r = requests.post( "https://huggingface.co/api/validate-yaml", body, headers=headers ) r.raise_for_status() except requests.exceptions.HTTPError as exc: if r.status_code == 400: raise RuntimeError(r.text) else: raise exc def push_to_hub( self, repo_id, token=None, repo_type=None, commit_message=None, commit_description=None, revision=None, create_pr=None, ): """Push a RepoCard to a Hugging Face Hub repo. Args: repo_id (`str`): The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". token (`str`, *optional*): Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. repo_type (`str`, *optional*): The type of Hugging Face repo to push to. Defaults to None, which will use use "model". Other options are "dataset" and "space". commit_message (`str`, *optional*): The summary / title / first line of the generated commit commit_description (`str`, *optional*) The description of the generated commit revision (`str`, *optional*): The git revision to commit from. Defaults to the head of the `"main"` branch. create_pr (`bool`, *optional*): Whether or not to create a Pull Request with this commit. Defaults to `False`. Returns: `str`: URL of the commit which updated the card metadata. """ repo_name = repo_id.split("/")[-1] if self.data.model_name and self.data.model_name != repo_name: logger.warning( f"Set model name {self.data.model_name} in CardData does not match " f"repo name {repo_name}. Updating model name to match repo name." ) self.data.model_name = repo_name # Validate card before pushing to hub self.validate(repo_type=repo_type) with tempfile.TemporaryDirectory() as tmpdir: tmp_path = Path(tmpdir) / "README.md" tmp_path.write_text(str(self)) url = upload_file( path_or_fileobj=str(tmp_path), path_in_repo="README.md", repo_id=repo_id, token=token, repo_type=repo_type, identical_ok=True, commit_message=commit_message, commit_description=commit_description, create_pr=create_pr, revision=revision, ) return url
(content: str)
57,944
toyplot.canvas
Canvas
Top-level container for Toyplot drawings. Parameters ---------- width: number, string, or (number, string) tuple, optional Width of the canvas. Assumes CSS pixels if units aren't provided. Defaults to 600px (6.25") if unspecified. See :ref:`units` for details on how Toyplot handles real world units. height: number, string, or (number, string) tuple, optional Height of the canvas. Assumes CSS pixels if units aren't provided. Defaults to the canvas width if unspecified. See :ref:`units` for details on how Toyplot handles real world units. style: dict, optional Collection of CSS styles to apply to the canvas. hyperlink: string, optional When specified, the entire canvas is hyperlinked to the given URI. Note that hyperlinks set on other entities (such as axes, marks, or text) will override this. autorender: boolean, optional Turn autorendering on / off for this canvas. Defaults to the value in :data:`toyplot.config.autorender`. autoformat: string, optional Specify the format ("html" or "png") to be used for autorendering this canvas. Defaults to the value in :data:`toyplot.config.autoformat`. Examples -------- The following would create a Canvas 8 inches wide and 6 inches tall, with a yellow background: >>> canvas = toyplot.Canvas("8in", "6in", style={"background-color":"yellow"})
class Canvas(object): """Top-level container for Toyplot drawings. Parameters ---------- width: number, string, or (number, string) tuple, optional Width of the canvas. Assumes CSS pixels if units aren't provided. Defaults to 600px (6.25") if unspecified. See :ref:`units` for details on how Toyplot handles real world units. height: number, string, or (number, string) tuple, optional Height of the canvas. Assumes CSS pixels if units aren't provided. Defaults to the canvas width if unspecified. See :ref:`units` for details on how Toyplot handles real world units. style: dict, optional Collection of CSS styles to apply to the canvas. hyperlink: string, optional When specified, the entire canvas is hyperlinked to the given URI. Note that hyperlinks set on other entities (such as axes, marks, or text) will override this. autorender: boolean, optional Turn autorendering on / off for this canvas. Defaults to the value in :data:`toyplot.config.autorender`. autoformat: string, optional Specify the format ("html" or "png") to be used for autorendering this canvas. Defaults to the value in :data:`toyplot.config.autoformat`. Examples -------- The following would create a Canvas 8 inches wide and 6 inches tall, with a yellow background: >>> canvas = toyplot.Canvas("8in", "6in", style={"background-color":"yellow"}) """ class _AnimationChanges(object): def __init__(self): self._begin = [] self._end = [] self._change = [] self._state = [] def add(self, begin, end, change, state): self._begin.append(begin) self._end.append(end) self._change.append(change) self._state.append(state) def __init__(self, width=None, height=None, style=None, hyperlink=None, autorender=None, autoformat=None): if width is None: width = toyplot.config.width if height is None: height = toyplot.config.height self._width = toyplot.units.convert(width, "px", default="px") if width is not None else 600 self._height = toyplot.units.convert(height, "px", default="px") if height is not None else self._width self._hyperlink = None self._style = { "background-color": "transparent", "border-color": toyplot.color.black, "border-style": "none", "border-width": 1.0, "fill": toyplot.color.black, "fill-opacity": 1.0, "font-family": "Helvetica", "font-size": "12px", "opacity": 1.0, "stroke": toyplot.color.black, "stroke-opacity": 1.0, "stroke-width": 1.0, } self.hyperlink = hyperlink self.style = style self._changes = toyplot.Canvas._AnimationChanges() self._scenegraph = toyplot.scenegraph.SceneGraph() self.autorender(autorender, autoformat) def _repr_html_(self): from . import html return toyplot.html.tostring(self, style={"text-align":"center"}) def _repr_png_(self): from . import png return toyplot.png.render(self) @property def height(self): """Height of the canvas in CSS pixels.""" return self._height @height.setter def height(self, value): self._height = toyplot.units.convert(value, "px", default="px") @property def hyperlink(self): """URI that will be hyperlinked from the entire canvas.""" return self._hyperlink @hyperlink.setter def hyperlink(self, value): self._hyperlink = toyplot.require.hyperlink(value) @property def style(self): """Collection of CSS styles that will be applied to the canvas.""" return self._style @style.setter def style(self, value): self._style = toyplot.style.combine( self._style, toyplot.style.require(value, allowed=set(["background-color", "border-color", "border-style", "border-width"])), ) @property def width(self): """Width of the canvas in CSS pixels.""" return self._width @width.setter def width(self, value): self._width = toyplot.units.convert(value, "px", default="px") def frame(self, begin, end=None, number=None, count=None): """Return a single animation frame that can be used to animate the canvas contents. Parameters ---------- begin: float Specify the frame start time (in seconds). end: float, optional Specify the frame end time (in seconds). number: integer, optional Specify a number for this frame. count: integer, optional Specify the total number of frames of which this frame is one. Returns ------- frame: :class:`toyplot.canvas.AnimationFrame` instance. """ if end is None: end = begin + (1.0 / 30.0) if number is None: number = 0 if count is None: count = 1 return AnimationFrame(changes=self._changes, count=count, number=number, begin=begin, end=end) def frames(self, frames): """Return a sequence of animation frames that can be used to animate the canvas contents. Parameters ---------- frames: integer, tuple, or sequence Pass a sequence of values that specify the time (in seconds) of the beginning / end of each frame. Note that the number of frames will be the length of the sequence minus one. Alternatively, you can pass a 2-tuple containing the number of frames and the frame rate in frames-per-second. Finally, you may simply specify the number of frames, in which case the rate will default to 30 frames-per-second. Yields ------ frames: :class:`toyplot.canvas.AnimationFrame` Use the methods and properties of each frame object to modify the state of the canvas over time. """ if isinstance(frames, numbers.Integral): frames = (frames, 30.0) if isinstance(frames, tuple): frame_count, frame_rate = frames times = numpy.linspace(0, frame_count / frame_rate, frame_count + 1, endpoint=True) for index, (begin, end) in enumerate(zip(times[:-1], times[1:])): yield AnimationFrame(changes=self._changes, count=frame_count, number=index, begin=begin, end=end) def animation(self): """Return a summary of the canvas animation state. Returns ------- begin: float Start-time of the animation in seconds. end: float End-time of the animation in seconds. changes: object Opaque collection of data structures that describe changes to the canvas state during animation (if any). """ begin = 0.0 end = numpy.max(self._changes._end) if self._changes._end else 0.0 changes = collections.defaultdict(lambda: collections.defaultdict(list)) for begin, change, state in zip(self._changes._begin, self._changes._change, self._changes._state): changes[begin][change].append(state) return begin, end, changes def autorender(self, enable=None, autoformat=None): """Enable / disable canvas autorendering. Autorendering - which is enabled by default when a canvas is created - controls how the canvas should be displayed automatically without caller intervention in certain interactive environments, such as Jupyter notebooks. Note that autorendering is disabled when a canvas is explicitly shown using any of the rendering backends. Parameters ---------- enable: boolean, optional Turn autorendering on / off for this canvas. Defaults to the value in :data:`toyplot.config.autorender`. format: string, optional Specify the format ("html" or "png") to be used for autorendering this canvas. Defaults to the value in :data:`toyplot.config.autoformat`. """ if enable is None: enable = toyplot.config.autorender if autoformat is None: autoformat = toyplot.config.autoformat Canvas._autorender = [entry for entry in Canvas._autorender if entry[0] != self] if enable: Canvas._autorender.append((self, autoformat)) def cartesian( self, aspect=None, bounds=None, corner=None, grid=None, hyperlink=None, label=None, margin=50, padding=10, palette=None, rect=None, show=True, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, xticklocator=None, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, yticklocator=None, ): """Add a set of Cartesian axes to the canvas. See Also -------- :ref:`cartesian-coordinates` Parameters ---------- aspect: string, optional Set to "fit-range" to automatically expand the domain so that its aspect ratio matches the aspect ratio of the range. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the axes by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the axes by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the axes using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. hyperlink: string, optional When specified, the range (content area of the axes) is hyperlinked to the given URI. Note that this overrides the canvas hyperlink, if any, and is overridden by hyperlinks set on other entities such as marks or text. label: string, optional Human-readable axes label. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the axes contents and the containing grid cell When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`. padding: number, string, or (number, string) tuple, optional Distance between the axes and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. palette: :class:`toyplot.color.Palette`, optional Specifies a palette to be used when automatically assigning per-series colors. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the axes by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. show: bool, optional Set to `False` to hide the axes (the axes contents will still be visible). xmin, xmax, ymin, ymax: float, optional Used to explicitly override the axis domain (normally, the domain is implicitly defined by the marks added to the axes). xshow, yshow: bool, optional Set to `False` to hide individual axes. xlabel, ylabel: string, optional Human-readable axis labels. xticklocator, yticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. xscale, yscale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. See :ref:`log-scales` for examples. Returns ------- axes: :class:`toyplot.coordinates.Cartesian` """ xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) axes = toyplot.coordinates.Cartesian( aspect=aspect, hyperlink=hyperlink, label=label, padding=padding, palette=palette, scenegraph=self._scenegraph, show=show, xaxis=None, xlabel=xlabel, xmax=xmax, xmax_range=xmax_range, xmin=xmin, xmin_range=xmin_range, xscale=xscale, xshow=xshow, xticklocator=xticklocator, ylabel=ylabel, yaxis=None, ymax=ymax, ymax_range=ymax_range, ymin=ymin, ymin_range=ymin_range, yscale=yscale, yshow=yshow, yticklocator=yticklocator, ) self._scenegraph.add_edge(self, "render", axes) return axes def legend( self, entries, bounds=None, corner=None, grid=None, label=None, margin=50, rect=None, ): """Add a legend to the canvas. See Also -------- :ref:`labels-and-legends` Parameters ---------- entries: sequence of entries to add to the legend Each entry to be displayed in the legend must be either a (label, mark) tuple or a (label, marker) tuple. Labels are human-readable text, markers are specified using the syntax described in :ref:`markers`, and marks can be any instance of :class:`toyplot.mark.Mark`. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the legend. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between legend and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". Returns ------- legend: :class:`toyplot.coordinates.Table` """ xmin, xmax, ymin, ymax = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, corner=corner, grid=grid, margin=margin, rect=rect, ) table = toyplot.coordinates.Table( annotation=True, brows=0, columns=2, filename=None, label=label, lcolumns=0, scenegraph=self._scenegraph, rcolumns=0, rows=len(entries), trows=0, xmax_range=xmax, xmin_range=xmin, ymax_range=ymax, ymin_range=ymin, ) table.cells.column[0].align = "right" table.cells.column[1].align = "left" for index, (label, spec) in enumerate(entries): # pylint: disable=redefined-argument-from-local if isinstance(spec, toyplot.mark.Mark): markers = spec.markers else: markers = [toyplot.marker.convert(spec)] text = "" for marker in markers: if text: text = text + " " text = text + marker table.cells.cell[index, 0].data = text table.cells.cell[index, 1].data = label self._scenegraph.add_edge(self, "render", table) return table def matrix( self, data, blabel=None, blocator=None, bounds=None, bshow=None, colorshow=False, corner=None, filename=None, grid=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rect=None, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None, ): """Add a matrix visualization to the canvas. See Also -------- :ref:`matrix-visualization` Parameters ---------- data: matrix, or (matrix, :class:`toyplot.color.Map`) tuple, required The given data will be used to populate the visualization, using either the given colormap or a default. blabel: str, optional Human readable label along the bottom of the matrix. blocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the bottom of the matrix. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". bshow: bool, optional Set to `False` to hide column labels along the bottom of the matrix. colorshow: bool, optional Set to `True` to add a color scale to the visualization. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. filename: str, optional Supplies a default filename for users who choose to download the matrix contents. Note that users and web browsers are free to ignore or override this. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the matrix. llabel: str, optional Human readable label along the left side of the matrix. llocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the left side of the matrix. lshow: bool, optional Set to `False` to hide row labels along the left side of the matrix. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the matrix and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". rlabel: str, optional Human readable label along the right side of the matrix. rlocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the right side of the matrix. rshow: bool, optional Set to `False` to hide row labels along the right side of the matrix. step: integer, optional Specifies the number of rows or columns to skip between indices. This is useful when the matrix cells become too small relative to the index text. tlabel: str, optional Human readable label along the top of the matrix. tlocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the top of the matrix. tshow: bool, optional Set to `False` to hide column labels along the top of the matrix. Returns ------- axes: :class:`toyplot.coordinates.Table` """ if isinstance(data, tuple): matrix = toyplot.require.scalar_matrix(data[0]) colormap = toyplot.require.instance(data[1], toyplot.color.Map) else: matrix = toyplot.require.scalar_matrix(data) colormap = toyplot.color.brewer.map("BlueRed", domain_min=matrix.min(), domain_max=matrix.max()) colors = colormap.colors(matrix) xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin) table = toyplot.coordinates.Table( annotation=False, brows=2, columns=matrix.shape[1], filename=filename, label=label, lcolumns=2, scenegraph=self._scenegraph, rcolumns=2, rows=matrix.shape[0], trows=2, xmax_range=xmax_range, xmin_range=xmin_range, ymax_range=ymax_range, ymin_range=ymin_range, ) table.top.row[[0, 1]].height = 20 table.bottom.row[[0, 1]].height = 20 table.left.column[[0, 1]].width = 20 table.right.column[[0, 1]].width = 20 table.left.column[1].align = "right" table.right.column[0].align = "left" table.cells.column[[0, -1]].lstyle = {"font-weight":"bold"} table.cells.row[[0, -1]].lstyle = {"font-weight":"bold"} if tlabel is not None: cell = table.top.row[0].merge() cell.data = tlabel if llabel is not None: cell = table.left.column[0].merge() cell.data = llabel cell.angle = 90 if rlabel is not None: cell = table.right.column[1].merge() cell.data = rlabel cell.angle = 90 if blabel is not None: cell = table.bottom.row[1].merge() cell.data = blabel if tshow is None: tshow = True if tshow: if tlocator is None: tlocator = toyplot.locator.Integer(step=step) for j, label, title in zip(*tlocator.ticks(0, matrix.shape[1] - 1)): # pylint: disable=redefined-argument-from-local table.top.cell[1, int(j)].data = label #table.top.cell[1, j].title = title if lshow is None: lshow = True if lshow: if llocator is None: llocator = toyplot.locator.Integer(step=step) for i, label, title in zip(*llocator.ticks(0, matrix.shape[0] - 1)): # pylint: disable=redefined-argument-from-local table.left.cell[int(i), 1].data = label #table.left.cell[i, 1].title = title if rshow is None and rlocator is not None: rshow = True if rshow: if rlocator is None: rlocator = toyplot.locator.Integer(step=step) for i, label, title in zip(*rlocator.ticks(0, matrix.shape[0] - 1)): # pylint: disable=redefined-argument-from-local table.right.cell[int(i), 0].data = label #table.right.cell[i, 0].title = title if bshow is None and blocator is not None: bshow = True if bshow: if blocator is None: blocator = toyplot.locator.Integer(step=step) for j, label, title in zip(*blocator.ticks(0, matrix.shape[1] - 1)): # pylint: disable=redefined-argument-from-local table.bottom.cell[0, int(j)].data = label #table.bottom.cell[0, j].title = title table.body.cells.data = matrix table.body.cells.format = toyplot.format.NullFormatter() for i in numpy.arange(matrix.shape[0]): for j in numpy.arange(matrix.shape[1]): cell = table.body.cell[i, j] cell.style = {"stroke": "none", "fill": toyplot.color.to_css(colors[i, j])} cell.title = "%.6f" % matrix[i, j] self._scenegraph.add_edge(self, "render", table) if colorshow: self.color_scale( colormap=colormap, x1=xmax_range, y1=ymax_range, x2=xmax_range, y2=ymin_range, width=10, padding=10, show=True, label="", ticklocator=None, scale="linear", ) return table def color_scale( self, colormap, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, offset=None, padding=10, rect=None, scale="linear", show=True, ticklocator=None, width=10, ): """Add a color scale to the canvas. The color scale displays a mapping from scalar values to colors, for the given colormap. Note that the supplied colormap must have an explicitly defined domain (specified when the colormap was created), otherwise the mapping would be undefined. Parameters ---------- colormap: :class:`toyplot.color.Map`, required Colormap to be displayed. min, max: float, optional Used to explicitly override the domain that will be shown. show: bool, optional Set to `False` to hide the axis (the color bar will still be visible). label: string, optional Human-readable label placed below the axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. Returns ------- axes: :class:`toyplot.coordinates.Numberline` """ axes = self.numberline( bounds=bounds, corner=corner, grid=grid, label=label, margin=margin, max=max, min=min, padding=padding, palette=None, rect=rect, scale=scale, show=show, ticklocator=ticklocator, x1=x1, x2=x2, y1=y1, y2=y2, ) axes.colormap( colormap=colormap, width=width, offset=offset, ) return axes def numberline( self, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, padding=None, palette=None, rect=None, scale="linear", show=True, spacing=None, ticklocator=None, ): """Add a 1D numberline to the canvas. Parameters ---------- min, max: float, optional Used to explicitly override the numberline domain (normally, the domain is implicitly defined by any marks added to the numberline). show: bool, optional Set to `False` to hide the numberline (the numberline contents will still be visible). label: string, optional Human-readable label placed below the numberline axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. See :ref:`tick-locators`. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along the axis. See :ref:`log-scales`. spacing: number, string, or (number, string) tuple, optional Distance between plotted data added to the numberline. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. padding: number, string, or (number, string) tuple, optional Distance between the numberline axis and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. Defaults to the same value as `spacing`. Returns ------- axes: :class:`toyplot.coordinates.Cartesian` """ xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin) if x1 is None: x1 = xmin_range else: x1 = toyplot.units.convert(x1, target="px", default="px", reference=self._width) if x1 < 0: x1 = self._width + x1 if y1 is None: y1 = 0.5 * (ymin_range + ymax_range) else: y1 = toyplot.units.convert(y1, target="px", default="px", reference=self._height) if y1 < 0: y1 = self._height + y1 if x2 is None: x2 = xmax_range else: x2 = toyplot.units.convert(x2, target="px", default="px", reference=self._width) if x2 < 0: x2 = self._width + x2 if y2 is None: y2 = 0.5 * (ymin_range + ymax_range) else: y2 = toyplot.units.convert(y2, target="px", default="px", reference=self._height) if y2 < 0: y2 = self._height + y2 if spacing is None: spacing = 20 if padding is None: padding = spacing axes = toyplot.coordinates.Numberline( label=label, max=max, min=min, padding=padding, palette=palette, scenegraph=self._scenegraph, scale=scale, show=show, spacing=spacing, ticklocator=ticklocator, x1=x1, x2=x2, y1=y1, y2=y2, ) self._scenegraph.add_edge(self, "render", axes) return axes def table( self, data=None, rows=None, columns=None, annotation=False, bounds=None, brows=None, corner=None, filename=None, grid=None, label=None, lcolumns=None, margin=50, rcolumns=None, rect=None, trows=None, ): """Add a set of table axes to the canvas. Parameters ---------- Returns ------- axes: :class:`toyplot.coordinates.Table` """ if data is not None: data = toyplot.data.Table(data) rows = data.shape[0] if rows is None else max(rows, data.shape[0]) columns = data.shape[1] if columns is None else max( columns, data.shape[1]) if trows is None: trows = 1 if rows is None or columns is None: # pragma: no cover raise ValueError("You must specify data, or rows and columns.") if trows is None: trows = 0 if brows is None: brows = 0 if lcolumns is None: lcolumns = 0 if rcolumns is None: rcolumns = 0 xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) table = toyplot.coordinates.Table( annotation=annotation, brows=brows, columns=columns, filename=filename, label=label, lcolumns=lcolumns, scenegraph=self._scenegraph, rcolumns=rcolumns, rows=rows, trows=trows, xmax_range=xmax_range, xmin_range=xmin_range, ymax_range=ymax_range, ymin_range=ymin_range, ) if data is not None: for j, (key, column) in enumerate(data.items()): if trows: table.top.cell[trows - 1, j].data = key for i, (value, mask) in enumerate(zip(column, numpy.ma.getmaskarray(column))): if not mask: table.body.cell[i, j].data = value if issubclass(column._data.dtype.type, numpy.floating): if trows: table.top.cell[0, j].align = "center" table.body.cell[:, j].format = toyplot.format.FloatFormatter() table.body.cell[:, j].align = "separator" elif issubclass(column._data.dtype.type, numpy.character): table.cells.cell[:, j].align = "left" elif issubclass(column._data.dtype.type, numpy.integer): table.cells.cell[:, j].align = "right" if trows: # Format top cells for use as a header table.top.cells.lstyle = {"font-weight": "bold"} # Enable a single horizontal line between top and body. table.cells.grid.hlines[trows] = "single" self._scenegraph.add_edge(self, "render", table) return table def image( self, data, bounds=None, corner=None, grid=None, margin=50, rect=None, ): """Add an image to the canvas. Parameters ---------- data: image, or (image, colormap) tuple bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the image by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the image by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the image by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the image using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. margin: size of the margin around grid cells, optional Specifies the amount of empty space to leave between grid cells When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`. """ colormap = None if isinstance(data, tuple): data, colormap = data if not isinstance(colormap, toyplot.color.Map): raise ValueError("Expected toyplot.color.Map, received %s." % colormap) # pragma: no cover data = numpy.atleast_3d(data) if data.shape[2] != 1: raise ValueError("Expected an image with one channel.") # pragma: no cover data = colormap.colors(data) xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) mark = toyplot.mark.Image( xmin_range, xmax_range, ymin_range, ymax_range, data=data, ) self._scenegraph.add_edge(self, "render", mark) return mark def text( self, x, y, text, angle=0.0, fill=None, opacity=1.0, title=None, style=None): """Add text to the canvas. Parameters ---------- x, y: float Coordinates of the text anchor in canvas drawing units. Note that canvas Y coordinates increase from top-to-bottom. text: string The text to be displayed. title: string, optional Human-readable title for the mark. The SVG / HTML backends render the title as a tooltip. style: dict, optional Collection of CSS styles to apply to the mark. See :class:`toyplot.mark.Text` for a list of useful styles. Returns ------- text: :class:`toyplot.mark.Text` """ table = toyplot.data.Table() table["x"] = toyplot.require.scalar_vector(x) table["y"] = toyplot.require.scalar_vector(y, table.shape[0]) table["text"] = toyplot.broadcast.pyobject(text, table.shape[0]) table["angle"] = toyplot.broadcast.scalar(angle, table.shape[0]) table["fill"] = toyplot.broadcast.pyobject(fill, table.shape[0]) table["toyplot:fill"] = toyplot.color.broadcast( colors=fill, shape=(table.shape[0],), default=toyplot.color.black, ) table["opacity"] = toyplot.broadcast.scalar(opacity, table.shape[0]) table["title"] = toyplot.broadcast.pyobject(title, table.shape[0]) style = toyplot.style.require(style, allowed=toyplot.style.allowed.text) mark = toyplot.mark.Text( coordinate_axes=["x", "y"], table=table, coordinates=["x", "y"], text=["text"], angle=["angle"], fill=["toyplot:fill"], opacity=["opacity"], title=["title"], style=style, annotation=True, filename=None, ) self._scenegraph.add_edge(self, "render", mark) return mark def _point_scale(self, width=None, height=None, scale=None): """Return a scale factor to convert this canvas to a target width or height in points.""" if numpy.count_nonzero( [width is not None, height is not None, scale is not None]) > 1: raise ValueError("Specify only one of width, height, or scale.") # pragma: no cover if width is not None: scale = toyplot.units.convert( width, "pt") / toyplot.units.convert((self._width, "px"), "pt") elif height is not None: scale = toyplot.units.convert( height, "pt") / toyplot.units.convert((self._height, "px"), "pt") elif scale is None: scale = 1.0 scale *= 72.0 / 96.0 return scale @staticmethod def _ipython_post_execute(): # pragma: no cover try: import IPython.display for canvas, autoformat in Canvas._autorender: if autoformat == "html": IPython.display.display_html(canvas) elif autoformat == "png": IPython.display.display_png(canvas) except: pass @staticmethod def _ipython_register(): # pragma: no cover try: import IPython if IPython.get_ipython(): IPython.get_ipython().events.register( "post_execute", Canvas._ipython_post_execute) except: pass
(width=None, height=None, style=None, hyperlink=None, autorender=None, autoformat=None)
57,945
toyplot.canvas
__init__
null
def __init__(self, width=None, height=None, style=None, hyperlink=None, autorender=None, autoformat=None): if width is None: width = toyplot.config.width if height is None: height = toyplot.config.height self._width = toyplot.units.convert(width, "px", default="px") if width is not None else 600 self._height = toyplot.units.convert(height, "px", default="px") if height is not None else self._width self._hyperlink = None self._style = { "background-color": "transparent", "border-color": toyplot.color.black, "border-style": "none", "border-width": 1.0, "fill": toyplot.color.black, "fill-opacity": 1.0, "font-family": "Helvetica", "font-size": "12px", "opacity": 1.0, "stroke": toyplot.color.black, "stroke-opacity": 1.0, "stroke-width": 1.0, } self.hyperlink = hyperlink self.style = style self._changes = toyplot.Canvas._AnimationChanges() self._scenegraph = toyplot.scenegraph.SceneGraph() self.autorender(autorender, autoformat)
(self, width=None, height=None, style=None, hyperlink=None, autorender=None, autoformat=None)
57,946
toyplot.canvas
_ipython_post_execute
null
@staticmethod def _ipython_post_execute(): # pragma: no cover try: import IPython.display for canvas, autoformat in Canvas._autorender: if autoformat == "html": IPython.display.display_html(canvas) elif autoformat == "png": IPython.display.display_png(canvas) except: pass
()
57,947
toyplot.canvas
_ipython_register
null
@staticmethod def _ipython_register(): # pragma: no cover try: import IPython if IPython.get_ipython(): IPython.get_ipython().events.register( "post_execute", Canvas._ipython_post_execute) except: pass
()
57,948
toyplot.canvas
_point_scale
Return a scale factor to convert this canvas to a target width or height in points.
def _point_scale(self, width=None, height=None, scale=None): """Return a scale factor to convert this canvas to a target width or height in points.""" if numpy.count_nonzero( [width is not None, height is not None, scale is not None]) > 1: raise ValueError("Specify only one of width, height, or scale.") # pragma: no cover if width is not None: scale = toyplot.units.convert( width, "pt") / toyplot.units.convert((self._width, "px"), "pt") elif height is not None: scale = toyplot.units.convert( height, "pt") / toyplot.units.convert((self._height, "px"), "pt") elif scale is None: scale = 1.0 scale *= 72.0 / 96.0 return scale
(self, width=None, height=None, scale=None)
57,949
toyplot.canvas
_repr_html_
null
def _repr_html_(self): from . import html return toyplot.html.tostring(self, style={"text-align":"center"})
(self)
57,950
toyplot.canvas
_repr_png_
null
def _repr_png_(self): from . import png return toyplot.png.render(self)
(self)
57,951
toyplot.canvas
animation
Return a summary of the canvas animation state. Returns ------- begin: float Start-time of the animation in seconds. end: float End-time of the animation in seconds. changes: object Opaque collection of data structures that describe changes to the canvas state during animation (if any).
def animation(self): """Return a summary of the canvas animation state. Returns ------- begin: float Start-time of the animation in seconds. end: float End-time of the animation in seconds. changes: object Opaque collection of data structures that describe changes to the canvas state during animation (if any). """ begin = 0.0 end = numpy.max(self._changes._end) if self._changes._end else 0.0 changes = collections.defaultdict(lambda: collections.defaultdict(list)) for begin, change, state in zip(self._changes._begin, self._changes._change, self._changes._state): changes[begin][change].append(state) return begin, end, changes
(self)
57,952
toyplot.canvas
autorender
Enable / disable canvas autorendering. Autorendering - which is enabled by default when a canvas is created - controls how the canvas should be displayed automatically without caller intervention in certain interactive environments, such as Jupyter notebooks. Note that autorendering is disabled when a canvas is explicitly shown using any of the rendering backends. Parameters ---------- enable: boolean, optional Turn autorendering on / off for this canvas. Defaults to the value in :data:`toyplot.config.autorender`. format: string, optional Specify the format ("html" or "png") to be used for autorendering this canvas. Defaults to the value in :data:`toyplot.config.autoformat`.
def autorender(self, enable=None, autoformat=None): """Enable / disable canvas autorendering. Autorendering - which is enabled by default when a canvas is created - controls how the canvas should be displayed automatically without caller intervention in certain interactive environments, such as Jupyter notebooks. Note that autorendering is disabled when a canvas is explicitly shown using any of the rendering backends. Parameters ---------- enable: boolean, optional Turn autorendering on / off for this canvas. Defaults to the value in :data:`toyplot.config.autorender`. format: string, optional Specify the format ("html" or "png") to be used for autorendering this canvas. Defaults to the value in :data:`toyplot.config.autoformat`. """ if enable is None: enable = toyplot.config.autorender if autoformat is None: autoformat = toyplot.config.autoformat Canvas._autorender = [entry for entry in Canvas._autorender if entry[0] != self] if enable: Canvas._autorender.append((self, autoformat))
(self, enable=None, autoformat=None)
57,953
toyplot.canvas
cartesian
Add a set of Cartesian axes to the canvas. See Also -------- :ref:`cartesian-coordinates` Parameters ---------- aspect: string, optional Set to "fit-range" to automatically expand the domain so that its aspect ratio matches the aspect ratio of the range. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the axes by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the axes by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the axes using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. hyperlink: string, optional When specified, the range (content area of the axes) is hyperlinked to the given URI. Note that this overrides the canvas hyperlink, if any, and is overridden by hyperlinks set on other entities such as marks or text. label: string, optional Human-readable axes label. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the axes contents and the containing grid cell When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`. padding: number, string, or (number, string) tuple, optional Distance between the axes and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. palette: :class:`toyplot.color.Palette`, optional Specifies a palette to be used when automatically assigning per-series colors. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the axes by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. show: bool, optional Set to `False` to hide the axes (the axes contents will still be visible). xmin, xmax, ymin, ymax: float, optional Used to explicitly override the axis domain (normally, the domain is implicitly defined by the marks added to the axes). xshow, yshow: bool, optional Set to `False` to hide individual axes. xlabel, ylabel: string, optional Human-readable axis labels. xticklocator, yticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. xscale, yscale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. See :ref:`log-scales` for examples. Returns ------- axes: :class:`toyplot.coordinates.Cartesian`
def cartesian( self, aspect=None, bounds=None, corner=None, grid=None, hyperlink=None, label=None, margin=50, padding=10, palette=None, rect=None, show=True, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, xticklocator=None, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, yticklocator=None, ): """Add a set of Cartesian axes to the canvas. See Also -------- :ref:`cartesian-coordinates` Parameters ---------- aspect: string, optional Set to "fit-range" to automatically expand the domain so that its aspect ratio matches the aspect ratio of the range. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the axes by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the axes by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the axes using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. hyperlink: string, optional When specified, the range (content area of the axes) is hyperlinked to the given URI. Note that this overrides the canvas hyperlink, if any, and is overridden by hyperlinks set on other entities such as marks or text. label: string, optional Human-readable axes label. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the axes contents and the containing grid cell When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`. padding: number, string, or (number, string) tuple, optional Distance between the axes and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. palette: :class:`toyplot.color.Palette`, optional Specifies a palette to be used when automatically assigning per-series colors. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the axes by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. show: bool, optional Set to `False` to hide the axes (the axes contents will still be visible). xmin, xmax, ymin, ymax: float, optional Used to explicitly override the axis domain (normally, the domain is implicitly defined by the marks added to the axes). xshow, yshow: bool, optional Set to `False` to hide individual axes. xlabel, ylabel: string, optional Human-readable axis labels. xticklocator, yticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. xscale, yscale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. See :ref:`log-scales` for examples. Returns ------- axes: :class:`toyplot.coordinates.Cartesian` """ xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) axes = toyplot.coordinates.Cartesian( aspect=aspect, hyperlink=hyperlink, label=label, padding=padding, palette=palette, scenegraph=self._scenegraph, show=show, xaxis=None, xlabel=xlabel, xmax=xmax, xmax_range=xmax_range, xmin=xmin, xmin_range=xmin_range, xscale=xscale, xshow=xshow, xticklocator=xticklocator, ylabel=ylabel, yaxis=None, ymax=ymax, ymax_range=ymax_range, ymin=ymin, ymin_range=ymin_range, yscale=yscale, yshow=yshow, yticklocator=yticklocator, ) self._scenegraph.add_edge(self, "render", axes) return axes
(self, aspect=None, bounds=None, corner=None, grid=None, hyperlink=None, label=None, margin=50, padding=10, palette=None, rect=None, show=True, xlabel=None, xmax=None, xmin=None, xscale='linear', xshow=True, xticklocator=None, ylabel=None, ymax=None, ymin=None, yscale='linear', yshow=True, yticklocator=None)
57,954
toyplot.canvas
color_scale
Add a color scale to the canvas. The color scale displays a mapping from scalar values to colors, for the given colormap. Note that the supplied colormap must have an explicitly defined domain (specified when the colormap was created), otherwise the mapping would be undefined. Parameters ---------- colormap: :class:`toyplot.color.Map`, required Colormap to be displayed. min, max: float, optional Used to explicitly override the domain that will be shown. show: bool, optional Set to `False` to hide the axis (the color bar will still be visible). label: string, optional Human-readable label placed below the axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. Returns ------- axes: :class:`toyplot.coordinates.Numberline`
def color_scale( self, colormap, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, offset=None, padding=10, rect=None, scale="linear", show=True, ticklocator=None, width=10, ): """Add a color scale to the canvas. The color scale displays a mapping from scalar values to colors, for the given colormap. Note that the supplied colormap must have an explicitly defined domain (specified when the colormap was created), otherwise the mapping would be undefined. Parameters ---------- colormap: :class:`toyplot.color.Map`, required Colormap to be displayed. min, max: float, optional Used to explicitly override the domain that will be shown. show: bool, optional Set to `False` to hide the axis (the color bar will still be visible). label: string, optional Human-readable label placed below the axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along an axis. Returns ------- axes: :class:`toyplot.coordinates.Numberline` """ axes = self.numberline( bounds=bounds, corner=corner, grid=grid, label=label, margin=margin, max=max, min=min, padding=padding, palette=None, rect=rect, scale=scale, show=show, ticklocator=ticklocator, x1=x1, x2=x2, y1=y1, y2=y2, ) axes.colormap( colormap=colormap, width=width, offset=offset, ) return axes
(self, colormap, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, offset=None, padding=10, rect=None, scale='linear', show=True, ticklocator=None, width=10)
57,955
toyplot.canvas
frame
Return a single animation frame that can be used to animate the canvas contents. Parameters ---------- begin: float Specify the frame start time (in seconds). end: float, optional Specify the frame end time (in seconds). number: integer, optional Specify a number for this frame. count: integer, optional Specify the total number of frames of which this frame is one. Returns ------- frame: :class:`toyplot.canvas.AnimationFrame` instance.
def frame(self, begin, end=None, number=None, count=None): """Return a single animation frame that can be used to animate the canvas contents. Parameters ---------- begin: float Specify the frame start time (in seconds). end: float, optional Specify the frame end time (in seconds). number: integer, optional Specify a number for this frame. count: integer, optional Specify the total number of frames of which this frame is one. Returns ------- frame: :class:`toyplot.canvas.AnimationFrame` instance. """ if end is None: end = begin + (1.0 / 30.0) if number is None: number = 0 if count is None: count = 1 return AnimationFrame(changes=self._changes, count=count, number=number, begin=begin, end=end)
(self, begin, end=None, number=None, count=None)
57,956
toyplot.canvas
frames
Return a sequence of animation frames that can be used to animate the canvas contents. Parameters ---------- frames: integer, tuple, or sequence Pass a sequence of values that specify the time (in seconds) of the beginning / end of each frame. Note that the number of frames will be the length of the sequence minus one. Alternatively, you can pass a 2-tuple containing the number of frames and the frame rate in frames-per-second. Finally, you may simply specify the number of frames, in which case the rate will default to 30 frames-per-second. Yields ------ frames: :class:`toyplot.canvas.AnimationFrame` Use the methods and properties of each frame object to modify the state of the canvas over time.
def frames(self, frames): """Return a sequence of animation frames that can be used to animate the canvas contents. Parameters ---------- frames: integer, tuple, or sequence Pass a sequence of values that specify the time (in seconds) of the beginning / end of each frame. Note that the number of frames will be the length of the sequence minus one. Alternatively, you can pass a 2-tuple containing the number of frames and the frame rate in frames-per-second. Finally, you may simply specify the number of frames, in which case the rate will default to 30 frames-per-second. Yields ------ frames: :class:`toyplot.canvas.AnimationFrame` Use the methods and properties of each frame object to modify the state of the canvas over time. """ if isinstance(frames, numbers.Integral): frames = (frames, 30.0) if isinstance(frames, tuple): frame_count, frame_rate = frames times = numpy.linspace(0, frame_count / frame_rate, frame_count + 1, endpoint=True) for index, (begin, end) in enumerate(zip(times[:-1], times[1:])): yield AnimationFrame(changes=self._changes, count=frame_count, number=index, begin=begin, end=end)
(self, frames)
57,957
toyplot.canvas
image
Add an image to the canvas. Parameters ---------- data: image, or (image, colormap) tuple bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the image by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the image by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the image by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the image using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. margin: size of the margin around grid cells, optional Specifies the amount of empty space to leave between grid cells When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`.
def image( self, data, bounds=None, corner=None, grid=None, margin=50, rect=None, ): """Add an image to the canvas. Parameters ---------- data: image, or (image, colormap) tuple bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the image by specifying the position of each of its boundaries. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the image by specifying its upper-left-hand corner, width, and height. Assumes CSS pixels if units aren't provided, and supports all units described in :ref:`units`, including percentage of the canvas width / height. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the image by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified using absolute units as described in :ref:`units`, or as a percentage of the canvas width / height. The inset only supports absolute drawing units. All units default to CSS pixels if unspecified. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the image using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. margin: size of the margin around grid cells, optional Specifies the amount of empty space to leave between grid cells When using the `grid` parameter for positioning. Assumes CSS pixels by default, and supports all of the absolute units described in :ref:`units`. """ colormap = None if isinstance(data, tuple): data, colormap = data if not isinstance(colormap, toyplot.color.Map): raise ValueError("Expected toyplot.color.Map, received %s." % colormap) # pragma: no cover data = numpy.atleast_3d(data) if data.shape[2] != 1: raise ValueError("Expected an image with one channel.") # pragma: no cover data = colormap.colors(data) xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) mark = toyplot.mark.Image( xmin_range, xmax_range, ymin_range, ymax_range, data=data, ) self._scenegraph.add_edge(self, "render", mark) return mark
(self, data, bounds=None, corner=None, grid=None, margin=50, rect=None)
57,958
toyplot.canvas
legend
Add a legend to the canvas. See Also -------- :ref:`labels-and-legends` Parameters ---------- entries: sequence of entries to add to the legend Each entry to be displayed in the legend must be either a (label, mark) tuple or a (label, marker) tuple. Labels are human-readable text, markers are specified using the syntax described in :ref:`markers`, and marks can be any instance of :class:`toyplot.mark.Mark`. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the legend. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between legend and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". Returns ------- legend: :class:`toyplot.coordinates.Table`
def legend( self, entries, bounds=None, corner=None, grid=None, label=None, margin=50, rect=None, ): """Add a legend to the canvas. See Also -------- :ref:`labels-and-legends` Parameters ---------- entries: sequence of entries to add to the legend Each entry to be displayed in the legend must be either a (label, mark) tuple or a (label, marker) tuple. Labels are human-readable text, markers are specified using the syntax described in :ref:`markers`, and marks can be any instance of :class:`toyplot.mark.Mark`. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the legend. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between legend and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". Returns ------- legend: :class:`toyplot.coordinates.Table` """ xmin, xmax, ymin, ymax = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, corner=corner, grid=grid, margin=margin, rect=rect, ) table = toyplot.coordinates.Table( annotation=True, brows=0, columns=2, filename=None, label=label, lcolumns=0, scenegraph=self._scenegraph, rcolumns=0, rows=len(entries), trows=0, xmax_range=xmax, xmin_range=xmin, ymax_range=ymax, ymin_range=ymin, ) table.cells.column[0].align = "right" table.cells.column[1].align = "left" for index, (label, spec) in enumerate(entries): # pylint: disable=redefined-argument-from-local if isinstance(spec, toyplot.mark.Mark): markers = spec.markers else: markers = [toyplot.marker.convert(spec)] text = "" for marker in markers: if text: text = text + " " text = text + marker table.cells.cell[index, 0].data = text table.cells.cell[index, 1].data = label self._scenegraph.add_edge(self, "render", table) return table
(self, entries, bounds=None, corner=None, grid=None, label=None, margin=50, rect=None)
57,959
toyplot.canvas
matrix
Add a matrix visualization to the canvas. See Also -------- :ref:`matrix-visualization` Parameters ---------- data: matrix, or (matrix, :class:`toyplot.color.Map`) tuple, required The given data will be used to populate the visualization, using either the given colormap or a default. blabel: str, optional Human readable label along the bottom of the matrix. blocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the bottom of the matrix. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". bshow: bool, optional Set to `False` to hide column labels along the bottom of the matrix. colorshow: bool, optional Set to `True` to add a color scale to the visualization. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. filename: str, optional Supplies a default filename for users who choose to download the matrix contents. Note that users and web browsers are free to ignore or override this. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the matrix. llabel: str, optional Human readable label along the left side of the matrix. llocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the left side of the matrix. lshow: bool, optional Set to `False` to hide row labels along the left side of the matrix. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the matrix and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". rlabel: str, optional Human readable label along the right side of the matrix. rlocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the right side of the matrix. rshow: bool, optional Set to `False` to hide row labels along the right side of the matrix. step: integer, optional Specifies the number of rows or columns to skip between indices. This is useful when the matrix cells become too small relative to the index text. tlabel: str, optional Human readable label along the top of the matrix. tlocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the top of the matrix. tshow: bool, optional Set to `False` to hide column labels along the top of the matrix. Returns ------- axes: :class:`toyplot.coordinates.Table`
def matrix( self, data, blabel=None, blocator=None, bounds=None, bshow=None, colorshow=False, corner=None, filename=None, grid=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rect=None, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None, ): """Add a matrix visualization to the canvas. See Also -------- :ref:`matrix-visualization` Parameters ---------- data: matrix, or (matrix, :class:`toyplot.color.Map`) tuple, required The given data will be used to populate the visualization, using either the given colormap or a default. blabel: str, optional Human readable label along the bottom of the matrix. blocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the bottom of the matrix. bounds: (xmin, xmax, ymin, ymax) tuple, optional Use the bounds property to position / size the legend by specifying the position of each of its boundaries. The boundaries may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". bshow: bool, optional Set to `False` to hide column labels along the bottom of the matrix. colorshow: bool, optional Set to `True` to add a color scale to the visualization. corner: (corner, inset, width, height) tuple, optional Use the corner property to position / size the legend by specifying its width and height, plus an inset from a corner of the canvas. Allowed corner values are "top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", and "left". The width and height may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". The inset is specified in absolute drawing units. filename: str, optional Supplies a default filename for users who choose to download the matrix contents. Note that users and web browsers are free to ignore or override this. grid: (rows, columns, index) tuple, or (rows, columns, i, j) tuple, or (rows, columns, i, rowspan, j, columnspan) tuple, optional Use the grid property to position / size the legend using a collection of grid cells filling the canvas. Specify the number of rows and columns in the grid, then specify either a zero-based cell index (which runs in left-ot-right, top-to-bottom order), a pair of i, j cell coordinates, or a set of i, column-span, j, row-span coordinates so the legend can cover more than one cell. label: str, optional Optional human-readable label for the matrix. llabel: str, optional Human readable label along the left side of the matrix. llocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the left side of the matrix. lshow: bool, optional Set to `False` to hide row labels along the left side of the matrix. margin: number, (top, side) tuple, (top, side, bottom) tuple, or (top, right, bottom, left) tuple, optional Specifies the amount of empty space to leave between the matrix and the containing grid cell when using the `grid` parameter for positioning. rect: (x, y, width, height) tuple, optional Use the rect property to position / size the legend by specifying its upper-left-hand corner, width, and height. Each parameter may be specified in absolute drawing units, or as a percentage of the canvas width / height using strings that end with "%". rlabel: str, optional Human readable label along the right side of the matrix. rlocator: :class:`toyplot.locator.TickLocator`, optional Supplies row labels along the right side of the matrix. rshow: bool, optional Set to `False` to hide row labels along the right side of the matrix. step: integer, optional Specifies the number of rows or columns to skip between indices. This is useful when the matrix cells become too small relative to the index text. tlabel: str, optional Human readable label along the top of the matrix. tlocator: :class:`toyplot.locator.TickLocator`, optional Supplies column labels along the top of the matrix. tshow: bool, optional Set to `False` to hide column labels along the top of the matrix. Returns ------- axes: :class:`toyplot.coordinates.Table` """ if isinstance(data, tuple): matrix = toyplot.require.scalar_matrix(data[0]) colormap = toyplot.require.instance(data[1], toyplot.color.Map) else: matrix = toyplot.require.scalar_matrix(data) colormap = toyplot.color.brewer.map("BlueRed", domain_min=matrix.min(), domain_max=matrix.max()) colors = colormap.colors(matrix) xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin) table = toyplot.coordinates.Table( annotation=False, brows=2, columns=matrix.shape[1], filename=filename, label=label, lcolumns=2, scenegraph=self._scenegraph, rcolumns=2, rows=matrix.shape[0], trows=2, xmax_range=xmax_range, xmin_range=xmin_range, ymax_range=ymax_range, ymin_range=ymin_range, ) table.top.row[[0, 1]].height = 20 table.bottom.row[[0, 1]].height = 20 table.left.column[[0, 1]].width = 20 table.right.column[[0, 1]].width = 20 table.left.column[1].align = "right" table.right.column[0].align = "left" table.cells.column[[0, -1]].lstyle = {"font-weight":"bold"} table.cells.row[[0, -1]].lstyle = {"font-weight":"bold"} if tlabel is not None: cell = table.top.row[0].merge() cell.data = tlabel if llabel is not None: cell = table.left.column[0].merge() cell.data = llabel cell.angle = 90 if rlabel is not None: cell = table.right.column[1].merge() cell.data = rlabel cell.angle = 90 if blabel is not None: cell = table.bottom.row[1].merge() cell.data = blabel if tshow is None: tshow = True if tshow: if tlocator is None: tlocator = toyplot.locator.Integer(step=step) for j, label, title in zip(*tlocator.ticks(0, matrix.shape[1] - 1)): # pylint: disable=redefined-argument-from-local table.top.cell[1, int(j)].data = label #table.top.cell[1, j].title = title if lshow is None: lshow = True if lshow: if llocator is None: llocator = toyplot.locator.Integer(step=step) for i, label, title in zip(*llocator.ticks(0, matrix.shape[0] - 1)): # pylint: disable=redefined-argument-from-local table.left.cell[int(i), 1].data = label #table.left.cell[i, 1].title = title if rshow is None and rlocator is not None: rshow = True if rshow: if rlocator is None: rlocator = toyplot.locator.Integer(step=step) for i, label, title in zip(*rlocator.ticks(0, matrix.shape[0] - 1)): # pylint: disable=redefined-argument-from-local table.right.cell[int(i), 0].data = label #table.right.cell[i, 0].title = title if bshow is None and blocator is not None: bshow = True if bshow: if blocator is None: blocator = toyplot.locator.Integer(step=step) for j, label, title in zip(*blocator.ticks(0, matrix.shape[1] - 1)): # pylint: disable=redefined-argument-from-local table.bottom.cell[0, int(j)].data = label #table.bottom.cell[0, j].title = title table.body.cells.data = matrix table.body.cells.format = toyplot.format.NullFormatter() for i in numpy.arange(matrix.shape[0]): for j in numpy.arange(matrix.shape[1]): cell = table.body.cell[i, j] cell.style = {"stroke": "none", "fill": toyplot.color.to_css(colors[i, j])} cell.title = "%.6f" % matrix[i, j] self._scenegraph.add_edge(self, "render", table) if colorshow: self.color_scale( colormap=colormap, x1=xmax_range, y1=ymax_range, x2=xmax_range, y2=ymin_range, width=10, padding=10, show=True, label="", ticklocator=None, scale="linear", ) return table
(self, data, blabel=None, blocator=None, bounds=None, bshow=None, colorshow=False, corner=None, filename=None, grid=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rect=None, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None)
57,960
toyplot.canvas
numberline
Add a 1D numberline to the canvas. Parameters ---------- min, max: float, optional Used to explicitly override the numberline domain (normally, the domain is implicitly defined by any marks added to the numberline). show: bool, optional Set to `False` to hide the numberline (the numberline contents will still be visible). label: string, optional Human-readable label placed below the numberline axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. See :ref:`tick-locators`. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along the axis. See :ref:`log-scales`. spacing: number, string, or (number, string) tuple, optional Distance between plotted data added to the numberline. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. padding: number, string, or (number, string) tuple, optional Distance between the numberline axis and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. Defaults to the same value as `spacing`. Returns ------- axes: :class:`toyplot.coordinates.Cartesian`
def numberline( self, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, padding=None, palette=None, rect=None, scale="linear", show=True, spacing=None, ticklocator=None, ): """Add a 1D numberline to the canvas. Parameters ---------- min, max: float, optional Used to explicitly override the numberline domain (normally, the domain is implicitly defined by any marks added to the numberline). show: bool, optional Set to `False` to hide the numberline (the numberline contents will still be visible). label: string, optional Human-readable label placed below the numberline axis. ticklocator: :class:`toyplot.locator.TickLocator`, optional Controls the placement and formatting of axis ticks and tick labels. See :ref:`tick-locators`. scale: "linear", "log", "log10", "log2", or a ("log", <base>) tuple, optional Specifies the mapping from data to canvas coordinates along the axis. See :ref:`log-scales`. spacing: number, string, or (number, string) tuple, optional Distance between plotted data added to the numberline. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. padding: number, string, or (number, string) tuple, optional Distance between the numberline axis and plotted data. Assumes CSS pixels if units aren't provided. See :ref:`units` for details on how Toyplot handles real-world units. Defaults to the same value as `spacing`. Returns ------- axes: :class:`toyplot.coordinates.Cartesian` """ xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin) if x1 is None: x1 = xmin_range else: x1 = toyplot.units.convert(x1, target="px", default="px", reference=self._width) if x1 < 0: x1 = self._width + x1 if y1 is None: y1 = 0.5 * (ymin_range + ymax_range) else: y1 = toyplot.units.convert(y1, target="px", default="px", reference=self._height) if y1 < 0: y1 = self._height + y1 if x2 is None: x2 = xmax_range else: x2 = toyplot.units.convert(x2, target="px", default="px", reference=self._width) if x2 < 0: x2 = self._width + x2 if y2 is None: y2 = 0.5 * (ymin_range + ymax_range) else: y2 = toyplot.units.convert(y2, target="px", default="px", reference=self._height) if y2 < 0: y2 = self._height + y2 if spacing is None: spacing = 20 if padding is None: padding = spacing axes = toyplot.coordinates.Numberline( label=label, max=max, min=min, padding=padding, palette=palette, scenegraph=self._scenegraph, scale=scale, show=show, spacing=spacing, ticklocator=ticklocator, x1=x1, x2=x2, y1=y1, y2=y2, ) self._scenegraph.add_edge(self, "render", axes) return axes
(self, x1=None, y1=None, x2=None, y2=None, bounds=None, corner=None, grid=None, label=None, margin=50, max=None, min=None, padding=None, palette=None, rect=None, scale='linear', show=True, spacing=None, ticklocator=None)
57,961
toyplot.canvas
table
Add a set of table axes to the canvas. Parameters ---------- Returns ------- axes: :class:`toyplot.coordinates.Table`
def table( self, data=None, rows=None, columns=None, annotation=False, bounds=None, brows=None, corner=None, filename=None, grid=None, label=None, lcolumns=None, margin=50, rcolumns=None, rect=None, trows=None, ): """Add a set of table axes to the canvas. Parameters ---------- Returns ------- axes: :class:`toyplot.coordinates.Table` """ if data is not None: data = toyplot.data.Table(data) rows = data.shape[0] if rows is None else max(rows, data.shape[0]) columns = data.shape[1] if columns is None else max( columns, data.shape[1]) if trows is None: trows = 1 if rows is None or columns is None: # pragma: no cover raise ValueError("You must specify data, or rows and columns.") if trows is None: trows = 0 if brows is None: brows = 0 if lcolumns is None: lcolumns = 0 if rcolumns is None: rcolumns = 0 xmin_range, xmax_range, ymin_range, ymax_range = toyplot.layout.region( 0, self._width, 0, self._height, bounds=bounds, rect=rect, corner=corner, grid=grid, margin=margin, ) table = toyplot.coordinates.Table( annotation=annotation, brows=brows, columns=columns, filename=filename, label=label, lcolumns=lcolumns, scenegraph=self._scenegraph, rcolumns=rcolumns, rows=rows, trows=trows, xmax_range=xmax_range, xmin_range=xmin_range, ymax_range=ymax_range, ymin_range=ymin_range, ) if data is not None: for j, (key, column) in enumerate(data.items()): if trows: table.top.cell[trows - 1, j].data = key for i, (value, mask) in enumerate(zip(column, numpy.ma.getmaskarray(column))): if not mask: table.body.cell[i, j].data = value if issubclass(column._data.dtype.type, numpy.floating): if trows: table.top.cell[0, j].align = "center" table.body.cell[:, j].format = toyplot.format.FloatFormatter() table.body.cell[:, j].align = "separator" elif issubclass(column._data.dtype.type, numpy.character): table.cells.cell[:, j].align = "left" elif issubclass(column._data.dtype.type, numpy.integer): table.cells.cell[:, j].align = "right" if trows: # Format top cells for use as a header table.top.cells.lstyle = {"font-weight": "bold"} # Enable a single horizontal line between top and body. table.cells.grid.hlines[trows] = "single" self._scenegraph.add_edge(self, "render", table) return table
(self, data=None, rows=None, columns=None, annotation=False, bounds=None, brows=None, corner=None, filename=None, grid=None, label=None, lcolumns=None, margin=50, rcolumns=None, rect=None, trows=None)
57,962
toyplot.canvas
text
Add text to the canvas. Parameters ---------- x, y: float Coordinates of the text anchor in canvas drawing units. Note that canvas Y coordinates increase from top-to-bottom. text: string The text to be displayed. title: string, optional Human-readable title for the mark. The SVG / HTML backends render the title as a tooltip. style: dict, optional Collection of CSS styles to apply to the mark. See :class:`toyplot.mark.Text` for a list of useful styles. Returns ------- text: :class:`toyplot.mark.Text`
def text( self, x, y, text, angle=0.0, fill=None, opacity=1.0, title=None, style=None): """Add text to the canvas. Parameters ---------- x, y: float Coordinates of the text anchor in canvas drawing units. Note that canvas Y coordinates increase from top-to-bottom. text: string The text to be displayed. title: string, optional Human-readable title for the mark. The SVG / HTML backends render the title as a tooltip. style: dict, optional Collection of CSS styles to apply to the mark. See :class:`toyplot.mark.Text` for a list of useful styles. Returns ------- text: :class:`toyplot.mark.Text` """ table = toyplot.data.Table() table["x"] = toyplot.require.scalar_vector(x) table["y"] = toyplot.require.scalar_vector(y, table.shape[0]) table["text"] = toyplot.broadcast.pyobject(text, table.shape[0]) table["angle"] = toyplot.broadcast.scalar(angle, table.shape[0]) table["fill"] = toyplot.broadcast.pyobject(fill, table.shape[0]) table["toyplot:fill"] = toyplot.color.broadcast( colors=fill, shape=(table.shape[0],), default=toyplot.color.black, ) table["opacity"] = toyplot.broadcast.scalar(opacity, table.shape[0]) table["title"] = toyplot.broadcast.pyobject(title, table.shape[0]) style = toyplot.style.require(style, allowed=toyplot.style.allowed.text) mark = toyplot.mark.Text( coordinate_axes=["x", "y"], table=table, coordinates=["x", "y"], text=["text"], angle=["angle"], fill=["toyplot:fill"], opacity=["opacity"], title=["title"], style=style, annotation=True, filename=None, ) self._scenegraph.add_edge(self, "render", mark) return mark
(self, x, y, text, angle=0.0, fill=None, opacity=1.0, title=None, style=None)
57,963
toyplot
DeprecationWarning
Used with :func:`warnings.warn` to mark deprecated API.
class DeprecationWarning(Warning): """Used with :func:`warnings.warn` to mark deprecated API.""" pass
null
57,964
toyplot
bars
Convenience function for creating a bar plot in a single call. See :meth:`toyplot.coordinates.Cartesian.bars`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.BarMagnitudes` or :class:`toyplot.mark.BarBoundaries` The new bar mark.
def bars( a, b=None, c=None, along="x", baseline="stacked", color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a bar plot in a single call. See :meth:`toyplot.coordinates.Cartesian.bars`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.BarMagnitudes` or :class:`toyplot.mark.BarBoundaries` The new bar mark. """ canvas = Canvas(width=width, height=height) axes = canvas.cartesian( label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.bars( a=a, b=b, c=c, along=along, baseline=baseline, color=color, filename=filename, hyperlink=hyperlink, opacity=opacity, style=style, title=title, ) return canvas, axes, mark
(a, b=None, c=None, along='x', baseline='stacked', color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale='linear', xshow=True, ylabel=None, ymax=None, ymin=None, yscale='linear', yshow=True)
57,971
toyplot
fill
Convenience function for creating a fill plot in a single call. See :meth:`toyplot.coordinates.Cartesian.fill`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.FillBoundaries` or :class:`toyplot.mark.FillMagnitudes` The new fill mark.
def fill( a, b=None, c=None, along="x", baseline=None, color=None, filename=None, height=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a fill plot in a single call. See :meth:`toyplot.coordinates.Cartesian.fill`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.FillBoundaries` or :class:`toyplot.mark.FillMagnitudes` The new fill mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.fill( a=a, b=b, c=c, along=along, baseline=baseline, color=color, filename=filename, opacity=opacity, style=style, title=title, ) return canvas, axes, mark
(a, b=None, c=None, along='x', baseline=None, color=None, filename=None, height=None, label=None, margin=50, opacity=1.0, padding=10, show=True, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale='linear', xshow=True, ylabel=None, ymax=None, ymin=None, yscale='linear', yshow=True)
57,973
toyplot
graph
Convenience function for creating a graph plot in a single call. See :meth:`toyplot.coordinates.Cartesian.graph`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Graph` The new graph mark.
def graph( a, b=None, c=None, along="x", ecolor=None, eopacity=1.0, estyle=None, ewidth=1.0, height=None, hmarker=None, layout=None, margin=50, mmarker=None, mposition=0.5, olayout=None, padding=20, tmarker=None, varea=None, vcolor=None, vcoordinates=None, vlabel=None, vlshow=True, vlstyle=None, vmarker="o", vopacity=1.0, vsize=None, vstyle=None, vtitle=None, width=None, ): # pragma: no cover """Convenience function for creating a graph plot in a single call. See :meth:`toyplot.coordinates.Cartesian.graph`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Graph` The new graph mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect="fit-range", margin=margin, padding=padding, show=False, ) mark = axes.graph( a=a, b=b, c=c, along=along, ecolor=ecolor, eopacity=eopacity, estyle=estyle, ewidth=ewidth, hmarker=hmarker, layout=layout, mmarker=mmarker, mposition=mposition, olayout=olayout, tmarker=tmarker, varea=varea, vcolor=vcolor, vcoordinates=vcoordinates, vlabel=vlabel, vlshow=vlshow, vlstyle=vlstyle, vmarker=vmarker, vopacity=vopacity, vsize=vsize, vstyle=vstyle, vtitle=vtitle, ) return canvas, axes, mark
(a, b=None, c=None, along='x', ecolor=None, eopacity=1.0, estyle=None, ewidth=1.0, height=None, hmarker=None, layout=None, margin=50, mmarker=None, mposition=0.5, olayout=None, padding=20, tmarker=None, varea=None, vcolor=None, vcoordinates=None, vlabel=None, vlshow=True, vlstyle=None, vmarker='o', vopacity=1.0, vsize=None, vstyle=None, vtitle=None, width=None)
57,974
toyplot
image
Convenience function for displaying an image in a single call. See :meth:`toyplot.canvas.Canvas.image`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. mark: :class:`toyplot.mark.Image` The new image mark.
def image( data, height=None, margin=0, width=None, ): # pragma: no cover """Convenience function for displaying an image in a single call. See :meth:`toyplot.canvas.Canvas.image`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. mark: :class:`toyplot.mark.Image` The new image mark. """ canvas = Canvas( height=height, width=width, ) mark = canvas.image( data=data, margin=margin, ) return canvas, mark
(data, height=None, margin=0, width=None)
57,980
toyplot
matrix
Convenience function to create a matrix visualization in a single call. See :meth:`toyplot.canvas.Canvas.matrix`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas.
def matrix( data, blabel=None, blocator=None, bshow=None, colorshow=False, filename=None, height=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None, width=None, ): """Convenience function to create a matrix visualization in a single call. See :meth:`toyplot.canvas.Canvas.matrix`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas. """ canvas = Canvas( height=height, width=width, ) axes = canvas.matrix( blabel=blabel, blocator=blocator, bshow=bshow, colorshow=colorshow, data=data, filename=filename, label=label, llabel=llabel, llocator=llocator, lshow=lshow, margin=margin, rlabel=rlabel, rlocator=rlocator, rshow=rshow, step=step, tlabel=tlabel, tlocator=tlocator, tshow=tshow, ) return canvas, axes
(data, blabel=None, blocator=None, bshow=None, colorshow=False, filename=None, height=None, label=None, llabel=None, llocator=None, lshow=None, margin=50, rlabel=None, rlocator=None, rshow=None, step=1, tlabel=None, tlocator=None, tshow=None, width=None)
57,981
toyplot
plot
Convenience function for creating a line plot in a single call. See :meth:`toyplot.coordinates.Cartesian.plot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Plot` The new plot mark.
def plot( a, b=None, along="x", area=None, aspect=None, color=None, filename=None, height=None, label=None, margin=50, marker=None, mfill=None, mlstyle=None, mopacity=1.0, mstyle=None, mtitle=None, opacity=1.0, padding=10, show=True, size=None, stroke_width=2.0, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a line plot in a single call. See :meth:`toyplot.coordinates.Cartesian.plot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Plot` The new plot mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect=aspect, label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.plot( a=a, b=b, along=along, area=area, color=color, filename=filename, marker=marker, mfill=mfill, mlstyle=mlstyle, mopacity=mopacity, mstyle=mstyle, mtitle=mtitle, opacity=opacity, size=size, stroke_width=stroke_width, style=style, title=title, ) return canvas, axes, mark
(a, b=None, along='x', area=None, aspect=None, color=None, filename=None, height=None, label=None, margin=50, marker=None, mfill=None, mlstyle=None, mopacity=1.0, mstyle=None, mtitle=None, opacity=1.0, padding=10, show=True, size=None, stroke_width=2.0, style=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale='linear', xshow=True, ylabel=None, ymax=None, ymin=None, yscale='linear', yshow=True)
57,984
toyplot
scatterplot
Convenience function for creating a scatter plot in a single call. See :meth:`toyplot.coordinates.Cartesian.scatterplot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Point` The new scatterplot mark.
def scatterplot( a, b=None, along="x", area=None, aspect=None, color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, marker="o", mlstyle=None, mstyle=None, opacity=1.0, padding=10, show=True, size=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale="linear", xshow=True, ylabel=None, ymax=None, ymin=None, yscale="linear", yshow=True, ): """Convenience function for creating a scatter plot in a single call. See :meth:`toyplot.coordinates.Cartesian.scatterplot`, :meth:`toyplot.canvas.Canvas.cartesian`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. axes: :class:`toyplot.coordinates.Cartesian` A new set of 2D axes that fill the canvas. mark: :class:`toyplot.mark.Point` The new scatterplot mark. """ canvas = Canvas( height=height, width=width, ) axes = canvas.cartesian( aspect=aspect, label=label, margin=margin, padding=padding, show=show, xlabel=xlabel, xmax=xmax, xmin=xmin, xscale=xscale, xshow=xshow, ylabel=ylabel, ymax=ymax, ymin=ymin, yscale=yscale, yshow=yshow, ) mark = axes.scatterplot( a=a, b=b, along=along, area=area, color=color, filename=filename, hyperlink=hyperlink, marker=marker, mlstyle=mlstyle, mstyle=mstyle, opacity=opacity, size=size, title=title, ) return canvas, axes, mark
(a, b=None, along='x', area=None, aspect=None, color=None, filename=None, height=None, hyperlink=None, label=None, margin=50, marker='o', mlstyle=None, mstyle=None, opacity=1.0, padding=10, show=True, size=None, title=None, width=None, xlabel=None, xmax=None, xmin=None, xscale='linear', xshow=True, ylabel=None, ymax=None, ymin=None, yscale='linear', yshow=True)
57,988
toyplot
table
Convenience function to create a table visualization in a single call. See :meth:`toyplot.canvas.Canvas.table`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas.
def table( data=None, brows=None, columns=None, filename=None, height=None, label=None, lcolumns=None, margin=50, rcolumns=None, rows=None, trows=None, width=None, ): """Convenience function to create a table visualization in a single call. See :meth:`toyplot.canvas.Canvas.table`, and :class:`toyplot.canvas.Canvas` for parameter descriptions. Returns ------- canvas: :class:`toyplot.canvas.Canvas` A new canvas object. table: :class:`toyplot.coordinates.Table` A new set of table axes that fill the canvas. """ canvas = Canvas( height=height, width=width, ) axes = canvas.table( brows=brows, columns=columns, data=data, filename=filename, label=label, lcolumns=lcolumns, margin=margin, rcolumns=rcolumns, rows=rows, trows=trows, ) return canvas, axes
(data=None, brows=None, columns=None, filename=None, height=None, label=None, lcolumns=None, margin=50, rcolumns=None, rows=None, trows=None, width=None)
57,990
sib_api_v3_sdk.models.ab_test_campaign_result
AbTestCampaignResult
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
class AbTestCampaignResult(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'winning_version': 'str', 'winning_criteria': 'str', 'winning_subject_line': 'str', 'open_rate': 'str', 'click_rate': 'str', 'winning_version_rate': 'str', 'statistics': 'AbTestCampaignResultStatistics', 'clicked_links': 'AbTestCampaignResultClickedLinks' } attribute_map = { 'winning_version': 'winningVersion', 'winning_criteria': 'winningCriteria', 'winning_subject_line': 'winningSubjectLine', 'open_rate': 'openRate', 'click_rate': 'clickRate', 'winning_version_rate': 'winningVersionRate', 'statistics': 'statistics', 'clicked_links': 'clickedLinks' } def __init__(self, winning_version=None, winning_criteria=None, winning_subject_line=None, open_rate=None, click_rate=None, winning_version_rate=None, statistics=None, clicked_links=None): # noqa: E501 """AbTestCampaignResult - a model defined in Swagger""" # noqa: E501 self._winning_version = None self._winning_criteria = None self._winning_subject_line = None self._open_rate = None self._click_rate = None self._winning_version_rate = None self._statistics = None self._clicked_links = None self.discriminator = None if winning_version is not None: self.winning_version = winning_version if winning_criteria is not None: self.winning_criteria = winning_criteria if winning_subject_line is not None: self.winning_subject_line = winning_subject_line if open_rate is not None: self.open_rate = open_rate if click_rate is not None: self.click_rate = click_rate if winning_version_rate is not None: self.winning_version_rate = winning_version_rate if statistics is not None: self.statistics = statistics if clicked_links is not None: self.clicked_links = clicked_links @property def winning_version(self): """Gets the winning_version of this AbTestCampaignResult. # noqa: E501 Winning Campaign Info. pending = Campaign has been picked for sending and winning version is yet to be decided, tie = A tie happened between both the versions, notAvailable = Campaign has not yet been picked for sending. # noqa: E501 :return: The winning_version of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._winning_version @winning_version.setter def winning_version(self, winning_version): """Sets the winning_version of this AbTestCampaignResult. Winning Campaign Info. pending = Campaign has been picked for sending and winning version is yet to be decided, tie = A tie happened between both the versions, notAvailable = Campaign has not yet been picked for sending. # noqa: E501 :param winning_version: The winning_version of this AbTestCampaignResult. # noqa: E501 :type: str """ allowed_values = ["notAvailable", "pending", "tie", "A", "B"] # noqa: E501 if winning_version not in allowed_values: raise ValueError( "Invalid value for `winning_version` ({0}), must be one of {1}" # noqa: E501 .format(winning_version, allowed_values) ) self._winning_version = winning_version @property def winning_criteria(self): """Gets the winning_criteria of this AbTestCampaignResult. # noqa: E501 Criteria choosen for winning version (Open/Click) # noqa: E501 :return: The winning_criteria of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._winning_criteria @winning_criteria.setter def winning_criteria(self, winning_criteria): """Sets the winning_criteria of this AbTestCampaignResult. Criteria choosen for winning version (Open/Click) # noqa: E501 :param winning_criteria: The winning_criteria of this AbTestCampaignResult. # noqa: E501 :type: str """ allowed_values = ["Open", "Click"] # noqa: E501 if winning_criteria not in allowed_values: raise ValueError( "Invalid value for `winning_criteria` ({0}), must be one of {1}" # noqa: E501 .format(winning_criteria, allowed_values) ) self._winning_criteria = winning_criteria @property def winning_subject_line(self): """Gets the winning_subject_line of this AbTestCampaignResult. # noqa: E501 Subject Line of current winning version # noqa: E501 :return: The winning_subject_line of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._winning_subject_line @winning_subject_line.setter def winning_subject_line(self, winning_subject_line): """Sets the winning_subject_line of this AbTestCampaignResult. Subject Line of current winning version # noqa: E501 :param winning_subject_line: The winning_subject_line of this AbTestCampaignResult. # noqa: E501 :type: str """ self._winning_subject_line = winning_subject_line @property def open_rate(self): """Gets the open_rate of this AbTestCampaignResult. # noqa: E501 Open rate for current winning version # noqa: E501 :return: The open_rate of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._open_rate @open_rate.setter def open_rate(self, open_rate): """Sets the open_rate of this AbTestCampaignResult. Open rate for current winning version # noqa: E501 :param open_rate: The open_rate of this AbTestCampaignResult. # noqa: E501 :type: str """ self._open_rate = open_rate @property def click_rate(self): """Gets the click_rate of this AbTestCampaignResult. # noqa: E501 Click rate for current winning version # noqa: E501 :return: The click_rate of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._click_rate @click_rate.setter def click_rate(self, click_rate): """Sets the click_rate of this AbTestCampaignResult. Click rate for current winning version # noqa: E501 :param click_rate: The click_rate of this AbTestCampaignResult. # noqa: E501 :type: str """ self._click_rate = click_rate @property def winning_version_rate(self): """Gets the winning_version_rate of this AbTestCampaignResult. # noqa: E501 Open/Click rate for the winner version # noqa: E501 :return: The winning_version_rate of this AbTestCampaignResult. # noqa: E501 :rtype: str """ return self._winning_version_rate @winning_version_rate.setter def winning_version_rate(self, winning_version_rate): """Sets the winning_version_rate of this AbTestCampaignResult. Open/Click rate for the winner version # noqa: E501 :param winning_version_rate: The winning_version_rate of this AbTestCampaignResult. # noqa: E501 :type: str """ self._winning_version_rate = winning_version_rate @property def statistics(self): """Gets the statistics of this AbTestCampaignResult. # noqa: E501 :return: The statistics of this AbTestCampaignResult. # noqa: E501 :rtype: AbTestCampaignResultStatistics """ return self._statistics @statistics.setter def statistics(self, statistics): """Sets the statistics of this AbTestCampaignResult. :param statistics: The statistics of this AbTestCampaignResult. # noqa: E501 :type: AbTestCampaignResultStatistics """ self._statistics = statistics @property def clicked_links(self): """Gets the clicked_links of this AbTestCampaignResult. # noqa: E501 :return: The clicked_links of this AbTestCampaignResult. # noqa: E501 :rtype: AbTestCampaignResultClickedLinks """ return self._clicked_links @clicked_links.setter def clicked_links(self, clicked_links): """Sets the clicked_links of this AbTestCampaignResult. :param clicked_links: The clicked_links of this AbTestCampaignResult. # noqa: E501 :type: AbTestCampaignResultClickedLinks """ self._clicked_links = clicked_links def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(AbTestCampaignResult, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AbTestCampaignResult): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
(winning_version=None, winning_criteria=None, winning_subject_line=None, open_rate=None, click_rate=None, winning_version_rate=None, statistics=None, clicked_links=None)
57,991
sib_api_v3_sdk.models.ab_test_campaign_result
__eq__
Returns true if both objects are equal
def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AbTestCampaignResult): return False return self.__dict__ == other.__dict__
(self, other)
57,992
sib_api_v3_sdk.models.ab_test_campaign_result
__init__
AbTestCampaignResult - a model defined in Swagger
def __init__(self, winning_version=None, winning_criteria=None, winning_subject_line=None, open_rate=None, click_rate=None, winning_version_rate=None, statistics=None, clicked_links=None): # noqa: E501 """AbTestCampaignResult - a model defined in Swagger""" # noqa: E501 self._winning_version = None self._winning_criteria = None self._winning_subject_line = None self._open_rate = None self._click_rate = None self._winning_version_rate = None self._statistics = None self._clicked_links = None self.discriminator = None if winning_version is not None: self.winning_version = winning_version if winning_criteria is not None: self.winning_criteria = winning_criteria if winning_subject_line is not None: self.winning_subject_line = winning_subject_line if open_rate is not None: self.open_rate = open_rate if click_rate is not None: self.click_rate = click_rate if winning_version_rate is not None: self.winning_version_rate = winning_version_rate if statistics is not None: self.statistics = statistics if clicked_links is not None: self.clicked_links = clicked_links
(self, winning_version=None, winning_criteria=None, winning_subject_line=None, open_rate=None, click_rate=None, winning_version_rate=None, statistics=None, clicked_links=None)