diff options
author | Travis Oliphant <oliphant@enthought.com> | 2006-08-05 20:24:55 +0000 |
---|---|---|
committer | Travis Oliphant <oliphant@enthought.com> | 2006-08-05 20:24:55 +0000 |
commit | db349674856abc7b2652546e937c85dbbbebbf9c (patch) | |
tree | b40f595ec04a36881459922d642a2b0267c8159c | |
parent | 0072bd2837bcc89928fcc58e8ede88edbe1dcccd (diff) | |
download | numpy-db349674856abc7b2652546e937c85dbbbebbf9c.tar.gz |
Move source, info, and who to NumPy
-rw-r--r-- | numpy/lib/utils.py | 278 | ||||
-rw-r--r-- | numpy/numarray/alter_code1.py | 58 | ||||
-rw-r--r-- | numpy/numarray/convolve.py | 14 | ||||
-rw-r--r-- | numpy/numarray/image.py | 15 | ||||
-rw-r--r-- | numpy/numarray/nd_image.py | 14 |
5 files changed, 358 insertions, 21 deletions
diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 5e50ba487..14bc16680 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -1,10 +1,15 @@ import sys, os +import inspect +import types +import pydoc from numpy.core.numerictypes import obj2sctype from numpy.core.multiarray import dtype +from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', 'deprecate', 'get_numarray_include', - 'get_include', 'ctypes_load_library'] + 'get_include', 'ctypes_load_library', 'info', + 'source', 'who'] def issubclass_(arg1, arg2): try: @@ -107,7 +112,276 @@ def deprecate(func, oldname, newname): newfunc.__dict__.update(d) return newfunc - get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include') +#----------------------------------------------------------------------------- +# Function for output and information on the variables used. +#----------------------------------------------------------------------------- + + +def who(vardict=None): + """Print the scipy arrays in the given dictionary (or globals() if None). + """ + if vardict is None: + frame = sys._getframe().f_back + vardict = frame.f_globals + sta = [] + cache = {} + for name in vardict.keys(): + if isinstance(vardict[name],ndarray): + var = vardict[name] + idv = id(var) + if idv in cache.keys(): + namestr = name + " (%s)" % cache[idv] + original=0 + else: + cache[idv] = name + namestr = name + original=1 + shapestr = " x ".join(map(str, var.shape)) + bytestr = str(var.itemsize*product(var.shape)) + sta.append([namestr, shapestr, bytestr, var.dtype.name, + original]) + + maxname = 0 + maxshape = 0 + maxbyte = 0 + totalbytes = 0 + for k in range(len(sta)): + val = sta[k] + if maxname < len(val[0]): + maxname = len(val[0]) + if maxshape < len(val[1]): + maxshape = len(val[1]) + if maxbyte < len(val[2]): + maxbyte = len(val[2]) + if val[4]: + totalbytes += int(val[2]) + + if len(sta) > 0: + sp1 = max(10,maxname) + sp2 = max(10,maxshape) + sp3 = max(10,maxbyte) + prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') + print prval + "\n" + "="*(len(prval)+5) + "\n" + + for k in range(len(sta)): + val = sta[k] + print "%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), + val[1], ' '*(sp2-len(val[1])+5), + val[2], ' '*(sp3-len(val[2])+5), + val[3]) + print "\nUpper bound on total bytes = %d" % totalbytes + return + +#----------------------------------------------------------------------------- + + +# NOTE: pydoc defines a help function which works simliarly to this +# except it uses a pager to take over the screen. + +# combine name and arguments and split to multiple lines of +# width characters. End lines on a comma and begin argument list +# indented with the rest of the arguments. +def _split_line(name, arguments, width): + firstwidth = len(name) + k = firstwidth + newstr = name + sepstr = ", " + arglist = arguments.split(sepstr) + for argument in arglist: + if k == firstwidth: + addstr = "" + else: + addstr = sepstr + k = k + len(argument) + len(addstr) + if k > width: + k = firstwidth + 1 + len(argument) + newstr = newstr + ",\n" + " "*(firstwidth+2) + argument + else: + newstr = newstr + addstr + argument + return newstr + +_namedict = None +_dictlist = None + +# Traverse all module directories underneath globals +# to see if something is defined +def _makenamedict(module='numpy'): + module = __import__(module, globals(), locals(), []) + thedict = {module.__name__:module.__dict__} + dictlist = [module.__name__] + totraverse = [module.__dict__] + while 1: + if len(totraverse) == 0: + break + thisdict = totraverse.pop(0) + for x in thisdict.keys(): + if isinstance(thisdict[x],types.ModuleType): + modname = thisdict[x].__name__ + if modname not in dictlist: + moddict = thisdict[x].__dict__ + dictlist.append(modname) + totraverse.append(moddict) + thedict[modname] = moddict + return thedict, dictlist + + +def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): + """Get help information for a function, class, or module. + + Example: + >>> from numpy import * + >>> info(polyval) + polyval(p, x) + + Evaluate the polymnomial p at x. + + Description: + If p is of length N, this function returns the value: + p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] + """ + global _namedict, _dictlist + + if hasattr(object,'_ppimport_importer') or \ + hasattr(object, '_ppimport_module'): + object = object._ppimport_module + elif hasattr(object, '_ppimport_attr'): + object = object._ppimport_attr + + if object is None: + info(info) + elif isinstance(object, types.StringType): + if _namedict is None: + _namedict, _dictlist = _makenamedict(toplevel) + numfound = 0 + objlist = [] + for namestr in _dictlist: + try: + obj = _namedict[namestr][object] + if id(obj) in objlist: + print >> output, "\n *** Repeat reference found in %s *** " % namestr + else: + objlist.append(id(obj)) + print >> output, " *** Found in %s ***" % namestr + info(obj) + print >> output, "-"*maxwidth + numfound += 1 + except KeyError: + pass + if numfound == 0: + print >> output, "Help for %s not found." % object + else: + print >> output, "\n *** Total of %d references found. ***" % numfound + + elif inspect.isfunction(object): + name = object.func_name + arguments = apply(inspect.formatargspec, inspect.getargspec(object)) + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + print >> output, inspect.getdoc(object) + + elif inspect.isclass(object): + name = object.__name__ + if hasattr(object, '__init__'): + arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + else: + arguments = "()" + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + doc1 = inspect.getdoc(object) + if doc1 is None: + if hasattr(object,'__init__'): + print >> output, inspect.getdoc(object.__init__) + else: + print >> output, inspect.getdoc(object) + + methods = pydoc.allmethods(object) + if methods != []: + print >> output, "\n\nMethods:\n" + for meth in methods: + if meth[0] == '_': + continue + thisobj = getattr(object, meth, None) + if thisobj is not None: + methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None") + print >> output, " %s -- %s" % (meth, methstr) + + elif type(object) is types.InstanceType: ## check for __call__ method + print >> output, "Instance of class: ", object.__class__.__name__ + print >> output + if hasattr(object, '__call__'): + arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + + if hasattr(object,'name'): + name = "%s" % object.name + else: + name = "<name>" + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + doc = inspect.getdoc(object.__call__) + if doc is not None: + print >> output, inspect.getdoc(object.__call__) + print >> output, inspect.getdoc(object) + + else: + print >> output, inspect.getdoc(object) + + elif inspect.ismethod(object): + name = object.__name__ + arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + print >> output, inspect.getdoc(object) + + elif hasattr(object, '__doc__'): + print >> output, inspect.getdoc(object) + + +def source(object, output=sys.stdout): + """Write source for this object to output. + """ + try: + print >> output, "In file: %s\n" % inspect.getsourcefile(object) + print >> output, inspect.getsource(object) + except: + print >> output, "Not available for this object." + diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py index 72cc33acb..3fb1acd74 100644 --- a/numpy/numarray/alter_code1.py +++ b/numpy/numarray/alter_code1.py @@ -2,26 +2,46 @@ This module converts code written for Numeric to run with numpy Makes the following changes: - * Changes import statements (warns of use of from Numeric import *) - * Changes import statements (using numerix) ... + * Changes import statements + + Stubs for + convolve --> numarray.convolve + image --> numarray.image + nd_image --> numarray.nd_image + * Makes search and replace changes to: - - .typecode() - - .iscontiguous() - - .byteswapped() - - .itemsize() - - .toscalar() - * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] - * Replace xxx.spacesaver() with True - * Convert xx.savespace(?) to pass + ## xx.savespace(?) - - * Converts uses of 'b' to 'B' in the typecode-position of - functions: - eye, tri (in position 4) - ones, zeros, identity, empty, array, asarray, arange, - fromstring, indices, array_constructor (in position 2) - - and methods: - astype --- only argument + - .imaginary --> .imag + - .flat --> .ravel() (most of the time) + - .byteswapped() --> .byteswap(False) + - .byteswap() --> .byteswap(True) + - .info() --> numarray.info(self) + - .isaligned() --> .flags.aligned + - .isbyteswapped() --> (not .dtype.isnative) + - .typecode() --> .dtype.char + - .iscontiguous() --> .flags.contiguous + - .is_c_array() --> .flags.carray and .dtype.isnative + - .is_fortran_contiguous() --> .flags.fortran + - .is_f_array() --> .dtype.isnative and .flags.farray + - .itemsize() --> .itemsize + - .nelements() --> .size + - self.new(None) --> emtpy_like(self) + - self.new(type) --> empty(self.shape, type) + - .repeat(r) --> .repeat(r, axis=0) + - .size() --> .size + - .type() -- numarray.type(self.dtype) + - .typecode() --> .dtype.char + - .stddev() --> .std() + - .togglebyteorder() --> self.dtype=self.dtype.newbyteorder() + - .getshape() --> .shape + - .setshape(obj) --> .shape=obj + - .getflat() --> .ravel() + - .getreal() --> .real + - .setreal() --> .real = + - .getimag() --> .imag + - .setimag() --> .imag = + - .getimaginary() --> .imag + - .setimaginary() --> .imag + """ __all__ = ['fromfile', 'fromstr'] diff --git a/numpy/numarray/convolve.py b/numpy/numarray/convolve.py new file mode 100644 index 000000000..6c40ef111 --- /dev/null +++ b/numpy/numarray/convolve.py @@ -0,0 +1,14 @@ +try: + from stsci.convolve import * +except ImportError: + try: + from scipy.stsci.convolve import * + except ImportError: + msg = \ +"""The convolve package is not installed. + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) diff --git a/numpy/numarray/image.py b/numpy/numarray/image.py new file mode 100644 index 000000000..4ba23b68e --- /dev/null +++ b/numpy/numarray/image.py @@ -0,0 +1,15 @@ +try: + from stsci.image import * +except ImportError: + try: + from scipy.stsci.image import * + except ImportError: + msg = \ +"""The image package is not installed + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) + diff --git a/numpy/numarray/nd_image.py b/numpy/numarray/nd_image.py new file mode 100644 index 000000000..dff7fa066 --- /dev/null +++ b/numpy/numarray/nd_image.py @@ -0,0 +1,14 @@ +try: + from ndimage import * +except ImportError: + try: + from scipy.ndimage import * + except ImportError: + msg = \ +"""The nd_image package is not installed + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) |