A collection of utility functions and classes. Many (but not all) from the Python Cookbook – hence the name cbook
Often we want to just collect a bunch of stuff together, naming each item of the bunch; a dictionary’s OK for that, but a small do- nothing class is even handier, and prettier to use. Whenever you want to group a few variables:
>>> point = Bunch(datum=2, squared=4, coord=12) >>> point.datumBy: Alex Martelli From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
Handle registering and disconnecting for a set of signals and callbacks:
signals = 'eat', 'drink', 'be merry'
def oneat(x):
print 'eat', x
def ondrink(x):
print 'drink', x
callbacks = CallbackRegistry(signals)
ideat = callbacks.connect('eat', oneat)
iddrink = callbacks.connect('drink', ondrink)
#tmp = callbacks.connect('drunk', ondrink) # this will raise a ValueError
callbacks.process('drink', 123) # will call oneat
callbacks.process('eat', 456) # will call ondrink
callbacks.process('be merry', 456) # nothing will be called
callbacks.disconnect(ideat) # disconnect oneat
callbacks.process('eat', 456) # nothing will be called
In practice, one should always disconnect all callbacks when they are no longer needed to avoid dangling references (and thus memory leaks). However, real code in matplotlib rarely does so, and due to its design, it is rather difficult to place this kind of code. To get around this, and prevent this class of memory leaks, we instead store weak references to bound methods only, so when the destination object needs to die, the CallbackRegistry won’t keep it alive. The Python stdlib weakref module can not create weak references to bound methods directly, so we need to create a proxy object to handle weak references to bound methods (or regular free functions). This technique was shared by Peter Parente on his “Mindtrove” blog.
signals is a sequence of valid signals
Bases: object
Our own proxy object which enables weak references to bound and unbound methods and arbitrary callables. Pulls information about the function, class, and instance out of a bound method. Stores a weak reference to the instance to support garbage collection.
@organization: IBM Corporation @copyright: Copyright (c) 2005, 2006 IBM Corporation @license: The BSD License
Minor bugfixes by Michael Droettboom
Bases: object
This class provides a lightweight way to group arbitrary objects together into disjoint sets when a full-blown graph data structure would be overkill.
Objects can be joined using join(), tested for connectedness using joined(), and all disjoint sets can be retreived by using the object as an iterator.
The objects being joined must be hashable and weak-referenceable.
For example:
>>> class Foo:
... def __init__(self, s):
... self.s = s
... def __repr__(self):
... return self.s
...
>>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
>>> g = Grouper()
>>> g.join(a, b)
>>> g.join(b, c)
>>> g.join(d, e)
>>> list(g)
[[d, e], [a, b, c]]
>>> g.joined(a, b)
True
>>> g.joined(a, c)
True
>>> g.joined(a, d)
False
Bases: matplotlib.cbook.Scheduler
Schedule callbacks when scheduler is idle
class that implements a not-yet-full buffer
Bases: threading.Thread
Base class for timeout and idle scheduling
Sort by attribute or item
Example usage:
sort = Sorter()
list = [(1, 2), (4, 8), (0, 3)]
dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0},
{'a': 9, 'b': 9}]
sort(list) # default sort
sort(list, 1) # sort by index 1
sort(dict, 'a') # sort a list of dicts by key 'a'
Bases: object
Implement a stack where elements can be pushed on and you can move back and forth. But no pop. Should mimic home / back / forward in a browser
Bases: matplotlib.cbook.Scheduler
Schedule recurring events with a wait time in seconds
Bases: urllib2.BaseHandler
Urllib2 handler that takes care of caching files. The file cache.pck holds the directory of files that have been cached.
Check the cachedirectory for a sample_data file. If it does not exist, fetch it with urllib from the svn repo and store it in the cachedir.
If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned.
Bases: dict
All-in-one multiple-string-substitution class
Example usage:
text = "Larry Wall is the creator of Perl"
adict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print multiple_replace(adict, text)
xlat = Xlator(adict)
print xlat.xlat(text)
This generator takes a bunch of iterables that are ordered by func It sends out ordered tuples:
(func(row), [rows from all iterators matching func(row)])
It is used by matplotlib.mlab.recs_join() to join record arrays
return all possible pairs in sequence x
Condensed by Alex Martelli from this thread on c.l.python
Base class for handling string -> python type with support for missing values
Remove excess indentation from docstring s.
Discards any leading blank lines, then removes up to n whitespace characters from each line, where n is the number of leading whitespace characters in the first line. It differs from textwrap.dedent in its deletion of leading blank lines and its use of the first non-blank line to determine the indentation.
It is also faster in most cases.
Find all masked and/or non-finite points in a set of arguments, and return the arguments with only the unmasked points remaining.
Arguments can be in any of 5 categories:
The first argument must be in one of the first four categories; any argument with a length differing from that of the first argument (and hence anything in category 5) then will be passed through unchanged.
Masks are obtained from all arguments of the correct length in categories 1, 2, and 4; a point is bad if masked in a masked array or if it is a nan or inf. No attempt is made to extract a mask from categories 2, 3, and 4 if np.isfinite() does not yield a Boolean array.
All input arguments that are not passed unchanged are returned as ndarrays after removing the points or rows corresponding to masks in any of the arguments.
A vastly simpler version of this function was originally written as a helper for Axes.scatter().
this generator flattens nested containers such as
>>> l=( ('John', 'Hunter'), (1,23), [[[[42,(5,23)]]]])
so that
>>> for i in flatten(l): print i,
John Hunter 1 23 42 5 23
By: Composite of Holger Krekel and Luther Blissett From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294 and Recipe 1.12 in cookbook
Check the cachedirectory ~/.matplotlib/sample_data for a sample_data file. If it does not exist, fetch it with urllib from the mpl svn repo
http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/
and store it in the cachedir.
If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned
To add a datafile to this directory, you need to check out sample_data from matplotlib svn:
svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data
and svn add the data file you want to support. This is primarily intended for use in mpl examples that need custom data.
To bypass all downloading, set the rc parameter examples.download to False and examples.directory to the directory where we should look.
seq is a list of words. Return the index into seq such that:
len(' '.join(seq[:ind])<=N
Recursively list files
from Parmar and Martelli in the Python Cookbook
Bases: dict
A dictionary with a maximum size; this doesn’t override all the relevant methods to contrain size, just setitem, so use with caution
make directory newdir recursively, and set mode. Equivalent to
> mkdir -p NEWDIR
> chmod MODE NEWDIR
Bases: list
override repr when returning a list of matplotlib artists to prevent long, meaningless output. This is meant to be used for a homogeneous list of a give type
Bases: matplotlib.cbook.converter
convert to a date or None
use a time.strptime() format string for conversion
Bases: matplotlib.cbook.converter
convert to a datetime or None
use a time.strptime() format string for conversion
Bases: matplotlib.cbook.converter
convert to a float or None
Bases: matplotlib.cbook.converter
convert to an int or None
Bases: matplotlib.cbook.converter
convert to string or None
Find index ranges where mask is False.
mask will be flattened if it is not already 1-D.
Returns Nx2 numpy.ndarray with each row the start and stop indices for slices of the compressed numpy.ndarray corresponding to each of N uninterrupted runs of unmasked values. If optional argument compressed is False, it returns the start and stop indices into the original numpy.ndarray, not the compressed numpy.ndarray. Returns None if there are no unmasked values.
Example:
y = ma.array(np.arange(5), mask = [0,0,1,0,0])
ii = unmasked_index_ranges(ma.getmaskarray(y))
# returns array [[0,2,] [2,4,]]
y.compressed()[ii[1,0]:ii[1,1]]
# returns array [3,4,]
ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False)
# returns array [[0, 2], [3, 5]]
y.filled()[ii[1,0]:ii[1,1]]
# returns array [3,4,]
Prior to the transforms refactoring, this was used to support masked arrays in Line2D.