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
signals is a sequence of valid signals
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.
For example:
>>> g = grouper.Grouper()
>>> g.join('a', 'b')
>>> g.join('b', 'c')
>>> g.join('d', 'e')
>>> list(g)
[['a', 'b', 'c'], ['d', 'e']]
>>> 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'
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: 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)
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().
Computes the distance between a set of successive points in N dimensions.
where X is an MxN array or matrix. The distances between successive rows is computed. Distance is the standard Euclidean distance.
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
seq is a list of words. Return the index into seq such that:
len(' '.join(seq[:ind])<=N
Like the Matlab (TM) function with the same name, returns true if the supplied numpy array or matrix looks like a vector, meaning it has a one non-singleton axis (i.e., it can have multiple axes, but all must have length 1, except for one of them).
If you just want to see if the array has 1 axis, use X.ndim==1
This function provides simple (but somewhat less so than simple_linear_interpolation) linear interpolation. simple_linear_interpolation will give a list of point between a start and an end, while this does true linear interpolation at an arbitrary set of points.
This is very inefficient linear interpolation meant to be used only for a small number of points in relatively non-intensive use cases.
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
Computes the distance travelled along a polygonal curve in N dimensions.
where X is an MxN array or matrix. Returns an array of length M consisting of the distance along the curve at each point (i.e., the rows of X).
Should behave like python2.3 dict.pop() method; d is a dict:
# returns value for key and deletes item; raises a KeyError if key
# is not in dict
val = popd(d, key)
# returns value for key if key exists, else default. Delete key,
# val item if it exists. Will not raise a KeyError
val = popd(d, key, default)
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.
Finds the length of a set of vectors in n dimensions. This is like the numpy norm function for vectors, but has the ability to work over a particular axis of the supplied array or matrix.
Computes (sum((x_i)^P))^(1/P) for each {x_i} being the elements of X along the given axis. If axis is None, compute over all elements of X.