diff options
113 files changed, 587 insertions, 649 deletions
diff --git a/numpy/__init__.py b/numpy/__init__.py index 0fbb2b875..f75b74f4d 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -9,7 +9,7 @@ the book "Guide to NumPy" at It is being distributed for a fee for only a few years to cover some of the costs of development. After the restriction period -it will also be freely available. +it will also be freely available. Additional documentation is available in the docstrings and at @@ -53,7 +53,7 @@ else: __all__ += core.__all__ __all__ += lib.__all__ __all__ += ['linalg', 'fft', 'random', 'ctypeslib'] - + if __doc__ is not None: __doc__ += """ @@ -69,9 +69,9 @@ fft --- Core FFT routines testing --- Numpy testing tools These packages require explicit import -f2py --- Fortran to Python Interface Generator. -distutils --- Enhancements to distutils with support for - Fortran compilers support and more. +f2py --- Fortran to Python Interface Generator. +distutils --- Enhancements to distutils with support for + Fortran compilers support and more. Global symbols from subpackages @@ -82,7 +82,7 @@ testing --> NumpyTest """ def test(level=1, verbosity=1): - if level <= 10: + if level <= 10: return NumpyTest().test(level, verbosity) else: return NumpyTest().testall(level, verbosity) diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 3b59c3cbe..ede2e9d80 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -364,8 +364,8 @@ add_newdoc('numpy.core.multiarray','lexsort', sorting on key[1], and so forth. The result is a sort on multiple keys. If the keys represented columns of a spreadsheet, for example, this would sort using multiple columns (the last key being used for the - primary sort order, the second-to-last key for the secondary sort order, - and so on). The keys argument must be a sequence of things that can be + primary sort order, the second-to-last key for the secondary sort order, + and so on). The keys argument must be a sequence of things that can be converted to arrays of the same shape. """) @@ -660,7 +660,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', order -- If a has fields defined, then the order keyword can be the field name to sort on or a list (or tuple) of field names to indicate the order that fields should be used to define - the sort. + the sort. Returns: array of indices that sort a along the specified axis. @@ -1035,7 +1035,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', order -- If a has fields defined, then the order keyword can be the field name to sort on or a list (or tuple) of field names to indicate the order that fields should be used to define - the sort. + the sort. Returns: None. diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py index 3684ba492..ba526b732 100644 --- a/numpy/core/_internal.py +++ b/numpy/core/_internal.py @@ -1,4 +1,3 @@ - #A place for code to be called from C-code # that implements more complicated stuff. @@ -40,7 +39,7 @@ def _makenames_list(adict): titles = [x[3] for x in allfields] return names, formats, offsets, titles - + # Called in PyArray_DescrConverter function when # a dictionary without "names" and "formats" # fields is used as a data-type descriptor. @@ -219,7 +218,7 @@ class _missing_ctypes(object): def c_void_p(self, num): return num - + class _ctypes(object): def __init__(self, array, ptr=None): try: @@ -233,7 +232,7 @@ class _ctypes(object): self._zerod = True else: self._zerod = False - + def data_as(self, obj): return self._ctypes.cast(self._data, obj) @@ -246,12 +245,12 @@ class _ctypes(object): if self._zerod: return None return (obj*self._arr.ndim)(*self._arr.strides) - + def get_data(self): return self._data def get_shape(self): - if self._zerod: + if self._zerod: return None return (_getintp_ctype()*self._arr.ndim)(*self._arr.shape) @@ -262,7 +261,7 @@ class _ctypes(object): def get_as_parameter(self): return self._ctypes.c_void_p(self._data) - + data = property(get_data, None, doc="c-types data") shape = property(get_shape, None, doc="c-types shape") strides = property(get_strides, None, doc="c-types strides") diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 390252368..f0629660a 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -125,7 +125,7 @@ def _leading_trailing(a): def _boolFormatter(x): if x: return ' True' else: return 'False' - + def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): diff --git a/numpy/core/code_generators/generate_array_api.py b/numpy/core/code_generators/generate_array_api.py index 5da4b2439..c6f73c33f 100644 --- a/numpy/core/code_generators/generate_array_api.py +++ b/numpy/core/code_generators/generate_array_api.py @@ -16,8 +16,8 @@ h_template = r""" #ifdef _MULTIARRAYMODULE typedef struct { - PyObject_HEAD - npy_bool obval; + PyObject_HEAD + npy_bool obval; } PyBoolScalarObject; diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 96a681d3c..26ef5218f 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -267,7 +267,7 @@ defdict = { Ufunc(2, 1, None, 'returns minimum (if x1 < x2: x1; else: x2) elementwise', TD(noobj), - TD(O, f='_npy_ObjectMin') + TD(O, f='_npy_ObjectMin') ), 'bitwise_and' : Ufunc(2, 1, One, diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index c77ec30be..4ce06b247 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -38,7 +38,7 @@ class chararray(ndarray): return self def __array_finalize__(self, obj): - # The b is a special case because it is used for reconstructing. + # The b is a special case because it is used for reconstructing. if not _globalvar and self.dtype.char not in 'SUb': raise ValueError, "Can only create a chararray from string data." @@ -52,23 +52,23 @@ class chararray(ndarray): val = temp return val - def __eq__(self, other): + def __eq__(self, other): return compare_chararrays(self, other, '==', True) - def __ne__(self, other): + def __ne__(self, other): return compare_chararrays(self, other, '!=', True) def __ge__(self, other): - return compare_chararrays(self, other, '>=', True) + return compare_chararrays(self, other, '>=', True) def __le__(self, other): - return compare_chararrays(self, other, '<=', True) + return compare_chararrays(self, other, '<=', True) def __gt__(self, other): return compare_chararrays(self, other, '>', True) def __lt__(self, other): - return compare_chararrays(self, other, '<', True) + return compare_chararrays(self, other, '<', True) def __add__(self, other): b = broadcast(self, other) diff --git a/numpy/core/defmatrix.py b/numpy/core/defmatrix.py index becfa74c9..e64fd8c6d 100644 --- a/numpy/core/defmatrix.py +++ b/numpy/core/defmatrix.py @@ -1,4 +1,3 @@ - __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] import numeric as N @@ -135,7 +134,7 @@ class matrix(N.ndarray): if out.ndim == 0: return out[()] if out.ndim == 1: - sh = out.shape[0] + sh = out.shape[0] # Determine when we should have a column array try: n = len(index) @@ -146,14 +145,14 @@ class matrix(N.ndarray): else: out.shape = (1,sh) return out - + def _get_truendim(self): shp = self.shape truend = 0 for val in shp: if (val > 1): truend += 1 return truend - + def __mul__(self, other): if isinstance(other, N.ndarray) or N.isscalar(other) or \ @@ -249,28 +248,28 @@ class matrix(N.ndarray): def var(self, axis=None, dtype=None, out=None): return N.ndarray.var(self, axis, dtype, out)._align(axis) - + def prod(self, axis=None, dtype=None, out=None): return N.ndarray.prod(self, axis, dtype, out)._align(axis) - + def any(self, axis=None, out=None): - return N.ndarray.any(self, axis, out)._align(axis) + return N.ndarray.any(self, axis, out)._align(axis) def all(self, axis=None, out=None): return N.ndarray.all(self, axis, out)._align(axis) - + def max(self, axis=None, out=None): return N.ndarray.max(self, axis, out)._align(axis) def argmax(self, axis=None, out=None): return N.ndarray.argmax(self, axis, out)._align(axis) - + def min(self, axis=None, out=None): return N.ndarray.min(self, axis, out)._align(axis) - + def argmin(self, axis=None, out=None): return N.ndarray.argmin(self, axis, out)._align(axis) - + def ptp(self, axis=None, out=None): return N.ndarray.ptp(self, axis, out)._align(axis) @@ -289,10 +288,10 @@ class matrix(N.ndarray): def getA(self): return self.__array__() - + def getA1(self): return self.__array__().ravel() - + def getT(self): return self.transpose() @@ -300,7 +299,7 @@ class matrix(N.ndarray): if issubclass(self.dtype.type, N.complexfloating): return self.transpose().conjugate() else: - return self.transpose() + return self.transpose() T = property(getT, None, doc="transpose") A = property(getA, None, doc="base array") diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index e153f6061..e80006a15 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -124,13 +124,13 @@ def sort(a, axis=-1, kind='quicksort', order=None): axis -- axis to be sorted (default -1). Can be None to indicate that a flattened and sorted array should - be returned (the array method does not support this). + be returned (the array method does not support this). kind -- sorting algorithm (default 'quicksort') Possible values: 'quicksort', 'mergesort', or 'heapsort'. order -- For an array with fields defined, this argument allows specification of which fields to compare first, second, etc. Not all fields need be specified. - + Returns: None. @@ -171,7 +171,7 @@ def argsort(a, axis=-1, kind='quicksort', order=None): axis -- axis to be indirectly sorted (default -1) Can be None to indicate return indices into the - flattened array. + flattened array. kind -- sorting algorithm (default 'quicksort') Possible values: 'quicksort', 'mergesort', or 'heapsort' order -- For an array with fields defined, this argument allows diff --git a/numpy/core/ma.py b/numpy/core/ma.py index 5bd7ed7d2..fc1e89d7b 100644 --- a/numpy/core/ma.py +++ b/numpy/core/ma.py @@ -2101,7 +2101,7 @@ def diagonal(a, k = 0, axis1=0, axis2=1): return masked_array(d, m) else: return masked_array(d, fromnumeric.diagonal(m, k, axis1, axis2)) - + def trace (a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. @@ -2177,7 +2177,7 @@ array.choose = _m(_choose) del _choose def _clip(self,a_min,a_max,out=None): - return MaskedArray(data = self.data.clip(asarray(a_min).data, + return MaskedArray(data = self.data.clip(asarray(a_min).data, asarray(a_max).data), mask = mask_or(self.mask, mask_or(getmask(a_min),getmask(a_max)))) @@ -2215,7 +2215,7 @@ array.getfield = _m(not_implemented) def _max(a, axis=None, out=None): if out is not None: - raise TypeError("Output arrays Unsupported for masked arrays") + raise TypeError("Output arrays Unsupported for masked arrays") if axis is None: return maximum(a) else: @@ -2254,7 +2254,7 @@ def _squeeze(self): except AttributeError: result = _wrapit(self, 'squeeze') return result -array.squeeze = _m(_squeeze) +array.squeeze = _m(_squeeze) array.strides = property(_m(not_implemented)) array.sum = _m(sum) diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 0905b3939..4329cae5c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -159,7 +159,7 @@ def require(a, dtype=None, requirements=None): subok = 0 else: subok = 1 - + arr = array(a, dtype=dtype, copy=False, subok=subok) copychar = 'A' @@ -176,7 +176,7 @@ def require(a, dtype=None, requirements=None): if not arr.flags[prop]: arr = arr.copy(copychar) break - return arr + return arr def isfortran(a): """Returns True if 'a' is arranged in Fortran-order in memory with a.ndim > 1 @@ -240,7 +240,7 @@ def outer(a,b): def vdot(a, b): """Returns the dot product of 2 vectors (or anything that can be made into a vector). - + Note: this is not the same as `dot`, as it takes the conjugate of its first argument if complex and always returns a scalar.""" return dot(asarray(a).ravel().conj(), asarray(b).ravel()) @@ -265,7 +265,7 @@ def tensordot(a, b, axes=2): the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argument sequence - determines the axis or axes in arr2 to sum over. + determines the axis or axes in arr2 to sum over. When there is more than one axis to sum over, the corresponding arguments to axes should be sequences of the same length with the first @@ -273,7 +273,7 @@ def tensordot(a, b, axes=2): and so forth. If the axes argument is an integer, N, then the last N dimensions of a - and first N dimensions of b are summed over. + and first N dimensions of b are summed over. """ try: iter(axes) @@ -375,8 +375,8 @@ def rollaxis(a, axis, start=0): raise ValueError, msg % ('axis', axis, n) if not (0 <= start < n+1): raise ValueError, msg % ('start', start, n+1) - if (axis < start): # it's been removed - start -= 1 + if (axis < start): # it's been removed + start -= 1 if axis==start: return a axes = range(0,n) @@ -488,7 +488,7 @@ def indices(dimensions, dtype=int): def fromfunction(function, shape, **kwargs): """Returns an array constructed by calling a function on a tuple of number grids. - + The function should accept as many arguments as the length of shape and work on array inputs. The shape argument is a sequence of numbers indicating the length of the desired output for each axis. @@ -496,7 +496,7 @@ def fromfunction(function, shape, **kwargs): The function can also accept keyword arguments (except dtype), which will be passed through fromfunction to the function itself. The dtype argument (default float) determines the data-type of the index grid passed to the - function. + function. """ dtype = kwargs.pop('dtype', float) args = indices(shape, dtype=dtype) @@ -532,7 +532,7 @@ _lkup = { 'C':'1100', 'D':'1101', 'E':'1110', - 'F':'1111', + 'F':'1111', 'L':''} def binary_repr(num): @@ -698,7 +698,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): FloatingPointError: overflow encountered in short_scalars >>> seterr(all='ignore') {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} - + """ pyvals = umath.geterrobj() @@ -785,16 +785,16 @@ def geterrcall(): """ return umath.geterrobj()[2] -class _unspecified(object): +class _unspecified(object): pass _Unspecified = _unspecified() class errstate(object): """with errstate(**state): --> operations in following block use given state. - + # Set error handling to known state. - >>> _ = seterr(invalid='raise', divide='raise', over='raise', under='ignore') - + >>> _ = seterr(invalid='raise', divide='raise', over='raise', under='ignore') + |>> a = -arange(3) |>> with errstate(invalid='ignore'): ... print sqrt(a) @@ -812,7 +812,7 @@ class errstate(object): Traceback (most recent call last): ... FloatingPointError: divide by zero encountered in divide - + """ # Note that we don't want to run the above doctests because they will fail # without a from __future__ import with_statement diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index bc9fbe41e..0836241cd 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -216,7 +216,7 @@ def _add_integer_aliases(): Intname = 'Int%d' % bits uval = typeinfo['U'+ctype] typeobj = val[-1] - utypeobj = uval[-1] + utypeobj = uval[-1] if intname not in allTypes.keys(): uintname = 'uint%d' % bits allTypes[intname] = typeobj diff --git a/numpy/core/records.py b/numpy/core/records.py index 838372cf2..b8fca5d0b 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -1,4 +1,4 @@ -# All of the functions allow formats to be a dtype +# All of the functions allow formats to be a dtype __all__ = ['record', 'recarray', 'format_parser'] import numeric as sb @@ -110,7 +110,7 @@ class format_parser: if (byteorder is not None): byteorder = _byteorderconv[byteorder[0]] descr = descr.newbyteorder(byteorder) - + self._descr = descr class record(nt.void): @@ -129,7 +129,7 @@ class record(nt.void): pass fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr,None) - if res: + if res: obj = self.getfield(*res[:2]) # if it has fields return a recarray, # if it's a string return 'SU' return a chararray @@ -142,7 +142,7 @@ class record(nt.void): else: raise AttributeError, "'record' object has no "\ "attribute '%s'" % attr - + def __setattr__(self, attr, val): if attr in ['setfield', 'getfield', 'dtype']: @@ -171,7 +171,7 @@ class recarray(ndarray): def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False): - + if dtype is not None: descr = sb.dtype(dtype) else: @@ -207,7 +207,7 @@ class recarray(ndarray): # Save the dictionary # If the attr is a field name and not in the saved dictionary # Undo any "setting" of the attribute and do a setfield -# Thus, you can't create attributes on-the-fly that are field names. +# Thus, you can't create attributes on-the-fly that are field names. def __setattr__(self, attr, val): newattr = attr not in self.__dict__ @@ -224,14 +224,14 @@ class recarray(ndarray): return ret if newattr: # We just added this one try: # or this setattr worked on an internal - # attribute. + # attribute. object.__delattr__(self, attr) except: return ret try: res = fielddict[attr][:2] except (TypeError,KeyError): - raise AttributeError, "record array has no attribute %s" % attr + raise AttributeError, "record array has no attribute %s" % attr return self.setfield(val,*res) def __getitem__(self, indx): @@ -268,8 +268,8 @@ class recarray(ndarray): dtype = sb.dtype(obj) if dtype.fields is None: return self.__array__().view(dtype) - return ndarray.view(self, obj) - + return ndarray.view(self, obj) + def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a record array from a (flat) list of arrays @@ -284,9 +284,9 @@ def fromarrays(arrayList, dtype=None, shape=None, formats=None, >>> r.a array([1, 2, 3, 4]) """ - + arrayList = [sb.asarray(x) for x in arrayList] - + if shape is None or shape == 0: shape = arrayList[0].shape @@ -318,18 +318,18 @@ def fromarrays(arrayList, dtype=None, shape=None, formats=None, if len(descr) != len(arrayList): raise ValueError, "mismatch between the number of fields "\ "and the number of arrays" - + d0 = descr[0].shape nn = len(d0) if nn > 0: shape = shape[:-nn] - + for k, obj in enumerate(arrayList): nn = len(descr[k].shape) testshape = obj.shape[:len(obj.shape)-nn] if testshape != shape: raise ValueError, "array-shape mismatch in array %d" % k - + _array = recarray(shape, descr) # populate the record array (makes a copy) @@ -369,7 +369,7 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, (2, 'de', 1.3) ] """ - + nfields = len(recList[0]) if formats is None and dtype is None: # slower obj = sb.array(recList,dtype=object) @@ -400,7 +400,7 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, retval.shape = shape res = retval.view(recarray) - + res.dtype = sb.dtype((record, res.dtype)) return res @@ -409,7 +409,7 @@ def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a (read-only) record array from binary data contained in a string""" - + if dtype is None and formats is None: raise ValueError, "Must have dtype= or formats=" @@ -418,11 +418,11 @@ def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, descr = sb.dtype(dtype) else: descr = format_parser(formats, names, titles, aligned, byteorder)._descr - + itemsize = descr.itemsize if (shape is None or shape == 0 or shape == -1): shape = (len(datastring)-offset) / itemsize - + _array = recarray(shape, descr, buf=datastring, offset=offset) return _array @@ -465,7 +465,7 @@ def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, if (offset > 0): fd.seek(offset, 1) size = get_remaining_size(fd) - + if dtype is not None: descr = sb.dtype(dtype) else: @@ -520,7 +520,7 @@ def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, 'aligned' : aligned, 'byteorder' : byteorder } - + if obj is None: if shape is None: raise ValueError("Must define a shape if obj is None") diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 7953ba576..ac13f10c8 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -1,4 +1,3 @@ - import imp import os import sys @@ -54,7 +53,7 @@ def configuration(parent_package='',top_path=None): # which is done in error-handling # ufunc code. NPY_ALLOW_C_API and friends # cause the segfault. So, we disable threading - # for now. + # for now. if sys.version[:5] < '2.4.2': nosmp = 1 else: @@ -100,7 +99,7 @@ def configuration(parent_package='',top_path=None): if sys.platform == 'win32': moredefs.append('NPY_NO_SIGNAL') - + if sys.version[:3] < '2.4': if config_cmd.check_func('strtod', decl=False, headers=['stdlib.h']): diff --git a/numpy/core/tests/test_defmatrix.py b/numpy/core/tests/test_defmatrix.py index 27e72f3b5..1330bfff2 100644 --- a/numpy/core/tests/test_defmatrix.py +++ b/numpy/core/tests/test_defmatrix.py @@ -177,8 +177,8 @@ class test_indexing(NumpyTestCase): y = zeros((3,1),float) y[:,0] = [0.8,0.2,0.3] x[:,1] = y>0.5 - assert_equal(x, [[0,1],[0,0],[0,0]]) - + assert_equal(x, [[0,1],[0,0],[0,0]]) + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py index f0f894655..a7ce798b0 100644 --- a/numpy/core/tests/test_errstate.py +++ b/numpy/core/tests/test_errstate.py @@ -1,4 +1,3 @@ -
# The following exec statement (or something like it) is needed to
# prevent SyntaxError on Python < 2.5. Even though this is a test,
# SyntaxErrors are not acceptable; on Debian systems, they block
@@ -17,7 +16,7 @@ from numpy.testing import * class test_errstate(NumpyTestCase):
-
+
def test_invalid(self):
with errstate(all='raise', under='ignore'):
a = -arange(3)
@@ -31,7 +30,7 @@ class test_errstate(NumpyTestCase): pass
else:
self.fail()
-
+
def test_divide(self):
with errstate(all='raise', under='ignore'):
a = -arange(3)
@@ -45,7 +44,7 @@ class test_errstate(NumpyTestCase): pass
else:
self.fail()
-
+
def test_errcall(self):
def foo(*args):
print args
diff --git a/numpy/core/tests/test_ma.py b/numpy/core/tests/test_ma.py index d37ae5625..00bd5c86d 100644 --- a/numpy/core/tests/test_ma.py +++ b/numpy/core/tests/test_ma.py @@ -715,32 +715,32 @@ class test_ufuncs(NumpyTestCase): class test_array_methods(NumpyTestCase): - + def setUp(self): - x = numpy.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928, - 8.43 , 7.78 , 9.865, 5.878, 8.979, 4.732, - 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, + x = numpy.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928, + 8.43 , 7.78 , 9.865, 5.878, 8.979, 4.732, + 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04 , 9.63 , 7.712, 3.382, 4.489, 6.479, - 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, + 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993]) X = x.reshape(6,6) XX = x.reshape(3,2,2,3) - - m = numpy.array([0, 1, 0, 1, 0, 0, - 1, 0, 1, 1, 0, 1, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, 1, 1, 1, - 1, 0, 0, 1, 0, 0, + + m = numpy.array([0, 1, 0, 1, 0, 0, + 1, 0, 1, 1, 0, 1, + 0, 0, 0, 1, 0, 1, + 0, 0, 0, 1, 1, 1, + 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]) mx = array(data=x,mask=m) mX = array(data=X,mask=m.reshape(X.shape)) mXX = array(data=XX,mask=m.reshape(XX.shape)) - - m2 = numpy.array([1, 1, 0, 1, 0, 0, - 1, 1, 1, 1, 0, 1, - 0, 0, 1, 1, 0, 1, - 0, 0, 0, 1, 1, 1, - 1, 0, 0, 1, 1, 0, + + m2 = numpy.array([1, 1, 0, 1, 0, 0, + 1, 1, 1, 1, 0, 1, + 0, 0, 1, 1, 0, 1, + 0, 0, 0, 1, 1, 1, + 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]) m2x = array(data=x,mask=m2) m2X = array(data=X,mask=m2.reshape(X.shape)) @@ -789,14 +789,14 @@ class test_array_methods(NumpyTestCase): self.failUnless(eq(mXcp.data,mX.filled(1).cumprod(0))) mXcp = mX.cumprod(1) self.failUnless(eq(mXcp.data,mX.filled(1).cumprod(1))) - + def test_cumsum(self): (x,X,XX,m,mx,mX,mXX,) = self.d mXcp = mX.cumsum(0) self.failUnless(eq(mXcp.data,mX.filled(0).cumsum(0))) mXcp = mX.cumsum(1) self.failUnless(eq(mXcp.data,mX.filled(0).cumsum(1))) - + def test_varstd(self): (x,X,XX,m,mx,mX,mXX,) = self.d self.failUnless(eq(mX.var(axis=None),mX.compressed().var())) @@ -809,7 +809,7 @@ class test_array_methods(NumpyTestCase): self.failUnless(eq(mXvar0[k],mX[:,k].compressed().var())) self.failUnless(eq(numpy.sqrt(mXvar0[k]), mX[:,k].compressed().std())) - + def eqmask(m1, m2): if m1 is nomask: diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 58c93947d..ef2f0baad 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1,4 +1,3 @@ - from numpy.testing import * from numpy.core import * from numpy import random @@ -196,7 +195,7 @@ class test_zero_rank(NumpyTestCase): def check_output(self): x = array(2) self.failUnlessRaises(ValueError, add, x, [1], x) - + class test_creation(NumpyTestCase): def check_from_attribute(self): class x(object): @@ -283,23 +282,23 @@ class test_pickling(NumpyTestCase): p = loads(s) assert_equal(a, p) -class test_fancy_indexing(NumpyTestCase): - def check_list(self): - x = ones((1,1)) - x[:,[0]] = 2.0 - assert_array_equal(x, array([[2.0]])) +class test_fancy_indexing(NumpyTestCase): + def check_list(self): + x = ones((1,1)) + x[:,[0]] = 2.0 + assert_array_equal(x, array([[2.0]])) - x = ones((1,1,1)) - x[:,:,[0]] = 2.0 - assert_array_equal(x, array([[[2.0]]])) + x = ones((1,1,1)) + x[:,:,[0]] = 2.0 + assert_array_equal(x, array([[[2.0]]])) - def check_tuple(self): - x = ones((1,1)) - x[:,(0,)] = 2.0 - assert_array_equal(x, array([[2.0]])) - x = ones((1,1,1)) - x[:,:,(0,)] = 2.0 - assert_array_equal(x, array([[[2.0]]])) + def check_tuple(self): + x = ones((1,1)) + x[:,(0,)] = 2.0 + assert_array_equal(x, array([[2.0]])) + x = ones((1,1,1)) + x[:,:,(0,)] = 2.0 + assert_array_equal(x, array([[[2.0]]])) class test_string_compare(NumpyTestCase): def check_string(self): @@ -309,8 +308,8 @@ class test_string_compare(NumpyTestCase): assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) - assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) + assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) + assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) def check_mixed(self): g1 = array(["spam","spa","spammer","and eggs"]) @@ -321,7 +320,7 @@ class test_string_compare(NumpyTestCase): assert_array_equal(g1 > g2, [x > g2 for x in g1]) assert_array_equal(g1 <= g2, [x <= g2 for x in g1]) assert_array_equal(g1 >= g2, [x >= g2 for x in g1]) - + def check_unicode(self): g1 = array([u"This",u"is",u"example"]) @@ -330,8 +329,8 @@ class test_string_compare(NumpyTestCase): assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0,1,2]]) assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0,1,2]]) assert_array_equal(g1 >= g2, [g1[i] >= g2[i] for i in [0,1,2]]) - assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) - assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) + assert_array_equal(g1 < g2, [g1[i] < g2[i] for i in [0,1,2]]) + assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0,1,2]]) class test_argmax(NumpyTestCase): @@ -339,10 +338,10 @@ class test_argmax(NumpyTestCase): a = random.normal(0,1,(4,5,6,7,8)) for i in xrange(a.ndim): amax = a.max(i) - aargmax = a.argmax(i) + aargmax = a.argmax(i) axes = range(a.ndim) axes.remove(i) - assert all(amax == aargmax.choose(*a.transpose(i,*axes))) + assert all(amax == aargmax.choose(*a.transpose(i,*axes))) class test_newaxis(NumpyTestCase): def check_basic(self): diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index ea2486972..7242d17d0 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -8,7 +8,7 @@ class Vec: def __init__(self,sequence=None): if sequence is None: sequence=[] - self.array=array(sequence) + self.array=array(sequence) def __add__(self,other): out=Vec() out.array=self.array+other.array @@ -118,7 +118,7 @@ class test_dot(NumpyTestCase): b2 = rand(1,1) c1 = dot(b1,b2) c2 = dot_(b1,b2) - assert_almost_equal(c1, c2, decimal=self.N) + assert_almost_equal(c1, c2, decimal=self.N) def check_all(self): dims = [(),(1,),(1,1)] @@ -196,14 +196,14 @@ class test_seterr(NumpyTestCase): self.fail() seterr(divide='ignore') array([1.]) / array([0.]) - - + + class test_fromiter(NumpyTestCase): - + def makegen(self): for x in xrange(24): yield x**2 - + def test_types(self): ai32 = fromiter(self.makegen(), int32) ai64 = fromiter(self.makegen(), int64) @@ -247,7 +247,7 @@ class test_binary_repr(NumpyTestCase): def test_large(self): assert_equal(binary_repr(10736848),'101000111101010011010000') - + import sys if sys.version_info[:2] >= (2, 5): set_local_path() diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index ae52f8603..b6a7f6202 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -50,7 +50,7 @@ Ndescr = [ ('z2', 'b1')]), ('color', 'S2'), ('info', [ - ('Name', 'U8'), + ('Name', 'U8'), ('Value', 'c16')]), ('y', 'f8', (2, 2)), ('z', 'u1')] @@ -333,7 +333,7 @@ class test_read_values_nested_multiple(read_values_nested, NumpyTestCase): class test_empty_field(NumpyTestCase): def check_assign(self): - a = numpy.arange(10, dtype=numpy.float32) + a = numpy.arange(10, dtype=numpy.float32) a.dtype = [("int", "<0i4"),("float", "<2f4")] assert(a['int'].shape == (5,0)) assert(a['float'].shape == (5,2)) diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 078114dae..1839874a5 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -1,4 +1,3 @@ - from numpy.testing import * set_package_path() import numpy.core.umath as ncu @@ -11,7 +10,7 @@ types = [N.bool_, N.byte, N.ubyte, N.short, N.ushort, N.intc, N.uintc, N.single, N.double, N.longdouble, N.csingle, N.cdouble, N.clongdouble] -# This compares scalarmath against ufuncs. +# This compares scalarmath against ufuncs. class test_types(NumpyTestCase): def check_types(self, level=1): diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 13a1ce31e..37d361db9 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -1,4 +1,3 @@ - from numpy.testing import * set_package_path() from numpy.core.umath import minimum, maximum, exp @@ -167,7 +166,7 @@ class _test_complex_real(NumpyTestCase): def setUp(self): self.x = 0.52 self.z = self.x+0j - self.funcs = ['arcsin', 'arccos', 'arctan', 'arcsinh', 'arccosh', + self.funcs = ['arcsin', 'arccos', 'arctan', 'arcsinh', 'arccosh', 'arctanh', 'sin', 'cos', 'tan', 'exp', 'log', 'sqrt', 'log10'] def test_it(self): diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index 08c190a17..3a9ee48dc 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -192,7 +192,7 @@ def CCompiler_customize(self, dist, need_cxx=0): # not valid for C++ code, only for C. Remove it if it's there to # avoid a spurious warning on every compilation. All the default # options used by distutils can be extracted with: - + # from distutils import sysconfig # sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', # 'CCSHARED', 'LDSHARED', 'SO') @@ -200,7 +200,7 @@ def CCompiler_customize(self, dist, need_cxx=0): self.compiler_so.remove('-Wstrict-prototypes') except (AttributeError, ValueError): pass - + if hasattr(self,'compiler') and self.compiler[0].find('cc')>=0: if not self.compiler_cxx: if self.compiler[0][:3] == 'gcc': diff --git a/numpy/distutils/command/build_clib.py b/numpy/distutils/command/build_clib.py index de1781991..f53c77ffb 100644 --- a/numpy/distutils/command/build_clib.py +++ b/numpy/distutils/command/build_clib.py @@ -110,7 +110,7 @@ class build_clib(old_build_clib): sources = list(sources) - + lib_file = compiler.library_filename(lib_name, output_dir=self.build_clib) @@ -135,7 +135,7 @@ class build_clib(old_build_clib): force=self.force, requiref90=requiref90) fcompiler.customize(config_fc) - + macros = build_info.get('macros') include_dirs = build_info.get('include_dirs') extra_postargs = build_info.get('extra_compiler_args') or [] diff --git a/numpy/distutils/command/config_compiler.py b/numpy/distutils/command/config_compiler.py index 8e23a3d3d..30a21dd7d 100644 --- a/numpy/distutils/command/config_compiler.py +++ b/numpy/distutils/command/config_compiler.py @@ -1,4 +1,3 @@ - import sys from distutils.core import Command @@ -9,7 +8,7 @@ def show_fortran_compilers(_cache=[]): # Using cache to prevent infinite recursion if _cache: return _cache.append(1) - + from numpy.distutils.fcompiler import show_fcompilers import distutils.core dist = distutils.core._setup_distribution diff --git a/numpy/distutils/fcompiler/g95.py b/numpy/distutils/fcompiler/g95.py index 7a42c3d11..8fe79bfbb 100644 --- a/numpy/distutils/fcompiler/g95.py +++ b/numpy/distutils/fcompiler/g95.py @@ -16,7 +16,7 @@ class G95FCompiler(FCompiler): version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95 (?P<version>.*)!\) (?P<date>.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) - + executables = { 'version_cmd' : ["g95", "--version"], diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index 6e0f1895d..ac7984ebc 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -1,4 +1,3 @@ - import re import os import sys @@ -275,7 +274,7 @@ class Gnu95FCompiler(GnuFCompiler): def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': - opt.remove('cc_dynamic') + opt.remove('cc_dynamic') return opt if __name__ == '__main__': diff --git a/numpy/distutils/interactive.py b/numpy/distutils/interactive.py index dd3ab2f34..46bc6eeca 100644 --- a/numpy/distutils/interactive.py +++ b/numpy/distutils/interactive.py @@ -1,4 +1,3 @@ - import os import sys from pprint import pformat @@ -12,7 +11,7 @@ def show_information(*args): for a in ['name']: print 'os.%s = %s' % (a,pformat(getattr(os,a))) if hasattr(os,'uname'): - print 'system,node,release,version,machine = ',os.uname() + print 'system,node,release,version,machine = ',os.uname() def show_environ(*args): for k,i in os.environ.items(): @@ -29,7 +28,7 @@ def show_compilers(*args): def show_tasks(argv,ccompiler,fcompiler): print """\ -Tasks: +Tasks: i - Show python/platform/machine information ie - Show environment information c - Show C compilers information @@ -65,7 +64,7 @@ def edit_argv(*args): if s: argv[1:] = splitcmdline(s) return - + def interactive_sys_argv(argv): print '='*72 print 'Starting interactive session' @@ -186,4 +185,3 @@ def interactive_sys_argv(argv): print '-'*72 return argv - diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index 384d7f2d7..92dbda2b8 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -972,9 +972,9 @@ class Configuration(object): return def add_numarray_include_dirs(self): - import numpy.numarray.util as nnu - self.add_include_dirs(*nnu.get_numarray_include_dirs()) - + import numpy.numarray.util as nnu + self.add_include_dirs(*nnu.get_numarray_include_dirs()) + def add_headers(self,*files): """ Add installable headers to configuration. Argument(s) can be either diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 3aa359aa1..4899c8a5e 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -1114,7 +1114,7 @@ def get_atlas_version(**config): if _cached_atlas_version.has_key(key): return _cached_atlas_version[key] c = cmd_config(Distribution()) - atlas_version = None + atlas_version = None try: s, o = c.get_output(atlas_version_c_text, libraries=libraries, library_dirs=library_dirs) diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index 8d7c156df..bc9fb28c1 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -85,7 +85,7 @@ if using_newcore: 'complex_long_double':'PyArray_CDOUBLE', 'string':'PyArray_CHAR', # f2py 2e is not ready for PyArray_STRING (must set itemisize etc) #'string':'PyArray_STRING' - + } c2pycode_map={'double':'d', 'float':'f', diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py index f94712105..03085c28e 100644 --- a/numpy/f2py/f2py_testing.py +++ b/numpy/f2py/f2py_testing.py @@ -1,4 +1,3 @@ - import os,sys,re,time def cmdline(): diff --git a/numpy/f2py/lib/main.py b/numpy/f2py/lib/main.py index 45fd09946..911576d7d 100644 --- a/numpy/f2py/lib/main.py +++ b/numpy/f2py/lib/main.py @@ -159,7 +159,7 @@ def get_signature_output(sys_argv): def parse_files(sys_argv): flag = 'file' - file_names = [] + file_names = [] only_names = [] skip_names = [] options = [] @@ -206,7 +206,7 @@ def dump_signature(sys_argv): output_stream = open(signature_output,'w') flag = 'file' - file_names = [] + file_names = [] only_names = [] skip_names = [] options = [] @@ -245,7 +245,7 @@ def dump_signature(sys_argv): output_stream.write(block.topyf(' ')+'\n') output_stream.write(' END INTERFACE\n') output_stream.write('END PYTHON MODULE %s\n' % (modulename)) - + if signature_output not in ['stdout','stderr']: output_stream.close() return diff --git a/numpy/f2py/lib/parser/Fortran2003.py b/numpy/f2py/lib/parser/Fortran2003.py index e655ab5d2..bfdb8cbba 100644 --- a/numpy/f2py/lib/parser/Fortran2003.py +++ b/numpy/f2py/lib/parser/Fortran2003.py @@ -254,7 +254,7 @@ class SequenceBase(Base): def torepr(self): return '%s(%r, %r)' % (self.__class__.__name__, self.separator, self.items) def compare(self, other): return cmp((self.separator,self.items),(other.separator,self.items)) - + class UnaryOpBase(Base): """ <unary-op-base> = <unary-op> <rhs> @@ -265,7 +265,7 @@ class UnaryOpBase(Base): m = op_pattern.match(string) if not m: return #if not m: return rhs_cls(string) - rhs = string[m.end():].lstrip() + rhs = string[m.end():].lstrip() if not rhs: return op = string[:m.end()].rstrip().upper() return op, rhs_cls(rhs) @@ -779,7 +779,7 @@ class Executable_Construct(Base):# R213 class Executable_Construct_C201(Base): subclass_names = Executable_Construct.subclass_names[:] subclass_names[subclass_names.index('Action_Stmt')] = 'Action_Stmt_C201' - + class Action_Stmt(Base):# R214 """ @@ -966,7 +966,7 @@ class Intrinsic_Type_Spec(WORDClsBase): # R403 """ subclass_names = [] use_names = ['Kind_Selector','Char_Selector'] - + def match(string): for w,cls in [('INTEGER',Kind_Selector), ('REAL',Kind_Selector), @@ -1243,7 +1243,7 @@ class Logical_Literal_Constant(NumberBase): # R428 """ subclass_names = [] def match(string): - return NumberBase.match(pattern.abs_logical_literal_constant_named, string) + return NumberBase.match(pattern.abs_logical_literal_constant_named, string) match = staticmethod(match) class Derived_Type_Def(Base): # R429 @@ -1394,7 +1394,7 @@ class Type_Param_Decl(BinaryOpBase): # R436 if not lhs or not rhs: return return Type_Param_Name(lhs),'=',Scalar_Int_Initialization_Expr(rhs) match = staticmethod(match) - + class Type_Param_Attr_Spec(STRINGBase): # R437 """ <type-param-attr-spec> = KIND @@ -1814,7 +1814,7 @@ class Ac_Implied_Do(Base): # R470 <ac-implied-do> = ( <ac-value-list> , <ac-implied-do-control> ) """ subclass_names = [] - use_names = ['Ac_Value_List','Ac_Implied_Do_Control'] + use_names = ['Ac_Value_List','Ac_Implied_Do_Control'] def match(string): if string[0]+string[-1] != '()': return line, repmap = string_replace_map(string[1:-1].strip()) @@ -1830,7 +1830,7 @@ class Ac_Implied_Do(Base): # R470 class Ac_Implied_Do_Control(Base): # R471 """ - <ac-implied-do-control> = <ac-do-variable> = <scalar-int-expr> , <scalar-int-expr> [ , <scalar-int-expr> ] + <ac-implied-do-control> = <ac-do-variable> = <scalar-int-expr> , <scalar-int-expr> [ , <scalar-int-expr> ] """ subclass_names = [] use_names = ['Ac_Do_Variable','Scalar_Int_Expr'] @@ -1849,7 +1849,7 @@ class Ac_Implied_Do_Control(Base): # R471 class Ac_Do_Variable(Base): # R472 """ <ac-do-variable> = <scalar-int-variable> - <ac-do-variable> shall be a named variable + <ac-do-variable> shall be a named variable """ subclass_names = ['Scalar_Int_Variable'] @@ -2021,7 +2021,7 @@ class Entity_Decl(Base): # R504 if self.items[3] is not None: s += ' ' + str(self.items[3]) return s - + class Object_Name(Base): # R505 """ <object-name> = <name> @@ -2031,7 +2031,7 @@ class Object_Name(Base): # R505 class Initialization(Base): # R506 """ <initialization> = = <initialization-expr> - | => <null-init> + | => <null-init> """ subclass_names = [] use_names = ['Initialization_Expr', 'Null_Init'] @@ -2122,7 +2122,7 @@ class Explicit_Shape_Spec(SeparatorBase): # R511 def tostr(self): if self.items[0] is None: return str(self.items[1]) return SeparatorBase.tostr(self) - + class Lower_Bound(Base): # R512 """ <lower-bound> = <specification-expr> @@ -2182,7 +2182,7 @@ class Assumed_Size_Spec(Base): # R516 s += str(self.items[1]) + ' : ' s += '*' return s - + class Intent_Spec(STRINGBase): # R517 """ <intent-spec> = IN @@ -2218,7 +2218,7 @@ class Object_Name_Deferred_Shape_Spec_List_Item(CallBase): use_names = ['Deferred_Shape_Spec_List'] def match(string): return CallBase.match(Object_Name, Deferred_Shape_Spec_List, string, require_rhs=True) match = staticmethod(match) - + class Allocatable_Stmt(StmtBase, WORDClsBase): # R520 """ <allocateble-stmt> = ALLOCATABLE [ :: ] <object-name> [ ( <deferred-shape-spec-list> ) ] [ , <object-name> [ ( <deferred-shape-spec-list> ) ] ]... @@ -2229,7 +2229,7 @@ class Allocatable_Stmt(StmtBase, WORDClsBase): # R520 return WORDClsBase.match('ALLOCATABLE', Object_Name_Deferred_Shape_Spec_List_Item_List, string, check_colons=True, require_cls=True) match = staticmethod(match) - + class Asynchronous_Stmt(StmtBase, WORDClsBase): # R521 """ <asynchronous-stmt> = ASYNCHRONOUS [ :: ] <object-name-list> @@ -2331,7 +2331,7 @@ class Data_Stmt_Value(Base): # R530 return Data_Stmt_Repeat(lhs), Data_Stmt_Constant(rhs) match = staticmethod(match) def tostr(self): - return '%s * %s' % self.items + return '%s * %s' % self.items class Data_Stmt_Repeat(Base): # R531 """ @@ -2420,7 +2420,7 @@ class Optional_Stmt(StmtBase, WORDClsBase): # R537 def match(string): return WORDClsBase.match('OPTIONAL',Dummy_Arg_Name_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class Parameter_Stmt(StmtBase, CALLBase): # R538 """ <parameter-stmt> = PARAMETER ( <named-constant-def-list> ) @@ -2438,7 +2438,7 @@ class Named_Constant_Def(KeywordValueBase): # R539 use_names = ['Named_Constant', 'Initialization_Expr'] def match(string): return KeywordValueBase.match(Named_Constant, Initialization_Expr, string) match = staticmethod(match) - + class Pointer_Stmt(StmtBase, WORDClsBase): # R540 """ <pointer-stmt> = POINTER [ :: ] <pointer-decl-list> @@ -2448,7 +2448,7 @@ class Pointer_Stmt(StmtBase, WORDClsBase): # R540 def match(string): return WORDClsBase.match('POINTER',Pointer_Decl_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class Pointer_Decl(CallBase): # R541 """ <pointer-decl> = <object-name> [ ( <deferred-shape-spec-list> ) ] @@ -2522,7 +2522,7 @@ class Volatile_Stmt(StmtBase, WORDClsBase): # R548 def match(string): return WORDClsBase.match('VOLATILE',Object_Name_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class Implicit_Stmt(StmtBase, WORDClsBase): # R549 """ <implicit-stmt> = IMPLICIT <implicit-spec-list> @@ -2783,7 +2783,7 @@ class Parent_String(Base): # R610 <parent-string> = <scalar-variable-name> | <array-element> | <scalar-structure-component> - | <scalar-constant> + | <scalar-constant> """ subclass_names = ['Scalar_Variable_Name', 'Array_Element', 'Scalar_Structure_Component', 'Scalar_Constant'] @@ -2915,7 +2915,7 @@ class Allocate_Stmt(StmtBase): # R623 """ subclass_names = [] use_names = ['Type_Spec', 'Allocation_List', 'Alloc_Opt_List'] - + class Alloc_Opt(KeywordValueBase):# R624 """ <alloc-opt> = STAT = <stat-variable> @@ -2966,7 +2966,7 @@ class Allocation(CallBase):# R628 def match(string): return CallBase.match(Allocate_Object, Allocate_Shape_Spec_List, string, require_rhs = True) match = staticmethod(match) - + class Allocate_Object(Base): # R629 """ <allocate-object> = <variable-name> @@ -3015,7 +3015,7 @@ class Nullify_Stmt(StmtBase, CALLBase): # R633 use_names = ['Pointer_Object_List'] def match(string): return CALLBase.match('NULLIFY', Pointer_Object_List, string, require_rhs=True) match = staticmethod(match) - + class Pointer_Object(Base): # R634 """ <pointer-object> = <variable-name> @@ -3070,7 +3070,7 @@ class Primary(Base): # R701 """ subclass_names = ['Constant', 'Parenthesis', 'Designator','Array_Constructor', 'Structure_Constructor', - 'Function_Reference', 'Type_Param_Inquiry', 'Type_Param_Name', + 'Function_Reference', 'Type_Param_Inquiry', 'Type_Param_Name', ] class Parenthesis(BracketBase): # R701.h @@ -3098,14 +3098,14 @@ class Level_1_Expr(UnaryOpBase): # R702 class Defined_Unary_Op(STRINGBase): # R703 """ - <defined-unary-op> = . <letter> [ <letter> ]... . + <defined-unary-op> = . <letter> [ <letter> ]... . """ subclass_names = ['Defined_Op'] class Defined_Op(STRINGBase): # R703, 723 """ - <defined-op> = . <letter> [ <letter> ]... . + <defined-op> = . <letter> [ <letter> ]... . """ subclass_names = [] def match(string): @@ -3208,7 +3208,7 @@ class And_Operand(UnaryOpBase): # R714 class Or_Operand(BinaryOpBase): # R715 """ - <or-operand> = [ <or-operand> <and-op> ] <and-operand> + <or-operand> = [ <or-operand> <and-op> ] <and-operand> <and-op> = .AND. """ subclass_names = ['And_Operand'] @@ -3264,7 +3264,7 @@ class Expr(BinaryOpBase): # R722 class Defined_Unary_Op(STRINGBase): # R723 """ - <defined-unary-op> = . <letter> [ <letter> ]... . + <defined-unary-op> = . <letter> [ <letter> ]... . """ subclass_names = ['Defined_Op'] @@ -3337,7 +3337,7 @@ class Assignment_Stmt(StmtBase, BinaryOpBase): # R734 def match(string): return BinaryOpBase.match(Variable, '=', Expr, string, right=False) match = staticmethod(match) - + class Pointer_Assignment_Stmt(StmtBase): # R735 """ <pointer-assignment-stmt> = <data-pointer-object> [ ( <bounds-spec-list> ) ] => <data-target> @@ -3356,7 +3356,7 @@ class Data_Pointer_Object(BinaryOpBase): # R736 subclass_names = ['Variable_Name'] use_names = ['Variable', 'Data_Pointer_Component_Name'] def match(string): - return BinaryOpBase.match(Variable, r'%', Data_Pointer_Component_Name, string) + return BinaryOpBase.match(Variable, r'%', Data_Pointer_Component_Name, string) match = staticmethod(match) class Bounds_Spec(SeparatorBase): # R737 @@ -3398,7 +3398,7 @@ class Proc_Component_Ref(BinaryOpBase): # R741 subclass_names = [] use_names = ['Variable','Procedure_Component_Name'] def match(string): - return BinaryOpBase.match(Variable, r'%', Procedure_Component_Name, string) + return BinaryOpBase.match(Variable, r'%', Procedure_Component_Name, string) match = staticmethod(match) class Proc_Target(Base): # R742 @@ -3429,7 +3429,7 @@ class Where_Stmt(StmtBase): # R743 return Mask_Expr(expr), Where_Assignment_Stmt(stmt) match = staticmethod(match) def tostr(self): return 'WHERE (%s) %s' % tuple(self.items) - + class Where_Construct(Base): # R744 """ @@ -3507,7 +3507,7 @@ class Masked_Elsewhere_Stmt(StmtBase): # R749 def tostr(self): if self.items[1] is None: return 'ELSEWHERE(%s)' % (self.items[0]) return 'ELSEWHERE(%s) %s' % self.items - + class Elsewhere_Stmt(StmtBase, WORDClsBase): # R750 """ <elsewhere-stmt> = ELSEWHERE [ <where-construct-name> ] @@ -3957,7 +3957,7 @@ class Type_Guard_Stmt(StmtBase): # R823 if self.items[2] is not None: s += ' %s' % (self.items[2]) return s - + class End_Select_Type_Stmt(EndStmtBase): # R824 """ <end-select-type-stmt> = END SELECT [ <select-construct-name> ] @@ -4051,7 +4051,7 @@ class Label_Do_Stmt(StmtBase): # R828 def tostr(self): if self.itens[1] is None: return 'DO %s' % (self.items[0]) return 'DO %s %s' % self.items - + class Nonlabel_Do_Stmt(StmtBase, WORDClsBase): # R829 """ <nonlabel-do-stmt> = [ <do-construct-name> : ] DO [ <loop-control> ] @@ -4087,7 +4087,7 @@ class Loop_Control(Base): # R830 def tostr(self): if len(self.items)==1: return ', WHILE (%s)' % (self.items[0]) return ', %s = %s' % (self.items[0], ', '.join(map(str,self.items[1]))) - + class Do_Variable(Base): # R831 """ <do-variable> = <scalar-int-variable> @@ -4348,7 +4348,7 @@ class Open_Stmt(StmtBase, CALLBase): # R904 use_names = ['Connect_Spec_List'] def match(string): CALLBase.match('OPEN', Connect_Spec_List, string, require_rhs=True) match = staticmethod(match) - + class Connect_Spec(KeywordValueBase): # R905 """ <connect-spec> = [ UNIT = ] <file-unit-number> @@ -4473,7 +4473,7 @@ class Write_Stmt(StmtBase): # R911 def tostr(self): if self.items[1] is None: return 'WRITE(%s)' % (self.items[0]) return 'WRITE(%s) %s' % tuple(self.items) - + class Print_Stmt(StmtBase): # R912 """ <print-stmt> = PRINT <format> [ , <output-item-list> ] @@ -4496,7 +4496,7 @@ class Print_Stmt(StmtBase): # R912 def tostr(self): if self.items[1] is None: return 'PRINT %s' % (self.items[0]) return 'PRINT %s, %s' % tuple(self.items) - + class Io_Control_Spec_List(SequenceBase): # R913-list """ <io-control-spec-list> is a list taking into account C910, C917, C918 @@ -5049,7 +5049,7 @@ class Sign_Edit_Desc(STRINGBase): # R1015 subclass_names = [] def match(string): return STRINGBase.match(['SS','SP','S'], string) match = staticmethod(match) - + class Blank_Interp_Edit_Desc(STRINGBase): # R1016 """ <blank-interp-edit-desc> = BN @@ -5210,7 +5210,7 @@ class Use_Stmt(StmtBase): # R1109 if self.items[3] is not None: s += ' %s' % (self.items[3]) return s - + class Module_Nature(STRINGBase): # R1110 """ <module-nature> = INTRINSIC @@ -5397,7 +5397,7 @@ class Import_Stmt(StmtBase, WORDClsBase): # R1209 def match(string): return WORDClsBase.match('IMPORT',Import_Name_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class External_Stmt(StmtBase, WORDClsBase): # R1210 """ <external-stmt> = EXTERNAL [ :: ] <external-name-list> @@ -5407,7 +5407,7 @@ class External_Stmt(StmtBase, WORDClsBase): # R1210 def match(string): return WORDClsBase.match('EXTERNAL',External_Name_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class Procedure_Declaration_Stmt(StmtBase): # R1211 """ <procedure-declaration-stmt> = PROCEDURE ( [ <proc-interface> ] ) [ [ , <proc-attr-spec> ]... :: ] <proc-decl-list> @@ -5441,7 +5441,7 @@ class Proc_Decl(BinaryOpBase): # R1214 use_names = ['Null_Init'] def match(string): return BinaryOpBase.match(Procedure_Entity_Name,'=>', Null_Init, string) match = staticmethod(match) - + class Interface_Name(Base): # R1215 """ <interface-name> = <name> @@ -5457,7 +5457,7 @@ class Intrinsic_Stmt(StmtBase, WORDClsBase): # R1216 def match(string): return WORDClsBase.match('INTRINSIC',Intrinsic_Procedure_Name_List,string,check_colons=True, require_cls=True) match = staticmethod(match) tostr = WORDClsBase.tostr_a - + class Function_Reference(CallBase): # R1217 """ <function-reference> = <procedure-designator> ( [ <actual-arg-spec-list> ] ) @@ -5730,7 +5730,7 @@ class Return_Stmt(StmtBase): # R1236 if len(string)==6: return None, return Scalar_Int_Expr(string[6:].lstrip()), match = staticmethod(match) - def tostr(self): + def tostr(self): if self.items[0] is None: return 'RETURN' return 'RETURN %s' % self.items @@ -5833,11 +5833,11 @@ if 1: # Optimize subclass tree: l = [] for n in getattr(cls,'subclass_names',[]): l1 = _rpl_list(n) - for n1 in l1: + for n1 in l1: if n1 not in l: l.append(n1) return l - + for cls in Base_classes.values(): if not hasattr(cls, 'subclass_names'): continue opt_subclass_names = [] @@ -5881,7 +5881,7 @@ if 1: break if n not in subclasses_names: print '%s needs to be added to %s subclass_name list' % (n,cls.__name__) - for n in use_names + subclass_names: + for n in use_names + subclass_names: if not Base_classes.has_key(n): print '%s not defined used by %s' % (n, cls.__name__) diff --git a/numpy/f2py/lib/parser/base_classes.py b/numpy/f2py/lib/parser/base_classes.py index b2fa3511c..68ea9c24a 100644 --- a/numpy/f2py/lib/parser/base_classes.py +++ b/numpy/f2py/lib/parser/base_classes.py @@ -95,7 +95,7 @@ def get_base_classes(cls): bases = () for c in cls.__bases__: bases += get_base_classes(c) - return bases + cls.__bases__ + (cls,) + return bases + cls.__bases__ + (cls,) class Variable: """ @@ -391,7 +391,7 @@ class Variable: def is_array_pointer(self): return self.is_array() and self.is_pointer() - + def analyze(self): typedecl = self.get_typedecl() if self.is_array(): @@ -406,7 +406,7 @@ class Variable: shape.append(spec[0]) else: shape.append(spec[1]-spec[0]) - self.shape = shape + self.shape = shape return class ProgramBlock: @@ -528,7 +528,7 @@ class Statement: lines.append(line+'\n') else: lines.append(line+'\n') return ''.join(lines).replace('\n &\n','\n') - + def format_message(self, kind, message): if self.item is not None: message = self.reader.format_message(kind, message, @@ -613,7 +613,7 @@ class BeginStatement(Statement): self.blocktype = self.__class__.__name__.lower() if not hasattr(self, 'name'): # process_item may change this - self.name = '__'+self.blocktype.upper()+'__' + self.name = '__'+self.blocktype.upper()+'__' Statement.__init__(self, parent, item) return @@ -701,7 +701,7 @@ class BeginStatement(Statement): return False # item may be cloned that changes the items line: line = item.get_line() - + # Check if f77 code contains inline comments or other f90 # constructs that got undetected by get_source_info. if item.reader.isfix77: @@ -734,10 +734,10 @@ class BeginStatement(Statement): % (item.get_line(),self.__class__.__name__), item.span[0], item.span[1]) self.show_message(message) - + item.reader.set_mode(False, False) self.classes = classes - + r = BeginStatement.process_subitem(self, item) if r is None: # restore f77 fix mode @@ -817,4 +817,3 @@ class EndStatement(Statement): def tofortran(self, isfix=None): return self.get_indent_tab(isfix=isfix) + 'END %s %s'\ % (self.blocktype.upper(),self.name or '') - diff --git a/numpy/f2py/lib/parser/block_statements.py b/numpy/f2py/lib/parser/block_statements.py index 7e3f41d86..b3d29c911 100644 --- a/numpy/f2py/lib/parser/block_statements.py +++ b/numpy/f2py/lib/parser/block_statements.py @@ -391,7 +391,7 @@ class Program(BeginStatement, ProgramBlock, class EndBlockData(EndStatement): """ - END [ BLOCK DATA [ <block-data-name> ] ] + END [ BLOCK DATA [ <block-data-name> ] ] """ match = re.compile(r'end(\s*block\s*data\s*\w*|)\Z', re.I).match blocktype = 'blockdata' @@ -410,7 +410,7 @@ class BlockData(BeginStatement, HasImplicitStmt, HasUseStmt, def get_classes(self): return specification_part - + # Interface class EndInterface(EndStatement): @@ -432,7 +432,7 @@ class Interface(BeginStatement, HasImplicitStmt, HasUseStmt, | READ ( UNFORMATTED ) | WRITE ( FORMATTED ) | WRITE ( UNFORMATTED ) - + """ modes = ['free90', 'fix90', 'pyf'] match = re.compile(r'(interface\s*(\w+\s*\(.*\)|\w*)|abstract\s*interface)\Z',re.I).match @@ -444,7 +444,7 @@ class Interface(BeginStatement, HasImplicitStmt, HasUseStmt, def get_classes(self): l = intrinsic_type_spec + interface_specification if self.reader.mode=='pyf': - return [Subroutine, Function] + l + return [Subroutine, Function] + l return l def process_item(self): @@ -498,7 +498,7 @@ class Interface(BeginStatement, HasImplicitStmt, HasUseStmt, s += HasAttributes.topyf(self, tab=tab+' ') s += HasUseStmt.topyf(self, tab=tab+' ') s += tab + 'END' + self.tostr() + '\n' - return s + return s # Subroutine @@ -729,7 +729,7 @@ class EndSelect(EndStatement): class Select(BeginStatement): """ [ <case-construct-name> : ] SELECT CASE ( <case-expr> ) - + """ match = re.compile(r'select\s*case\s*\(.*\)\Z',re.I).match end_stmt_cls = EndSelect @@ -738,7 +738,7 @@ class Select(BeginStatement): return 'SELECT CASE ( %s )' % (self.expr) def process_item(self): self.expr = self.item.get_line()[6:].lstrip()[4:].lstrip()[1:-1].strip() - self.name = self.item.label + self.name = self.item.label return BeginStatement.process_item(self) def get_classes(self): @@ -751,7 +751,7 @@ class EndWhere(EndStatement): END WHERE [ <where-construct-name> ] """ match = re.compile(r'end\s*\where\s*\w*\Z',re.I).match - + class Where(BeginStatement): """ @@ -782,7 +782,7 @@ class EndForall(EndStatement): END FORALL [ <forall-construct-name> ] """ match = re.compile(r'end\s*forall\s*\w*\Z',re.I).match - + class Forall(BeginStatement): """ [ <forall-construct-name> : ] FORALL <forall-header> @@ -842,7 +842,7 @@ class IfThen(BeginStatement): self.expr = line[1:-1].strip() self.name = item.label return BeginStatement.process_item(self) - + def get_classes(self): return [Else, ElseIf] + execution_part_construct @@ -883,7 +883,7 @@ class If(BeginStatement): self.put_item(newitem) self.isvalid = False return - + def tostr(self): assert len(self.content)==1,`self.content` return 'IF (%s) %s' % (self.expr, str(self.content[0]).lstrip()) @@ -959,7 +959,7 @@ class Associate(BeginStatement): """ match = re.compile(r'associate\s*\(.*\)\Z',re.I).match end_stmt_cls = EndAssociate - + def process_item(self): line = self.item.get_line()[9:].lstrip() self.associations = line[1:-1].strip() @@ -1090,7 +1090,7 @@ class Type(BeginStatement, HasVariables, HasAttributes, AccessSpecs): def topyf(self, tab=''): s = tab + 'TYPE' if self.a.extends is not None: - s += ', EXTENDS(%s) ::' % (self.a.extends) + s += ', EXTENDS(%s) ::' % (self.a.extends) s += ' ' + self.name if self.a.parameters: s += ' (%s)' % (', '.join(self.a.parameters)) @@ -1171,7 +1171,7 @@ intrinsic_type_spec = [ SubprogramPrefix, Integer , Real, derived_type_spec = [ ] type_spec = intrinsic_type_spec + derived_type_spec declaration_type_spec = intrinsic_type_spec + [ TypeStmt, Class ] - + type_declaration_stmt = declaration_type_spec private_or_sequence = [ Private, Sequence ] diff --git a/numpy/f2py/lib/parser/parsefortran.py b/numpy/f2py/lib/parser/parsefortran.py index 71b019122..08716e7c8 100644 --- a/numpy/f2py/lib/parser/parsefortran.py +++ b/numpy/f2py/lib/parser/parsefortran.py @@ -79,7 +79,7 @@ class FortranParser: if self.block is None: self.reader.show_message('Nothing to analyze.') return - + try: self.block.analyze() except AnalyzeError: @@ -129,9 +129,9 @@ module foo hey = 1 end subroutine bar abstract interface - + end interface - + end module foo """ reader = FortranStringReader(string, True, False) @@ -195,4 +195,3 @@ if __name__ == "__main__": simple_main() #profile_main() #parse_all_f() - diff --git a/numpy/f2py/lib/parser/readfortran.py b/numpy/f2py/lib/parser/readfortran.py index dfe64b4f1..e3acffa36 100644 --- a/numpy/f2py/lib/parser/readfortran.py +++ b/numpy/f2py/lib/parser/readfortran.py @@ -52,9 +52,9 @@ class FortranReaderError: # TODO: may be derive it from Exception class Line: """ Holds a Fortran source line. """ - + f2py_strmap_findall = re.compile(r'(_F2PY_STRING_CONSTANT_\d+_|F2PY_EXPR_TUPLE_\d+)').findall - + def __init__(self, line, linenospan, label, reader): self.line = line.strip() self.span = linenospan @@ -87,7 +87,7 @@ class Line: self.line = self.apply_map(line) self.strline = None return - + def __repr__(self): return self.__class__.__name__+'(%r,%s,%r)' \ % (self.line, self.span, self.label) @@ -182,7 +182,7 @@ class FortranReaderBase: used to retrive a line. source may contain - Fortran 77 code - - fixed format Fortran 90 code + - fixed format Fortran 90 code - free format Fortran 90 code - .pyf signatures - extended free format Fortran 90 syntax """ @@ -277,7 +277,7 @@ class FortranReaderBase: return self def next(self, ignore_comments = False): - + try: if self.reader is not None: try: @@ -402,7 +402,7 @@ class FortranReaderBase: break linenostr = '%5d:' % (i) if i==endlineno: - sourceline = self.source_lines[i-1] + sourceline = self.source_lines[i-1] l0 = linenostr+sourceline[:startcolno] if endcolno==-1: l1 = sourceline[startcolno:] @@ -414,7 +414,7 @@ class FortranReaderBase: else: r.append(linenostr+ self.source_lines[i-1]) return '\n'.join(r) - + def format_error_message(self, message, startlineno, endlineno, startcolno=0, endcolno=-1): return self.format_message('ERROR',message, startlineno, @@ -555,7 +555,7 @@ class FortranReaderBase: # XXX: should we do line.replace('\\'+mlstr[0],mlstr[0]) # for line in multilines? return self.multiline_item(prefix,multilines,suffix, - startlineno, self.linecount) + startlineno, self.linecount) # The main method of interpreting raw source lines within # the following contexts: f77, fixed f90, free f90, pyf. @@ -565,7 +565,7 @@ class FortranReaderBase: a source item is .. - a fortran line - a list of continued fortran lines - - a multiline - lines inside triple-qoutes, only when in ispyf mode + - a multiline - lines inside triple-qoutes, only when in ispyf mode """ get_single_line = self.get_single_line line = get_single_line() @@ -613,7 +613,7 @@ class FortranReaderBase: return self.line_item(''.join(lines),startlineno,self.linecount,label) handle_inline_comment = self.handle_inline_comment - + if self.isfix90 and not is_f2py_directive: # handle inline comment newline,qc = handle_inline_comment(line[6:], startlineno) @@ -739,7 +739,7 @@ class FortranFileReader(FortranReaderBase): self.file.close() class FortranStringReader(FortranReaderBase): - + def __init__(self, string, isfree, isstrict, include_dirs = None): self.id = 'string-'+str(id(string)) source = StringIO(string) @@ -765,7 +765,7 @@ cf2py call me ! hey reader = FortranStringReader(string_f77,False,True) for item in reader: print item - + filename = tempfile.mktemp()+'.f' f = open(filename,'w') f.write(string_f77) @@ -823,7 +823,7 @@ cComment obj%bin_wid,' VEL_DMO = ', obj%vel_dmo end subroutine foo subroutine - + & foo end """ diff --git a/numpy/f2py/lib/parser/sourceinfo.py b/numpy/f2py/lib/parser/sourceinfo.py index 2f5aab603..7eb980251 100644 --- a/numpy/f2py/lib/parser/sourceinfo.py +++ b/numpy/f2py/lib/parser/sourceinfo.py @@ -76,6 +76,6 @@ def simple_main(): for filename in sys.argv[1:]: isfree, isstrict = get_source_info(filename) print '%s: isfree=%s, isstrict=%s' % (filename, isfree, isstrict) - + if __name__ == '__main__': simple_main() diff --git a/numpy/f2py/lib/parser/splitline.py b/numpy/f2py/lib/parser/splitline.py index b933602d4..9d4a40fc5 100644 --- a/numpy/f2py/lib/parser/splitline.py +++ b/numpy/f2py/lib/parser/splitline.py @@ -209,7 +209,7 @@ class LineSplitter(LineSplitterBase): quotechar = self.quotechar l = [] l_append = l.append - + nofslashes = 0 if quotechar is None: # search for string start @@ -323,7 +323,7 @@ class LineSplitterParen(LineSplitterBase): self.startchar = paren[0] self.endchar = paren[1] self.stopchar = None - + def get_item(self): fifo_pop = self.fifo_line.pop try: @@ -336,7 +336,7 @@ class LineSplitterParen(LineSplitterBase): stopchar = self.stopchar l = [] l_append = l.append - + nofslashes = 0 if stopchar is None: # search for parenthesis start @@ -377,7 +377,7 @@ class LineSplitterParen(LineSplitterBase): except IndexError: break return ParenString(''.join(l)) - + def test(): splitter = LineSplitter('abc\\\' def"12\\"3""56"dfad\'a d\'') l = [item for item in splitter] @@ -394,7 +394,7 @@ def test(): l,stopchar = splitquote('"abc123&') assert l==['"abc123&'],`l` assert stopchar=='"' - + splitter = LineSplitter(' &abc"123','"') l = [item for item in splitter] assert l==[' &abc"','123'] @@ -402,7 +402,7 @@ def test(): l,stopchar = splitquote(' &abc"123','"') assert l==[' &abc"','123'] assert stopchar is None - + l = split2('') assert l==('',''),`l` l = split2('12') @@ -424,4 +424,3 @@ def test(): if __name__ == '__main__': test() - diff --git a/numpy/f2py/lib/parser/statements.py b/numpy/f2py/lib/parser/statements.py index efbbca37f..b37948faf 100644 --- a/numpy/f2py/lib/parser/statements.py +++ b/numpy/f2py/lib/parser/statements.py @@ -95,7 +95,7 @@ class GeneralAssignment(Statement): if sign=='=>': self.__class__ = PointerAssignment else: - self.__class__ = Assignment + self.__class__ = Assignment apply_map = self.item.apply_map self.variable = apply_map(m.group('variable').replace(' ','')) self.expr = apply_map(m.group('expr')) @@ -247,7 +247,7 @@ class AssignedGoto(Statement): tab = self.get_indent_tab(isfix=isfix) if self.items: return tab + 'GO TO %s (%s)' \ - % (self.varname, ', '.join(self.items)) + % (self.varname, ', '.join(self.items)) return tab + 'GO TO %s' % (self.varname) def analyze(self): return @@ -339,7 +339,7 @@ Read0: READ ( <io-control-spec-list> ) [ <input-item-list> ] | [ NML = ] <namelist-group-name> | ADVANCE = <scalar-default-char-expr> ... - + Read1: READ <format> [, <input-item-list>] <format> == <default-char-expr> | <label> | * """ @@ -525,7 +525,7 @@ class Deallocate(Statement): def tofortran(self, isfix=None): return self.get_indent_tab(isfix=isfix) \ + 'DEALLOCATE (%s)' % (', '.join(self.items)) def analyze(self): return - + class ModuleProcedure(Statement): """ [ MODULE ] PROCEDURE <procedure-name-list> @@ -704,7 +704,7 @@ class Format(Statement): ... <sign-edit-descr> = SS | SP | S ... - + """ match = re.compile(r'format\s*\(.*\)\Z', re.I).match def process_item(self): @@ -775,7 +775,7 @@ class Data(Statement): | <substring> <array-element> = <data-ref> <array-section> = <data-ref> [ ( <substring-range> ) ] - + """ match = re.compile(r'data\b',re.I).match @@ -903,7 +903,7 @@ class Use(Statement): module = modules[self.name] use_provides = self.parent.a.use_provides print use - + return class Exit(Statement): @@ -966,7 +966,7 @@ class Equivalence(Statement): class Dimension(Statement): """ DIMENSION [ :: ] <array-name> ( <array-spec> ) [ , <array-name> ( <array-spec> ) ]... - + """ match = re.compile(r'dimension\b', re.I).match def process_item(self): @@ -990,7 +990,7 @@ class Dimension(Statement): class Target(Statement): """ TARGET [ :: ] <object-name> ( <array-spec> ) [ , <object-name> ( <array-spec> ) ]... - + """ match = re.compile(r'target\b', re.I).match def process_item(self): @@ -1018,7 +1018,7 @@ class Pointer(Statement): POINTER [ :: ] <pointer-decl-list> <pointer-decl> = <object-name> [ ( <deferred-shape-spec-list> ) ] | <proc-entity-name> - + """ match = re.compile(r'pointer\b',re.I).match def process_item(self): @@ -1111,7 +1111,7 @@ class Inquire(Statement): """ INQUIRE ( <inquire-spec-list> ) INQUIRE ( IOLENGTH = <scalar-int-variable> ) <output-item-list> - + <inquire-spec> = [ UNIT = ] <file-unit-number> | FILE = <file-name-expr> ... @@ -1495,7 +1495,7 @@ class GenericBinding(Statement): s += ' :: ' + self.spec + ' => ' + ', '.join(self.items) return tab + s - + class FinalBinding(StatementWithNamelist): """ FINAL [ :: ] <final-subroutine-name-list> @@ -1515,7 +1515,7 @@ class Allocatable(Statement): self.items = split_comma(line, self.item) return def tofortran(self, isfix=None): - return self.get_indent_tab(isfix=isfix) + 'ALLOCATABLE ' + ', '.join(self.items) + return self.get_indent_tab(isfix=isfix) + 'ALLOCATABLE ' + ', '.join(self.items) def analyze(self): for line in self.items: i = line.find('(') @@ -1583,7 +1583,7 @@ class Else(Statement): if self.name and self.name!=parent_name: self.warning('expected if-construct-name %r but got %r, skipping.'\ % (parent_name, self.name)) - self.isvalid = False + self.isvalid = False return def tofortran(self, isfix=None): @@ -1610,9 +1610,9 @@ class ElseIf(Statement): if self.name and self.name!=parent_name: self.warning('expected if-construct-name %r but got %r, skipping.'\ % (parent_name, self.name)) - self.isvalid = False + self.isvalid = False return - + def tofortran(self, isfix=None): s = '' if self.name: @@ -1658,7 +1658,7 @@ class Case(Statement): if self.name and self.name!=parent_name: self.warning('expected case-construct-name %r but got %r, skipping.'\ % (parent_name, self.name)) - self.isvalid = False + self.isvalid = False return def tofortran(self, isfix=None): @@ -1854,4 +1854,3 @@ class Pause(Statement): return self.get_indent_tab(isfix=isfix) + 'PAUSE ' + self.value return self.get_indent_tab(isfix=isfix) + 'PAUSE' def analyze(self): return - diff --git a/numpy/f2py/lib/parser/test_Fortran2003.py b/numpy/f2py/lib/parser/test_Fortran2003.py index 99fbcc955..a8aae6081 100644 --- a/numpy/f2py/lib/parser/test_Fortran2003.py +++ b/numpy/f2py/lib/parser/test_Fortran2003.py @@ -325,7 +325,7 @@ class test_Real_Literal_Constant(NumpyTestCase): # R417 a = cls('0.0D+0') assert isinstance(a,cls),`a` assert_equal(str(a),'0.0D+0') - + class test_Char_Selector(NumpyTestCase): # R424 def check_char_selector(self): @@ -343,7 +343,7 @@ class test_Char_Selector(NumpyTestCase): # R424 a = cls('(2, 8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = 2, KIND = 8)') - + a = cls('(kind=8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(KIND = 8)') @@ -728,7 +728,7 @@ class test_Structure_Constructor(NumpyTestCase): # R457 a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') - + class test_Component_Spec(NumpyTestCase): # R458 def check_simple(self): @@ -820,7 +820,7 @@ class test_Ac_Value_List(NumpyTestCase): # R469-list assert_equal(str(a),'a') class test_Ac_Implied_Do(NumpyTestCase): # R470 - + def check_ac_implied_do(self): cls = Ac_Implied_Do a = cls('( a, b, n = 1, 5 )') @@ -876,7 +876,7 @@ class test_Declaration_Type_Spec(NumpyTestCase): # R502 a = cls('Integer*2') assert isinstance(a, Intrinsic_Type_Spec),`a` assert_equal(str(a), 'INTEGER*2') - + a = cls('type(foo)') assert isinstance(a, cls),`a` assert_equal(str(a), 'TYPE(foo)') @@ -969,7 +969,7 @@ class test_Explicit_Shape_Spec(NumpyTestCase): # R511 assert_equal(str(a),'a') class test_Upper_Bound(NumpyTestCase): # R513 - + def check_simple(self): cls = Upper_Bound a = cls('a') @@ -1055,7 +1055,7 @@ class test_Parameter_Stmt(NumpyTestCase): # R538 a = cls('PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 )') assert isinstance(a, cls),`a` assert_equal(str(a),'PARAMETER(ONE = 1.0D+0, ZERO = 0.0D+0)') - + class test_Named_Constant_Def(NumpyTestCase): # R539 def check_simple(self): @@ -1170,7 +1170,7 @@ class test_Common_Block_Object(NumpyTestCase): # R558 ############################################################################### class test_Substring(NumpyTestCase): # R609 - + def check_simple(self): cls = Substring a = cls('a(:)') @@ -1185,7 +1185,7 @@ class test_Substring(NumpyTestCase): # R609 class test_Substring_Range(NumpyTestCase): # R611 - + def check_simple(self): cls = Substring_Range a = cls(':') @@ -1237,7 +1237,7 @@ class test_Part_Ref(NumpyTestCase): # R613 assert_equal(str(a),'a') class test_Type_Param_Inquiry(NumpyTestCase): # R615 - + def check_simple(self): cls = Type_Param_Inquiry a = cls('a % b') @@ -1272,7 +1272,7 @@ class test_Section_Subscript(NumpyTestCase): # R619 a = cls('zzz') assert isinstance(a, Name),`a` assert_equal(str(a),'zzz') - + class test_Section_Subscript_List(NumpyTestCase): # R619-list def check_simple(self): @@ -1320,7 +1320,7 @@ class test_Subscript_Triplet(NumpyTestCase): # R620 assert_equal(str(a),'a + 1 :') class test_Alloc_Opt(NumpyTestCase): # R624 - + def check_simple(self): cls = Alloc_Opt a = cls('stat=a') @@ -1329,7 +1329,7 @@ class test_Alloc_Opt(NumpyTestCase): # R624 assert_equal(repr(a),"Alloc_Opt('STAT', Name('a'))") class test_Nullify_Stmt(NumpyTestCase): # R633 - + def check_simple(self): cls = Nullify_Stmt a = cls('nullify (a)') @@ -1662,7 +1662,7 @@ class test_Expr(NumpyTestCase): # R722 self.assertRaises(NoMatchError,Scalar_Int_Expr,'a,b') class test_Assignment_Stmt(NumpyTestCase): # R734 - + def check_simple(self): cls = Assignment_Stmt a = cls('a = b') @@ -1792,7 +1792,7 @@ class test_Io_Control_Spec_List(NumpyTestCase): # R913-list a = cls('123,a') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123, NML = a') - + class test_Format(NumpyTestCase): # R914 def check_simple(self): @@ -2096,6 +2096,6 @@ if 1: print 'Nof tests needs:',nof_needed_tests,'out of',total_needs print 'Total number of classes:',total_classes print '-----' - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/f2py/lib/parser/test_parser.py b/numpy/f2py/lib/parser/test_parser.py index 3921e93a3..9f1767a1a 100644 --- a/numpy/f2py/lib/parser/test_parser.py +++ b/numpy/f2py/lib/parser/test_parser.py @@ -97,7 +97,7 @@ class test_Statements(NumpyTestCase): assert_equal(parse(Read, 'read "hey a" , a'),'READ "hey a", a') assert_equal(parse(Read, 'read * , a , b'),'READ *, a, b') assert_equal(parse(Read, 'read ( unit =10 )'),'READ (UNIT = 10)') - + def check_write(self): assert_equal(parse(Write, 'write ( 10 )'),'WRITE (10)') assert_equal(parse(Write, 'write ( 10 , a )'),'WRITE (10, a)') @@ -207,7 +207,7 @@ class test_Statements(NumpyTestCase): def check_exit(self): assert_equal(parse(Exit,'exit'),'EXIT') - assert_equal(parse(Exit,'exit ab'),'EXIT ab') + assert_equal(parse(Exit,'exit ab'),'EXIT ab') def check_parameter(self): assert_equal(parse(Parameter,'parameter (a = b(1,2))'), @@ -481,7 +481,7 @@ class test_Statements(NumpyTestCase): 'CHARACTER(LEN=3, KIND=fA(1,2))') assert_equal(parse(Character,'character(len=3,kind=fA(1,2))'), 'CHARACTER(LEN=3, KIND=fa(1,2))') - + def check_implicit(self): assert_equal(parse(Implicit,'implicit none'),'IMPLICIT NONE') assert_equal(parse(Implicit,'implicit'),'IMPLICIT NONE') diff --git a/numpy/f2py/lib/parser/typedecl_statements.py b/numpy/f2py/lib/parser/typedecl_statements.py index 6aaa370fa..7414a6d2d 100644 --- a/numpy/f2py/lib/parser/typedecl_statements.py +++ b/numpy/f2py/lib/parser/typedecl_statements.py @@ -47,7 +47,7 @@ class TypeDeclarationStatement(Statement): EXTENSION: <kind-selector> = ( [ KIND = ] <scalar-int-initialization-expr> ) | * <length> - + <char-selector> = <length-selector> | ( LEN = <type-param-value>, KIND = <scalar-int-initialization-expr> ) | ( <type-param-value>, [ KIND = ] <scalar-int-initialization-expr> ) @@ -218,7 +218,7 @@ class TypeDeclarationStatement(Statement): kind = l[4:].lstrip()[1:].lstrip() l = '' else: - kind = '' + kind = '' else: assert len(l)==2 if l[0].lower().startswith('len'): @@ -257,7 +257,7 @@ class TypeDeclarationStatement(Statement): s += '*%s' % (length) if kind: s += '(KIND=%s)' % (kind) - + return clsname + s def tofortran(self,isfix=None): @@ -270,7 +270,7 @@ class TypeDeclarationStatement(Statement): if self.entity_decls: s += ' ' + ', '.join(self.entity_decls) return tab + s - + def __str__(self): return self.tofortran() @@ -415,7 +415,7 @@ class Complex(TypeDeclarationStatement): def get_part_typedecl(self): bz = self.get_byte_size()/2 return Real(self.parent, self.item.copy('REAL*%s' % (bz))) - + class DoubleComplex(TypeDeclarationStatement): # not in standard match = re.compile(r'double\s*complex\b',re.I).match @@ -474,7 +474,7 @@ class Type(TypeDeclarationStatement): def get_bit_size(self): return self.get_type_decl(self.name).get_bit_size() - + TypeStmt = Type class Class(TypeDeclarationStatement): diff --git a/numpy/f2py/lib/py_wrap.py b/numpy/f2py/lib/py_wrap.py index e8734ec08..47c8437ad 100644 --- a/numpy/f2py/lib/py_wrap.py +++ b/numpy/f2py/lib/py_wrap.py @@ -76,7 +76,7 @@ capi_err: self.defined_types = [] self.defined_capi_codes = [] - + self.header_list = [] self.typedef_list = [] self.extern_list = [] @@ -121,7 +121,7 @@ capi_err: else: raise NotImplementedError,`block.__class__.__name__` return - + def c_code(self): return self.apply_attributes(self.main_template) def fortran_code(self): diff --git a/numpy/f2py/lib/py_wrap_subprogram.py b/numpy/f2py/lib/py_wrap_subprogram.py index 70affbedb..8dd0c3efb 100644 --- a/numpy/f2py/lib/py_wrap_subprogram.py +++ b/numpy/f2py/lib/py_wrap_subprogram.py @@ -1,4 +1,3 @@ - __all__ = ['PythonCAPISubProgram'] import sys @@ -88,7 +87,7 @@ static void %(init_func)s_c(%(name)s_functype func_ptr) { if cname in defined: return defined.append(cname) - + self.info('Generating interface for %s %s: %s' % (parent.modulename, block.__class__.__name__, cname)) self.parent = parent @@ -105,7 +104,7 @@ static void %(init_func)s_c(%(name)s_functype func_ptr) { self.fortran_code_template = '' WrapperCPPMacro(parent, 'F_FUNC') - + if isinstance(block.parent, Module): self.mname = block.parent.name self.init_func = '%s_init' % (name) @@ -199,7 +198,7 @@ static void %(init_func)s_c(%(name)s_functype func_ptr) { self.ctype_args_f_list = ctype_args_f + extra_ctype_args_f if not self.ctype_args_f_list: self.ctype_args_f_list.append('void') - + self.clean_pyobjfrom_list.reverse() self.clean_call_list.reverse() diff --git a/numpy/f2py/lib/py_wrap_type.py b/numpy/f2py/lib/py_wrap_type.py index 4c50029ad..7b90e7ed1 100644 --- a/numpy/f2py/lib/py_wrap_type.py +++ b/numpy/f2py/lib/py_wrap_type.py @@ -1,4 +1,3 @@ - __all__ = ['PythonCAPIType', 'PyTypeInterface'] from wrapper_base import * @@ -331,7 +330,7 @@ static int pyobj_to_%(ctype)s(PyObject *obj, %(ctype)s* value) { #endif return return_value; } -''' +''' def __init__(self, parent, typedecl): WrapperBase.__init__(self) self.name = name = typedecl.name @@ -342,7 +341,7 @@ static int pyobj_to_%(ctype)s(PyObject *obj, %(ctype)s* value) { if ctype in defined: return defined.append(ctype) - + self.info('Generating interface for %s: %s' % (typedecl.__class__.__name__, ctype)) self.parent = parent if isinstance(typedecl, (Integer,Byte,Real,DoublePrecision)): @@ -601,7 +600,7 @@ static int %(otype)s_init(%(otype)s *self, if (!PyArg_ParseTuple(capi_args,"%(attr_format_elist)s" %(attr_init_clist)s)) return_value = -1; - + #if defined(F2PY_DEBUG_PYOBJ_TOFROM) fprintf(stderr,"%(otype)s_init: return_value=%%d, PyErr_Occurred()=%%p\\n", return_value, PyErr_Occurred()); #endif @@ -656,7 +655,7 @@ static PyObject * %(otype)s_repr(PyObject * self) { self.wrappermodulename = typedecl.parent.name else: self.info('Generating interface for %s.%s: %s' % (parent.modulename, typedecl.name, ctype)) - + parent.isf90 = True self.parent = parent self.name = name = typedecl.name diff --git a/numpy/f2py/lib/test_derived_scalar.py b/numpy/f2py/lib/test_derived_scalar.py index e85f067d6..5e6ff249f 100644 --- a/numpy/f2py/lib/test_derived_scalar.py +++ b/numpy/f2py/lib/test_derived_scalar.py @@ -94,6 +94,6 @@ class test_m(NumpyTestCase): assert_equal(a.flag,2) assert_equal(r.flag,4) - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/f2py/lib/test_scalar_function_in.py b/numpy/f2py/lib/test_scalar_function_in.py index df6d2cee7..7c2539fe5 100644 --- a/numpy/f2py/lib/test_scalar_function_in.py +++ b/numpy/f2py/lib/test_scalar_function_in.py @@ -549,6 +549,6 @@ class test_m(NumpyTestCase): assert_equal(r,'1bcde') r = func('') assert_equal(r,'') - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/f2py/lib/test_scalar_in_out.py b/numpy/f2py/lib/test_scalar_in_out.py index 13f3e333d..37cf4d8d9 100644 --- a/numpy/f2py/lib/test_scalar_in_out.py +++ b/numpy/f2py/lib/test_scalar_in_out.py @@ -547,6 +547,6 @@ class test_m(NumpyTestCase): assert_equal(r,'1bcde') r = func('') assert_equal(r,'') - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/f2py/lib/wrapper_base.py b/numpy/f2py/lib/wrapper_base.py index ccda6401e..3164e817f 100644 --- a/numpy/f2py/lib/wrapper_base.py +++ b/numpy/f2py/lib/wrapper_base.py @@ -1,4 +1,3 @@ - import os import sys import re @@ -57,7 +56,7 @@ class WrapperBase: elif d.endswith('.c'): WrapperCCode(parent, d[:-2]) else: - self.warning('Unknown dependence: %r.' % (d)) + self.warning('Unknown dependence: %r.' % (d)) return def apply_attributes(self, template): diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py index 55e86284f..d1eb4016e 100644 --- a/numpy/f2py/rules.py +++ b/numpy/f2py/rules.py @@ -173,7 +173,7 @@ PyMODINIT_FUNC init#modulename#(void) { \tm = #modulename#_module = Py_InitModule(\"#modulename#\", f2py_module_methods); \tPyFortran_Type.ob_type = &PyType_Type; \timport_array(); -\tif (PyErr_Occurred()) +\tif (PyErr_Occurred()) \t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return;} \td = PyModule_GetDict(m); \ts = PyString_FromString(\"$R"""+"""evision: $\"); diff --git a/numpy/f2py/tests/array_from_pyobj/setup.py b/numpy/f2py/tests/array_from_pyobj/setup.py index f449117a7..bcb083180 100644 --- a/numpy/f2py/tests/array_from_pyobj/setup.py +++ b/numpy/f2py/tests/array_from_pyobj/setup.py @@ -1,4 +1,3 @@ - import os def configuration(parent_name='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/f2py/tests/c/return_real.py b/numpy/f2py/tests/c/return_real.py index 27e0843f1..62dbd2f74 100644 --- a/numpy/f2py/tests/c/return_real.py +++ b/numpy/f2py/tests/c/return_real.py @@ -6,7 +6,6 @@ Examples: python return_real.py --quiet """ - import f2py2e from Numeric import array diff --git a/numpy/f2py/tests/f77/callback.py b/numpy/f2py/tests/f77/callback.py index 672504bc7..bfe4eb547 100644 --- a/numpy/f2py/tests/f77/callback.py +++ b/numpy/f2py/tests/f77/callback.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python callback.py [<f2py options>] diff --git a/numpy/f2py/tests/f77/return_character.py b/numpy/f2py/tests/f77/return_character.py index 3361c11f5..b44b6ee70 100644 --- a/numpy/f2py/tests/f77/return_character.py +++ b/numpy/f2py/tests/f77/return_character.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python return_character.py [<f2py options>] diff --git a/numpy/f2py/tests/f77/return_complex.py b/numpy/f2py/tests/f77/return_complex.py index 9993bb6eb..e182902b3 100644 --- a/numpy/f2py/tests/f77/return_complex.py +++ b/numpy/f2py/tests/f77/return_complex.py @@ -6,7 +6,6 @@ Examples: python return_complex.py --quiet """ - import f2py2e from Numeric import array diff --git a/numpy/f2py/tests/f77/return_integer.py b/numpy/f2py/tests/f77/return_integer.py index 5bd7ae1ab..fe9e70fda 100644 --- a/numpy/f2py/tests/f77/return_integer.py +++ b/numpy/f2py/tests/f77/return_integer.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python return_integer.py [<f2py options>] diff --git a/numpy/f2py/tests/f77/return_logical.py b/numpy/f2py/tests/f77/return_logical.py index ac807b5be..cc5f9cb05 100644 --- a/numpy/f2py/tests/f77/return_logical.py +++ b/numpy/f2py/tests/f77/return_logical.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python return_logical.py [<f2py options>] diff --git a/numpy/f2py/tests/f77/return_real.py b/numpy/f2py/tests/f77/return_real.py index 29e720a85..a751743e9 100644 --- a/numpy/f2py/tests/f77/return_real.py +++ b/numpy/f2py/tests/f77/return_real.py @@ -6,7 +6,6 @@ Examples: python return_real.py --quiet """ - import numpy.f2py as f2py2e from numpy import array diff --git a/numpy/f2py/tests/f90/return_character.py b/numpy/f2py/tests/f90/return_character.py index 45174630a..1b5515f4d 100644 --- a/numpy/f2py/tests/f90/return_character.py +++ b/numpy/f2py/tests/f90/return_character.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python return_character.py [<f2py options>] diff --git a/numpy/f2py/tests/f90/return_complex.py b/numpy/f2py/tests/f90/return_complex.py index 71179e1f2..e615de218 100644 --- a/numpy/f2py/tests/f90/return_complex.py +++ b/numpy/f2py/tests/f90/return_complex.py @@ -5,7 +5,6 @@ Examples: python return_complex.py --quiet """ - import f2py2e from Numeric import array diff --git a/numpy/f2py/tests/f90/return_integer.py b/numpy/f2py/tests/f90/return_integer.py index 3e96dfd5f..c0241eeaf 100644 --- a/numpy/f2py/tests/f90/return_integer.py +++ b/numpy/f2py/tests/f90/return_integer.py @@ -1,4 +1,3 @@ - # XXX: investigate cases that are disabled under win32 # diff --git a/numpy/f2py/tests/f90/return_logical.py b/numpy/f2py/tests/f90/return_logical.py index c9479edaf..71cfe162e 100644 --- a/numpy/f2py/tests/f90/return_logical.py +++ b/numpy/f2py/tests/f90/return_logical.py @@ -1,4 +1,3 @@ - __usage__ = """ Run: python return_logical.py [<f2py options>] diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 5b0d326d1..7918ea3e5 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -36,7 +36,7 @@ def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, a = asarray(a) if n == None: n = a.shape[axis] - + if n < 1: raise ValueError("Invalid number of FFT data points (%d) specified." % n) try: diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 47e3f9d14..e17a0a726 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -1,4 +1,3 @@ - from info import __doc__ from numpy.version import version as __version__ diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index ca0269772..fe08912e7 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -66,11 +66,11 @@ def ediff1d(ary, to_end = None, to_begin = None): # We'll save ourselves a copy of a potentially large array in the common # case where neither to_begin or to_end was given. ed = nm.hstack(arrays) - + return ed def unique1d(ar1, return_index=False): - """Find the unique elements of 1D array. + """Find the unique elements of 1D array. Most of the other array set operations operate on the unique arrays generated by this function. @@ -96,13 +96,13 @@ def unique1d(ar1, return_index=False): if ar.size == 0: if return_index: return nm.empty(0, nm.bool), ar else: return ar - + if return_index: perm = ar.argsort() aux = ar[perm] flag = nm.concatenate( ([True], aux[1:] != aux[:-1]) ) return perm[flag], aux[flag] - + else: ar.sort() flag = nm.concatenate( ([True], ar[1:] != ar[:-1]) ) @@ -138,7 +138,7 @@ def intersect1d_nu( ar1, ar2 ): :Parameters: - `ar1` : array - `ar2` : array - + :Returns: - `intersection` : array @@ -172,7 +172,7 @@ def setxor1d( ar1, ar2 ): aux = nm.concatenate((ar1, ar2)) if aux.size == 0: return aux - + aux.sort() # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag = nm.concatenate( ([True], aux[1:] != aux[:-1], [True] ) ) diff --git a/numpy/lib/convdtype.py b/numpy/lib/convdtype.py index 17ed56102..ffef92e1c 100644 --- a/numpy/lib/convdtype.py +++ b/numpy/lib/convdtype.py @@ -63,4 +63,3 @@ def _test(): if __name__ == "__main__": _test() - diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 6e44bc205..1b79afc25 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -109,39 +109,39 @@ def histogram(a, bins=10, range=None, normed=False): def histogramdd(sample, bins=10, range=None, normed=False): """histogramdd(sample, bins = 10, range = None, normed = False) -> H, edges - + Return the D-dimensional histogram computed from sample. - + Parameters ---------- - sample: A sequence of D arrays, or an NxD array. - bins: A sequence of edge arrays, or a sequence of the number of bins. + sample: A sequence of D arrays, or an NxD array. + bins: A sequence of edge arrays, or a sequence of the number of bins. If a scalar is given, it is assumed to be the number of bins - for all dimensions. + for all dimensions. range: A sequence of lower and upper bin edges (default: [min, max]). - normed: If False, returns the number of samples in each bin. + normed: If False, returns the number of samples in each bin. If True, returns the frequency distribution. - - + + Output ------ H: Histogram array. - edges: List of arrays defining the bin edges. - + edges: List of arrays defining the bin edges. + Example: x = random.randn(100,3) H, edges = histogramdd(x, bins = (5, 6, 7)) - + See also: histogram """ - + try: N, D = sample.shape except (AttributeError, ValueError): ss = atleast_2d(sample) sample = ss.transpose() N, D = sample.shape - + nbin = empty(D, int) edges = D*[None] dedges = D*[None] @@ -152,7 +152,7 @@ def histogramdd(sample, bins=10, range=None, normed=False): raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D*[bins] - + if range is None: smin = atleast_1d(sample.min(0)) smax = atleast_1d(sample.max(0)) @@ -161,7 +161,7 @@ def histogramdd(sample, bins=10, range=None, normed=False): smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] - + for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] @@ -169,18 +169,18 @@ def histogramdd(sample, bins=10, range=None, normed=False): else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i])-1 - + Ncount = {} nbin = asarray(nbin) for i in arange(D): - Ncount[i] = digitize(sample[:,i], edges[i]) + Ncount[i] = digitize(sample[:,i], edges[i]) dedges[i] = diff(edges[i]) # Remove values falling outside of bins # Values that fall on an edge are put in the right bin. - # For the rightmost bin, we want values equal to the right + # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): @@ -192,23 +192,23 @@ def histogramdd(sample, bins=10, range=None, normed=False): for i in arange(D): Ncount[i] = Ncount[i][indices] - 1 N = len(indices) - + # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), int) - + # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() - + xy += Ncount[ni[-1]] - # Compute the number of repetitions in xy and assign it to the flattened histmat. + # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin, int) - + flatcount = bincount(xy) a = arange(len(flatcount)) hist[a] = flatcount @@ -219,7 +219,7 @@ def histogramdd(sample, bins=10, range=None, normed=False): hist = hist.swapaxes(i,j) if (hist.shape == nbin).all(): break - + if normed: s = hist.sum() for i in arange(D): @@ -227,9 +227,9 @@ def histogramdd(sample, bins=10, range=None, normed=False): shape[i] = nbin[i] hist = hist / dedges[i].reshape(shape) hist /= s - - return hist, edges - + + return hist, edges + def average(a, axis=None, weights=None, returned=False): """average(a, axis=None weights=None, returned=False) @@ -777,7 +777,7 @@ class vectorize(object): with the first element of the input. This can be avoided by specifying the otypes argument as either a string of typecode characters or a list of data-types specifiers. There should be one data-type specifier for - each output. + each output. Input: @@ -1054,7 +1054,7 @@ def i0(x): def kaiser(M,beta): """kaiser(M, beta) returns a Kaiser window of length M with shape parameter - beta. + beta. """ from numpy.dual import i0 n = arange(0,M) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 02f78bec5..e64d5dcd4 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -34,7 +34,7 @@ def unravel_index(x,dims): """ if x > _nx.prod(dims)-1 or x < 0: raise ValueError("Invalid index, must be 0 <= x <= number of elements.") - + idx = _nx.empty_like(dims) # Take dimensions @@ -275,7 +275,7 @@ class concatenator(object): newobj = array(newobj, copy=False, subok=True, ndmin=ndmin) if trans1d != -1 and tempobj.ndim < ndmin: - k2 = ndmin-tempobj.ndim + k2 = ndmin-tempobj.ndim if (trans1d < 0): trans1d += k2 + 1 defaxes = range(ndmin) diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 93bbc1f6d..9aea4ef12 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -650,4 +650,3 @@ class poly1d(object): # Stuff to do on module import warnings.simplefilter('always',RankWarning) - diff --git a/numpy/lib/setup.py b/numpy/lib/setup.py index f2ca221b2..0bd3c6ceb 100644 --- a/numpy/lib/setup.py +++ b/numpy/lib/setup.py @@ -1,4 +1,3 @@ - import imp import os from os.path import join diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index 32c47ede5..250525f76 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1,6 +1,6 @@ __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack', 'column_stack','row_stack', 'dstack','array_split','split','hsplit', - 'vsplit','dsplit','apply_over_axes','expand_dims', + 'vsplit','dsplit','apply_over_axes','expand_dims', 'apply_along_axis', 'kron', 'tile', 'get_array_wrap'] import numpy.core.numeric as _nx @@ -249,7 +249,7 @@ def column_stack(tup): must have the same first dimension. 2D arrays are stacked as-is, just like with hstack. 1D arrays are turned into 2D columns first. - + Arguments: tup -- sequence of 1D or 2D arrays. All arrays must have the same first dimension. @@ -532,12 +532,12 @@ def get_array_wrap(*args): In case of ties, leftmost wins. If no wrapper is found, return None """ wrappers = [(getattr(x, '__array_priority__', 0), -i, - x.__array_wrap__) for i, x in enumerate(args) + x.__array_wrap__) for i, x in enumerate(args) if hasattr(x, '__array_wrap__')] wrappers.sort() if wrappers: return wrappers[-1][-1] - return None + return None def kron(a,b): """kronecker product of a and b @@ -548,7 +548,7 @@ def kron(a,b): [ a[m-1,0]*b, a[m-1,1]*b, ... , a[m-1,n-1]*b ]] """ wrapper = get_array_wrap(a, b) - b = asanyarray(b) + b = asanyarray(b) a = array(a,copy=False,subok=True,ndmin=b.ndim) ndb, nda = b.ndim, a.ndim if (nda == 0 or ndb == 0): @@ -565,7 +565,7 @@ def kron(a,b): as_ = (1,)*(ndb-nda) + as_ else: bs = (1,)*(nda-ndb) + bs - nd = nda + nd = nda result = outer(a,b).reshape(as_+bs) axis = nd-1 for k in xrange(nd): @@ -626,4 +626,3 @@ def tile(A, reps): shape[i] = dim_out n /= dim_in return c.reshape(shape) - diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index 36b53c8e6..ccdcc7556 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -21,7 +21,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [1, 2, 5, 7] ) c = unique1d( a ) assert_array_equal( c, ec ) - + assert_array_equal([], unique1d([])) ## @@ -34,7 +34,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [1, 2, 5] ) c = intersect1d( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], intersect1d([],[])) ## @@ -47,7 +47,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [1, 2, 5] ) c = intersect1d_nu( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], intersect1d_nu([],[])) ## @@ -74,14 +74,14 @@ class test_aso(NumpyTestCase): ec = numpy.array( [1, 2, 3, 4, 5, 6] ) c = setxor1d( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], setxor1d([],[])) def check_ediff1d(self): zero_elem = numpy.array([]) one_elem = numpy.array([1]) two_elem = numpy.array([1,2]) - + assert_array_equal([],ediff1d(zero_elem)) assert_array_equal([0],ediff1d(zero_elem,to_begin=0)) assert_array_equal([0],ediff1d(zero_elem,to_end=0)) @@ -109,7 +109,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [True, False, True, False] ) c = setmember1d( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], setmember1d([],[])) ## @@ -122,7 +122,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [1, 2, 3, 4, 5, 7] ) c = union1d( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], union1d([],[])) ## @@ -142,7 +142,7 @@ class test_aso(NumpyTestCase): ec = numpy.array( [19, 20] ) c = setdiff1d( a, b ) assert_array_equal( c, ec ) - + assert_array_equal([], setdiff1d([],[])) diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index c3eaa9dd2..58f73ec5f 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1,4 +1,3 @@ - import sys from numpy.testing import * @@ -93,7 +92,7 @@ class test_linspace(NumpyTestCase): t3 = linspace(0,1,2).dtype assert_equal(t1, t2) assert_equal(t2, t3) - + class test_insert(NumpyTestCase): def check_basic(self): a = [1,2,3] @@ -276,23 +275,23 @@ class test_vectorize(NumpyTestCase): f = vectorize(addsubtract) r = f([0,3,6,9],5) assert_array_equal(r,[5,8,1,4]) - def check_large(self): - x = linspace(-3,2,10000) - f = vectorize(lambda x: x) - y = f(x) - assert_array_equal(y, x) + def check_large(self): + x = linspace(-3,2,10000) + f = vectorize(lambda x: x) + y = f(x) + assert_array_equal(y, x) class test_digitize(NumpyTestCase): def check_forward(self): x = arange(-6,5) bins = arange(-5,5) assert_array_equal(digitize(x,bins),arange(11)) - + def check_reverse(self): x = arange(5,-6,-1) bins = arange(5,-5,-1) assert_array_equal(digitize(x,bins),arange(11)) - + def check_random(self): x = rand(10) bin = linspace(x.min(), x.max(), 10) @@ -378,12 +377,12 @@ class test_histogramdd(NumpyTestCase): # Check that a sequence of arrays is accepted and H has the correct shape. z = [squeeze(y) for y in split(x,3,axis=1)] H, edges = histogramdd(z, bins=(4,3,2),range=[[-2,2], [0,3], [0,2]]) - answer = asarray([[[0,0],[0,0],[0,0]], - [[0,1], [0,0], [1,0]], - [[0,1], [0,0],[0,0]], + answer = asarray([[[0,0],[0,0],[0,0]], + [[0,1], [0,0], [1,0]], + [[0,1], [0,0],[0,0]], [[0,0],[0,0],[0,0]]]) assert_array_equal(H, answer) - + class test_unique(NumpyTestCase): def check_simple(self): diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index f7797396f..5d4f540b2 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -1,4 +1,3 @@ - from numpy.testing import * set_package_path() from numpy import array, ones, r_, mgrid diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py index e2afc72ae..f3a8720d9 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -78,7 +78,7 @@ import numpy as N class test_docs(NumpyTestCase): def check_doctests(self): return self.rundocs() - + def check_roots(self): assert_array_equal(N.roots([1,0,0]), [0,0]) diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py index 416c2644f..a96b4fc2c 100644 --- a/numpy/lib/tests/test_shape_base.py +++ b/numpy/lib/tests/test_shape_base.py @@ -1,4 +1,3 @@ - from numpy.testing import * set_package_path() import numpy.lib; @@ -360,17 +359,17 @@ class test_kron(NumpyTestCase): def check_return_type(self): a = ones([2,2]) m = asmatrix(a) - assert_equal(type(kron(a,a)), ndarray) - assert_equal(type(kron(m,m)), matrix) - assert_equal(type(kron(a,m)), matrix) - assert_equal(type(kron(m,a)), matrix) - class myarray(ndarray): + assert_equal(type(kron(a,a)), ndarray) + assert_equal(type(kron(m,m)), matrix) + assert_equal(type(kron(a,m)), matrix) + assert_equal(type(kron(m,a)), matrix) + class myarray(ndarray): __array_priority__ = 0.0 ma = myarray(a.shape, a.dtype, a.data) - assert_equal(type(kron(a,a)), ndarray) - assert_equal(type(kron(ma,ma)), myarray) - assert_equal(type(kron(a,ma)), ndarray) - assert_equal(type(kron(ma,a)), myarray) + assert_equal(type(kron(a,a)), ndarray) + assert_equal(type(kron(ma,ma)), myarray) + assert_equal(type(kron(a,ma)), ndarray) + assert_equal(type(kron(ma,a)), myarray) class test_tile(NumpyTestCase): diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index 3c6edfd24..7ef8a94e9 100644 --- a/numpy/lib/tests/test_twodim_base.py +++ b/numpy/lib/tests/test_twodim_base.py @@ -162,12 +162,12 @@ class test_histogram2d(NumpyTestCase): assert_array_almost_equal(H, answer/8., 3) def check_norm(self): x = array([1,2,3,1,2,3,1,2,3]) - y = array([1,1,1,2,2,2,3,3,3]) + y = array([1,1,1,2,2,2,3,3,3]) H, xed, yed = histogram2d(x,y,[[1,2,3,5], [1,2,3,5]], normed=True) answer=array([[1,1,.5], [1,1,.5], [.5,.5,.25]])/9. assert_array_almost_equal(H, answer, 3) - + if __name__ == "__main__": NumpyTest().run() diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py index dd9678302..8b990c57e 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -1,4 +1,3 @@ - import sys from numpy.testing import * diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index d79fd03c6..fd2ff586a 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -50,7 +50,7 @@ def eye(N, M=None, k=0, dtype=float): return m.astype(dtype) def diag(v, k=0): - """ returns a copy of the the k-th diagonal if v is a 2-d array + """ returns a copy of the the k-th diagonal if v is a 2-d array or returns a 2-d array with v as the k-th diagonal if v is a 1-d array. """ @@ -100,7 +100,7 @@ def diagflat(v,k=0): if not wrap: return res return wrap(res) - + def tri(N, M=None, k=0, dtype=float): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. @@ -108,7 +108,7 @@ def tri(N, M=None, k=0, dtype=float): if M is None: M = N m = greater_equal(subtract.outer(arange(N), arange(M)),-k) if m.dtype != dtype: - return m.astype(dtype) + return m.astype(dtype) def tril(m, k=0): """ returns the elements on and below the k-th diagonal of m. k=0 is the @@ -145,20 +145,20 @@ def vander(x, N=None): def histogram2d(x,y, bins=10, range=None, normed=False): """histogram2d(x,y, bins=10, range=None, normed=False) -> H, xedges, yedges - - Compute the 2D histogram from samples x,y. + + Compute the 2D histogram from samples x,y. Parameters ---------- x,y: 1D data series. Both arrays must have the same length. - bins: Number of bins -or- [nbin x, nbin y] -or- + bins: Number of bins -or- [nbin x, nbin y] -or- [bin edges] -or- [x bin edges, y bin edges]. range: A sequence of lower and upper bin edges (default: [min, max]). - normed: True or False. - - The histogram array is a count of the number of samples in each - two dimensional bin. - Setting normed to True returns a density rather than a bin count. + normed: True or False. + + The histogram array is a count of the number of samples in each + two dimensional bin. + Setting normed to True returns a density rather than a bin count. """ import numpy as np try: @@ -196,19 +196,19 @@ def histogram2d(x,y, bins=10, range=None, normed=False): xedges = yedges.copy() ynbin = len(yedges)-1 xnbin = len(xedges)-1 - + dxedges = np.diff(xedges) dyedges = np.diff(yedges) - + # Flattened histogram matrix (1D) hist = np.zeros((xnbin)*(ynbin), int) # Count the number of sample in each bin (1D) - xbin = np.digitize(x,xedges) - ybin = np.digitize(y,yedges) - + xbin = np.digitize(x,xedges) + ybin = np.digitize(y,yedges) + # Values that fall on an edge are put in the right bin. - # For the rightmost bin, we want values equal to the right + # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. xdecimal = int(-np.log10(dxedges.min()))+6 ydecimal = int(-np.log10(dyedges.min()))+6 @@ -220,15 +220,15 @@ def histogram2d(x,y, bins=10, range=None, normed=False): outliers = (xbin==0) | (xbin==xnbin+1) | (ybin==0) | (ybin == ynbin+1) xbin = xbin[outliers==False] - 1 ybin = ybin[outliers==False] - 1 - + # Compute the sample indices in the flattened histogram matrix. if xnbin >= ynbin: xy = ybin*(xnbin) + xbin - + else: xy = xbin*(ynbin) + ybin - - + + # Compute the number of repetitions in xy and assign it to the flattened # histogram matrix. diff --git a/numpy/lib/user_array.py b/numpy/lib/user_array.py index d20593f45..43e9da3f2 100644 --- a/numpy/lib/user_array.py +++ b/numpy/lib/user_array.py @@ -196,7 +196,7 @@ class container(object): return self.array.__getattribute__(attr) ############################################################# -# Test of class container +# Test of class container ############################################################# if __name__ == '__main__': temp=reshape(arange(10000),(100,100)) diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 981ec6de5..e50679eaa 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -7,7 +7,7 @@ from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', 'deprecate', 'get_numarray_include', - 'get_include', 'info', 'source', 'who'] + 'get_include', 'info', 'source', 'who'] def issubclass_(arg1, arg2): try: @@ -195,7 +195,7 @@ _dictlist = None # Traverse all module directories underneath globals # to see if something is defined def _makenamedict(module='numpy'): - module = __import__(module, globals(), locals(), []) + module = __import__(module, globals(), locals(), []) thedict = {module.__name__:module.__dict__} dictlist = [module.__name__] totraverse = [module.__dict__] @@ -373,4 +373,3 @@ def source(object, output=sys.stdout): print >> output, inspect.getsource(object) except: print >> output, "Not available for this object." - diff --git a/numpy/linalg/info.py b/numpy/linalg/info.py index e28668a8c..fce02b836 100644 --- a/numpy/linalg/info.py +++ b/numpy/linalg/info.py @@ -4,7 +4,7 @@ Core Linear Algebra Tools Linear Algebra Basics: - norm --- Vector or matrix norm + norm --- Vector or matrix norm inv --- Inverse of a square matrix solve --- Solve a linear system of equations det --- Determinant of a square matrix diff --git a/numpy/matlib.py b/numpy/matlib.py index 6035f394f..a4720bc3c 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -12,7 +12,7 @@ def empty(shape, dtype=None, order='C'): """return an empty matrix of the given shape """ return ndarray.__new__(matrix, shape, dtype, order=order) - + def ones(shape, dtype=None, order='C'): """return a matrix initialized to all ones """ @@ -23,7 +23,7 @@ def ones(shape, dtype=None, order='C'): def zeros(shape, dtype=None, order='C'): """return a matrix initialized to all zeros """ - a = ndarray.__new__(matrix, shape, dtype, order=order) + a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(0) return a diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py index 4a62324fc..ae950e7e0 100644 --- a/numpy/numarray/alter_code1.py +++ b/numpy/numarray/alter_code1.py @@ -50,7 +50,7 @@ Makes the following changes: - .setimag() --> .imag = - .getimaginary() --> .imag - .setimaginary() --> .imag - + """ __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] @@ -111,14 +111,14 @@ def replaceattr(astr): astr = astr.replace(".is_fortran_contiguous()",".flags.fortran") astr = astr.replace(".itemsize()",".itemsize") astr = astr.replace(".size()",".size") - astr = astr.replace(".nelements()",".size") + astr = astr.replace(".nelements()",".size") astr = astr.replace(".typecode()",".dtype.char") astr = astr.replace(".stddev()",".std()") astr = astr.replace(".getshape()", ".shape") astr = astr.replace(".getflat()", ".ravel()") astr = astr.replace(".getreal", ".real") astr = astr.replace(".getimag", ".imag") - astr = astr.replace(".getimaginary", ".imag") + astr = astr.replace(".getimaginary", ".imag") # preserve uses of flat that should be o.k. tmpstr = flatindex_re.sub(r"@@@@\2",astr) @@ -161,9 +161,9 @@ def replaceother(astr): astr = setshape_re.sub('\\1.shape = \\2', astr) astr = setreal_re.sub('\\1.real = \\2', astr) astr = setimag_re.sub('\\1.imag = \\2', astr) - astr = setimaginary_re.sub('\\1.imag = \\2', astr) + astr = setimaginary_re.sub('\\1.imag = \\2', astr) return astr - + import datetime def fromstr(filestr): savestr = filestr[:] @@ -249,7 +249,7 @@ def convertsrc(direc=os.path.curdir, ext=None, orig=1): else: os.remove(afile) makenewfile(afile, fstr) - + def _func(arg, dirname, fnames): convertall(dirname, orig=0) convertsrc(dirname, ['h','c'], orig=0) diff --git a/numpy/numarray/alter_code2.py b/numpy/numarray/alter_code2.py index 8505ca9cc..87ec5aa07 100644 --- a/numpy/numarray/alter_code2.py +++ b/numpy/numarray/alter_code2.py @@ -2,7 +2,7 @@ This module converts code written for numpy.numarray to work with numpy -FIXME: finish this. +FIXME: finish this. """ #__all__ = ['convertfile', 'convertall', 'converttree'] diff --git a/numpy/numarray/convolve.py b/numpy/numarray/convolve.py index 6c40ef111..68a4730a1 100644 --- a/numpy/numarray/convolve.py +++ b/numpy/numarray/convolve.py @@ -10,5 +10,5 @@ except ImportError: 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/functions.py b/numpy/numarray/functions.py index 2a6e5317b..329e08024 100644 --- a/numpy/numarray/functions.py +++ b/numpy/numarray/functions.py @@ -1,4 +1,3 @@ - # missing Numarray defined names (in from numarray import *) ##__all__ = ['ClassicUnpickler', 'Complex32_fromtype', ## 'Complex64_fromtype', 'ComplexArray', 'Error', @@ -8,7 +7,7 @@ ## 'PyINT_TYPES', 'PyLevel2Type', 'PyNUMERIC_TYPES', 'PyREAL_TYPES', ## 'SUPPRESS_SMALL', ## 'SuitableBuffer', 'USING_BLAS', -## 'UsesOpPriority', +## 'UsesOpPriority', ## 'codegenerator', 'generic', 'libnumarray', 'libnumeric', ## 'make_ufuncs', 'memory', ## 'numarrayall', 'numarraycore', 'numinclude', 'safethread', @@ -72,7 +71,7 @@ def type2dtype(typecode, type, dtype, use_default=True): def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 1) - return N.fromfunction(shape, dimensions, dtype=dtype) + return N.fromfunction(shape, dimensions, dtype=dtype) def ones(shape, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, 1) return N.ones(shape, dtype) @@ -90,7 +89,7 @@ def where(condition, x=None, y=None, out=None): out[...] = arr return out return arr - + def indices(shape, type=None): return N.indices(shape, type) @@ -118,7 +117,7 @@ def around(array, digits=0, output=None): if output is None: return ret return - + def array2list(arr): return arr.tolist() @@ -174,7 +173,7 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, shape = (-1,) if not isinstance(shape, tuple): shape = (shape,) - + if (list(shape).count(-1)>1): raise ValueError("At most one unspecified dimension in shape") @@ -208,7 +207,7 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, ##the most common case, namely reading in data from an unchanging ##file whose size may be determined before allocation, should be ##quick -- only one allocation will be needed. - + recsize = dtype.itemsize * N.product([i for i in shape if i != -1]) blocksize = max(_BLOCKSIZE/recsize, 1)*recsize @@ -265,7 +264,7 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, if a.dtype.char == '?': N.not_equal(a, 0, a) return a - + def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, True) if shape is None: @@ -275,7 +274,7 @@ def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None): res = N.fromstring(datastring, count=count) if shape is not None: res.shape = shape - return res + return res # check_overflow is ignored @@ -333,12 +332,12 @@ def getShape(shape, *args): if not issubclass(dummy.dtype.type, N.integer): raise TypeError if len(dummy) > N.MAXDIMS: - raise TypeError + raise TypeError except: raise TypeError("Shape must be a sequence of integers") return shape - + def identity(n, type=None, typecode=None, dtype=None): dtype = type2dtype(typecode, type, dtype, True) return N.identity(n, dtype) @@ -455,8 +454,8 @@ def take(array, indices, axis=0, outarr=None, clipmode=RAISE): if outarr is None: return res out[...] = res - return - + return + def tensormultiply(a1, a2): a1, a2 = N.asarray(a1), N.asarray(a2) if (a1.shape[-1] != a2.shape[0]): diff --git a/numpy/numarray/image.py b/numpy/numarray/image.py index 4ba23b68e..e24326f79 100644 --- a/numpy/numarray/image.py +++ b/numpy/numarray/image.py @@ -12,4 +12,4 @@ 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/numerictypes.py b/numpy/numarray/numerictypes.py index 3b27871df..490ced970 100644 --- a/numpy/numarray/numerictypes.py +++ b/numpy/numarray/numerictypes.py @@ -118,7 +118,7 @@ class NumericType(object): self.default = None self.typeno = -1 return self - + def __init__(self, name, bytes, default, typeno): if not isinstance(name, str): raise TypeError("name must be a string") @@ -159,7 +159,7 @@ class UnsignedIntegralType(IntegralType, UnsignedType): class FloatingType(NumericType): pass - + class ComplexType(NumericType): pass @@ -174,7 +174,7 @@ class ObjectType(NumericType): Any = AnyType("Any", None, None, _tAny) Object = ObjectType("Object", None, None, _tObject) - + # Numeric Types: Bool = BooleanType("Bool", 1, 0, _tBool) @@ -182,7 +182,7 @@ Int8 = SignedIntegralType( "Int8", 1, 0, _tInt8) Int16 = SignedIntegralType("Int16", 2, 0, _tInt16) Int32 = SignedIntegralType("Int32", 4, 0, _tInt32) Int64 = SignedIntegralType("Int64", 8, 0, _tInt64) - + Float32 = FloatingType("Float32", 4, 0.0, _tFloat32) Float64 = FloatingType("Float64", 8, 0.0, _tFloat64) @@ -227,8 +227,8 @@ else: Long = _register("Long", Int32) _register("ULong", UInt32) MaybeLong = _register("MaybeLong", Int32) - __all__.append('MaybeLong') - + __all__.append('MaybeLong') + _register("UByte", UInt8) _register("UShort", UInt16) @@ -249,7 +249,7 @@ _register("i4", Int32) _register("i8", Int64) if HasUInt64: _register("u8", UInt64) - + _register("f4", Float32) _register("f8", Float64) _register("c8", Complex32) @@ -272,7 +272,7 @@ if LP64: _register("l", Int64) else: _register("l", Int32) - + _register("d", Float64) _register("f", Float32) _register("D", Complex64) @@ -311,7 +311,7 @@ else: genericTypeRank = ['Bool','Int8','UInt8','Int16','UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Float32','Float64', 'Complex32', 'Complex64', 'Object'] - + pythonTypeRank = [ bool, int, long, float, complex ] # The next line is not platform independent XXX Needs to be generalized @@ -321,7 +321,7 @@ if not LP64: long:("Int64","int"), float:("Float64","float"), complex:("Complex64","complex")} - + scalarTypeMap = { int:"Int32", long:"Int64", @@ -348,7 +348,7 @@ scalarTypeMap.update({bool:"Bool"}) def _initGenericCoercions(): global genericCoercions genericCoercions = {} - + # vector with ... for ntype1 in genericTypeRank: nt1 = typeDict[ntype1] @@ -375,14 +375,14 @@ def _initGenericCoercions(): size = min(2*ntypesize1, MAX_INT_SIZE) else: size = ntypesize2 - outtype = "Int"+str(8*size) + outtype = "Int"+str(8*size) else: if rank1 >= rank2: outtype = ntype1 else: outtype = ntype2 genericCoercions[(ntype1, ntype2)] = outtype - + for ntype2 in pythonTypeRank: # scalar mapto, kind = pythonTypeMap[ntype2] @@ -397,7 +397,7 @@ def _initGenericCoercions(): outtype = mapto genericCoercions[(ntype1, ntype2)] = outtype genericCoercions[(ntype2, ntype1)] = outtype - + # scalar-scalar for ntype1 in pythonTypeRank: maptype1 = scalarTypeMap[ntype1] @@ -405,7 +405,7 @@ def _initGenericCoercions(): for ntype2 in pythonTypeRank: maptype2 = scalarTypeMap[ntype2] genericCoercions[(ntype1, ntype2)] = genericCoercions[(maptype1, maptype2)] - + # Special cases more easily dealt with outside of the loop genericCoercions[("Complex32", "Float64")] = "Complex64" genericCoercions[("Float64", "Complex32")] = "Complex64" @@ -454,42 +454,42 @@ typecodes = {'Integer': '1silN', if HasUInt64: _MaximumType = { Bool : UInt64, - + Int8 : Int64, Int16 : Int64, Int32 : Int64, Int64 : Int64, - + UInt8 : UInt64, UInt16 : UInt64, UInt32 : UInt64, UInt8 : UInt64, - + Float32 : Float64, Float64 : Float64, - + Complex32 : Complex64, - Complex64 : Complex64 + Complex64 : Complex64 } else: _MaximumType = { Bool : Int64, - + Int8 : Int64, Int16 : Int64, Int32 : Int64, Int64 : Int64, - + UInt8 : Int64, UInt16 : Int64, UInt32 : Int64, UInt8 : Int64, - + Float32 : Float64, Float64 : Float64, - + Complex32 : Complex64, - Complex64 : Complex64 + Complex64 : Complex64 } def MaximumType(t): @@ -510,7 +510,7 @@ def getType(type): raise TypeError("Not a numeric type") scalarTypes = (bool,int,long,float,complex) - + _scipy_dtypechar = { Int8 : 'b', UInt8 : 'B', @@ -546,7 +546,6 @@ if LP64: else: _scipy_dtypechar_inverse['p'] = Int32 _scipy_dtypechar_inverse['P'] = UInt32 - + def typefrom(obj): return _scipy_dtypechar_inverse[obj.dtype.char] - diff --git a/numpy/numarray/session.py b/numpy/numarray/session.py index 25520bd41..ee155f9dc 100644 --- a/numpy/numarray/session.py +++ b/numpy/numarray/session.py @@ -209,7 +209,7 @@ class _ObjectProxy(object): return False -class _SaveSession(object): +class _SaveSession(object): """Tag object which marks the end of a save session and holds the saved session variable names as a list of strings in the same order as the session pickles.""" @@ -250,13 +250,13 @@ def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): Defaults to dictionary.keys(). 'file' a filename or file object for the session file. - + 'dictionary' the dictionary in which to look up the variables. Defaults to the caller's globals() - + 'verbose' print additional debug output when True. """ - + global VERBOSE VERBOSE = verbose @@ -264,7 +264,7 @@ def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): if isinstance(file, str): file = open(file, "wb") - + if dictionary is None: dictionary = _callers_globals() @@ -272,7 +272,7 @@ def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): keys = dictionary.keys() else: keys = variables.split(",") - + source_modules = _callers_modules() + sys.modules.keys() p = pickle.Pickler(file, protocol=2) @@ -303,7 +303,7 @@ def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): file.close() def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): - + """load a numpy session from a file and store the specified 'variables' into 'dictionary'. @@ -311,16 +311,16 @@ def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): Defaults to dictionary.keys(). 'file' a filename or file object for the session file. - + 'dictionary' the dictionary in which to look up the variables. Defaults to the caller's globals() 'verbose' print additional debug output when True. """ - + global VERBOSE VERBOSE = verbose - + if isinstance(file, str): file = open(file, "rb") if dictionary is None: @@ -346,4 +346,3 @@ def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): def test(): import doctest, numpy.numarray.session return doctest.testmod(numpy.numarray.session) - diff --git a/numpy/numarray/setup.py b/numpy/numarray/setup.py index 39fc40152..056232d4b 100644 --- a/numpy/numarray/setup.py +++ b/numpy/numarray/setup.py @@ -1,4 +1,3 @@ - from os.path import join def configuration(parent_package='',top_path=None): @@ -6,7 +5,7 @@ def configuration(parent_package='',top_path=None): config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') - + # Configure fftpack_lite config.add_extension('_capi', sources=['_capi.c'] diff --git a/numpy/numarray/util.py b/numpy/numarray/util.py index 374c041cc..2a7efb60d 100644 --- a/numpy/numarray/util.py +++ b/numpy/numarray/util.py @@ -1,4 +1,3 @@ - from numpy import geterr __all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', 'handleError', @@ -39,4 +38,3 @@ def get_numarray_include_dirs(): base = os.path.dirname(numpy.__file__) newdirs = [os.path.join(base, 'numarray')] return newdirs - diff --git a/numpy/oldnumeric/__init__.py b/numpy/oldnumeric/__init__.py index dbf4298c5..83819ad04 100644 --- a/numpy/oldnumeric/__init__.py +++ b/numpy/oldnumeric/__init__.py @@ -1,4 +1,3 @@ - # Don't add these to the __all__ variable though from numpy import * @@ -34,7 +33,7 @@ __all__ += precision.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += misc.__all__ - + del compat del functions del precision diff --git a/numpy/oldnumeric/alter_code1.py b/numpy/oldnumeric/alter_code1.py index 73878de3f..87538a855 100644 --- a/numpy/oldnumeric/alter_code1.py +++ b/numpy/oldnumeric/alter_code1.py @@ -52,7 +52,7 @@ for name in _func2: for name in _func4: _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) + func_re[name] = re.compile(_astr, re.DOTALL) for name in _meth1: _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name @@ -143,7 +143,7 @@ def fromstr(filestr): filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') - filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') + filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') @@ -225,7 +225,7 @@ def convertsrc(direc=os.path.curdir, ext=None, orig=1): else: os.remove(afile) makenewfile(afile, fstr) - + def _func(arg, dirname, fnames): convertall(dirname, orig=0) convertsrc(dirname, ext=['h','c'], orig=0) @@ -234,7 +234,7 @@ def converttree(direc=os.path.curdir): """Convert all .py files and source code files in the tree given """ os.path.walk(direc, _func, None) - + if __name__ == '__main__': fromargs(sys.argv) diff --git a/numpy/oldnumeric/alter_code2.py b/numpy/oldnumeric/alter_code2.py index 6db8fe3e2..baa6b9d26 100644 --- a/numpy/oldnumeric/alter_code2.py +++ b/numpy/oldnumeric/alter_code2.py @@ -30,7 +30,7 @@ import os import re import glob -# To convert typecharacters we need to +# To convert typecharacters we need to # Not very safe. Disabled for now.. def replacetypechars(astr): astr = astr.replace("'s'","'h'") @@ -140,7 +140,7 @@ def converttree(direc=os.path.curdir): """Convert all .py files in the tree given """ - os.path.walk(direc, _func, None) + os.path.walk(direc, _func, None) if __name__ == '__main__': fromargs(sys.argv) diff --git a/numpy/oldnumeric/compat.py b/numpy/oldnumeric/compat.py index 42a98631f..1d376dd12 100644 --- a/numpy/oldnumeric/compat.py +++ b/numpy/oldnumeric/compat.py @@ -2,7 +2,7 @@ __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', - 'LittleEndian', 'arrayrange', 'matrixmultiply', + 'LittleEndian', 'arrayrange', 'matrixmultiply', 'array_constructor', 'pickle_array', 'DumpArray', 'LoadArray', 'multiarray', # from cPickle @@ -34,7 +34,7 @@ arraytype = mu.ndarray LittleEndian = (sys.byteorder == 'little') -from numpy import deprecate +from numpy import deprecate # backward compatibility arrayrange = deprecate(functions.arange, 'arrayrange', 'arange') @@ -67,4 +67,3 @@ def pickle_array(a): else: return (array_constructor, (a.shape, a.dtype.char, a.tostring(), LittleEndian)) - diff --git a/numpy/oldnumeric/fix_default_axis.py b/numpy/oldnumeric/fix_default_axis.py index 15054b50c..8483de85e 100644 --- a/numpy/oldnumeric/fix_default_axis.py +++ b/numpy/oldnumeric/fix_default_axis.py @@ -52,7 +52,7 @@ _all = _func0 + _funcm1 func_re = {} for name in _all: - _astr = r"""%s\s*[(]"""%name + _astr = r"""%s\s*[(]"""%name func_re[name] = re.compile(_astr) @@ -142,7 +142,7 @@ def _import_change(fstr, names): fstr = "%s%s%s" % (fstr[:ind], "import numpy.oldnumeric as numpy", fstr[ind+len(importstr):]) num += 1 - + # case 2 importre = re.compile("""import numpy as ([A-Za-z0-9_]+)""") modules = importre.findall(fstr) @@ -230,7 +230,7 @@ def add_axis(fstr, import_change=False): return fstr, total else: fstr, num = _import_change(fstr, _funcm1+_func0) - return fstr, num + return fstr, num def makenewfile(name, filestr): diff --git a/numpy/oldnumeric/functions.py b/numpy/oldnumeric/functions.py index 7d6d8abfa..1f09d8f84 100644 --- a/numpy/oldnumeric/functions.py +++ b/numpy/oldnumeric/functions.py @@ -44,10 +44,10 @@ def argmin(x, axis=-1): def compress(condition, m, axis=-1): return N.compress(condition, m, axis) - + def fromfunction(args, dimensions): return N.fromfunction(args, dimensions, dtype=int) - + def ones(shape, typecode='l', savespace=0, dtype=None): """ones(shape, dtype=int) returns an array of the given dimensions which is initialized to all ones. @@ -61,7 +61,7 @@ def zeros(shape, typecode='l', savespace=0, dtype=None): """zeros(shape, dtype=int) returns an array of the given dimensions which is initialized to all zeros """ - dtype = convtypecode(typecode,dtype) + dtype = convtypecode(typecode,dtype) return mu.zeros(shape, dtype) def identity(n,typecode='l', dtype=None): @@ -71,7 +71,7 @@ def identity(n,typecode='l', dtype=None): return nn.identity(n, dtype) def empty(shape, typecode='l', dtype=None): - dtype = convtypecode(typecode, dtype) + dtype = convtypecode(typecode, dtype) return mu.empty(shape, dtype) def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): @@ -122,4 +122,3 @@ def cross_product(a, b, axis1=-1, axis2=-1): def average(a, axis=0, weights=None, returned=False): return N.average(a, axis, weights, returned) - diff --git a/numpy/oldnumeric/linear_algebra.py b/numpy/oldnumeric/linear_algebra.py index 90d6f7138..2e7a264fe 100644 --- a/numpy/oldnumeric/linear_algebra.py +++ b/numpy/oldnumeric/linear_algebra.py @@ -1,4 +1,3 @@ - """Backward compatible with LinearAlgebra from Numeric """ # This module is a lite version of the linalg.py module in SciPy which contains @@ -7,10 +6,10 @@ # zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. -__all__ = ['LinAlgError', 'solve_linear_equations', +__all__ = ['LinAlgError', 'solve_linear_equations', 'inverse', 'cholesky_decomposition', 'eigenvalues', - 'Heigenvalues', 'generalized_inverse', - 'determinant', 'singular_value_decomposition', + 'Heigenvalues', 'generalized_inverse', + 'determinant', 'singular_value_decomposition', 'eigenvectors', 'Heigenvectors', 'linear_least_squares' ] @@ -52,7 +51,7 @@ def eigenvectors(A): def Heigenvectors(A): w, v = linalg.eigh(A) return w, transpose(v) - + # Generalized inverse def generalized_inverse(a, rcond = 1.e-10): diff --git a/numpy/oldnumeric/matrix.py b/numpy/oldnumeric/matrix.py index 321d8d4df..7c5b3700c 100644 --- a/numpy/oldnumeric/matrix.py +++ b/numpy/oldnumeric/matrix.py @@ -1,4 +1,4 @@ -# This module is for compatibility only. +# This module is for compatibility only. __all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string'] @@ -10,7 +10,7 @@ from numpy.oldnumeric import dot, identity, multiply import numpy.oldnumeric.linear_algebra as LinearAlgebra from numpy import matrix as Matrix, squeeze -# Hidden names that will be the same. +# Hidden names that will be the same. _table = [None]*256 for k in range(256): diff --git a/numpy/oldnumeric/misc.py b/numpy/oldnumeric/misc.py index 74a643c64..4b43f3985 100644 --- a/numpy/oldnumeric/misc.py +++ b/numpy/oldnumeric/misc.py @@ -31,7 +31,7 @@ from array_printer import array2string class Unpickler(pickle.Unpickler): def __init__(self, *args, **kwds): - raise NotImplemented + raise NotImplemented def load_array(self): raise NotImplemented diff --git a/numpy/oldnumeric/mlab.py b/numpy/oldnumeric/mlab.py index c7de8a417..c3e125fe3 100644 --- a/numpy/oldnumeric/mlab.py +++ b/numpy/oldnumeric/mlab.py @@ -13,7 +13,7 @@ from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ from numpy.linalg import eig, svd from numpy.random import rand, randn import numpy as nn - + from typeconv import convtypecode def eye(N, M=None, k=0, typecode=None, dtype=None): @@ -25,7 +25,7 @@ def eye(N, M=None, k=0, typecode=None, dtype=None): m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) - + def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. @@ -35,7 +35,7 @@ def tri(N, M=None, k=0, typecode=None, dtype=None): m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) - + def trapz(y, x=None, axis=-1): return _Ntrapz(y, x, axis=axis) @@ -113,10 +113,9 @@ __all__ += precision.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += misc.__all__ - + del compat del functions del precision del ufuncs del misc - diff --git a/numpy/oldnumeric/precision.py b/numpy/oldnumeric/precision.py index 8a242f023..f495992a8 100644 --- a/numpy/oldnumeric/precision.py +++ b/numpy/oldnumeric/precision.py @@ -3,7 +3,7 @@ # The character strings are still for "new" NumPy # which is the only Incompatibility with Numeric -__all__ = ['Character', 'Complex', 'Float', +__all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros'] @@ -46,25 +46,25 @@ except(PrecisionError): try: UnsignedInt16 = _lookup(_code_table, "UnsignedInteger", 16) UInt16 = UnsignedInt16 - __all__.extend(['UnsignedInt16', 'UInt16']) + __all__.extend(['UnsignedInt16', 'UInt16']) except(PrecisionError): pass try: UnsignedInt32 = _lookup(_code_table, "UnsignedInteger", 32) UInt32 = UnsignedInt32 - __all__.extend(['UnsignedInt32', 'UInt32']) + __all__.extend(['UnsignedInt32', 'UInt32']) except(PrecisionError): pass try: UnsignedInt64 = _lookup(_code_table, "UnsignedInteger", 64) UInt64 = UnsignedInt64 - __all__.extend(['UnsignedInt64', 'UInt64']) + __all__.extend(['UnsignedInt64', 'UInt64']) except(PrecisionError): pass try: UnsignedInt128 = _lookup(_code_table, "UnsignedInteger", 128) UInt128 = UnsignedInt128 - __all__.extend(['UnsignedInt128', 'UInt128']) + __all__.extend(['UnsignedInt128', 'UInt128']) except(PrecisionError): pass UnsignedInteger = 'u' @@ -77,7 +77,7 @@ except(PrecisionError): pass try: Int8 = _lookup(_code_table, 'Integer', 8) - __all__.append('Int8') + __all__.append('Int8') except(PrecisionError): pass try: @@ -109,7 +109,7 @@ except(PrecisionError): pass try: Float8 = _lookup(_code_table, 'Float', 8) - __all__.append('Float8') + __all__.append('Float8') except(PrecisionError): pass try: @@ -119,17 +119,17 @@ except(PrecisionError): pass try: Float32 = _lookup(_code_table, 'Float', 32) - __all__.append('Float32') + __all__.append('Float32') except(PrecisionError): pass try: Float64 = _lookup(_code_table, 'Float', 64) - __all__.append('Float64') + __all__.append('Float64') except(PrecisionError): pass try: Float128 = _lookup(_code_table, 'Float', 128) - __all__.append('Float128') + __all__.append('Float128') except(PrecisionError): pass Float = 'd' @@ -141,22 +141,22 @@ except(PrecisionError): pass try: Complex8 = _lookup(_code_table, 'Complex', 16) - __all__.append('Complex8') + __all__.append('Complex8') except(PrecisionError): pass try: Complex16 = _lookup(_code_table, 'Complex', 32) - __all__.append('Complex16') + __all__.append('Complex16') except(PrecisionError): pass try: Complex32 = _lookup(_code_table, 'Complex', 64) - __all__.append('Complex32') + __all__.append('Complex32') except(PrecisionError): pass try: Complex64 = _lookup(_code_table, 'Complex', 128) - __all__.append('Complex64') + __all__.append('Complex64') except(PrecisionError): pass try: diff --git a/numpy/oldnumeric/random_array.py b/numpy/oldnumeric/random_array.py index e8d386ce4..84e923e13 100644 --- a/numpy/oldnumeric/random_array.py +++ b/numpy/oldnumeric/random_array.py @@ -18,7 +18,7 @@ def seed(x=0, y=0): if (x == 0 or y == 0): mt.seed() else: - mt.seed((x,y)) + mt.seed((x,y)) def get_seed(): raise NotImplementedError, \ @@ -266,5 +266,3 @@ def test(): if __name__ == '__main__': test() - - diff --git a/numpy/oldnumeric/rng.py b/numpy/oldnumeric/rng.py index 77a90c694..fcf08bb37 100644 --- a/numpy/oldnumeric/rng.py +++ b/numpy/oldnumeric/rng.py @@ -1,7 +1,7 @@ # This module re-creates the RNG interface from Numeric # Replace import RNG with import numpy.oldnumeric.rng as RNG # -# It is for backwards compatibility only. +# It is for backwards compatibility only. __all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution', @@ -21,7 +21,7 @@ class Distribution(object): def density(self,x): raise NotImplementedError - + def __call__(self, x): return self.density(x) @@ -36,7 +36,7 @@ class Distribution(object): class ExponentialDistribution(Distribution): def __init__(self, lambda_): if (lambda_ <= 0): - raise error, "parameter must be positive" + raise error, "parameter must be positive" Distribution.__init__(self, 'exponential', lambda_) def density(x): @@ -115,7 +115,7 @@ class CreateGenerator(object): def sample(self, n): return self._dist._sample(self._rng, n) - + standard_generator = CreateGenerator(-1) def ranf(): @@ -126,12 +126,10 @@ def random_sample(*n): """random_sample(n) = array of n random numbers; random_sample(n1, n2, ...)= random array of shape (n1, n2, ..)""" - + if not n: return standard_generator.ranf() m = 1 for i in n: m = m * i return standard_generator.sample(m).reshape(*n) - - diff --git a/numpy/oldnumeric/tests/test_oldnumeric.py b/numpy/oldnumeric/tests/test_oldnumeric.py index 14d5dfd84..628ec231f 100644 --- a/numpy/oldnumeric/tests/test_oldnumeric.py +++ b/numpy/oldnumeric/tests/test_oldnumeric.py @@ -80,7 +80,7 @@ class test_oldtypes(NumPyTestCase): a1 = array([0,1,0], Bool) a2 = array([0,1,0], bool) assert_array_equal(a1, a2) - + if __name__ == "__main__": NumPyTest().run() diff --git a/numpy/oldnumeric/typeconv.py b/numpy/oldnumeric/typeconv.py index cb7239027..1fbf1e072 100644 --- a/numpy/oldnumeric/typeconv.py +++ b/numpy/oldnumeric/typeconv.py @@ -1,4 +1,3 @@ - __all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes'] import numpy as N @@ -48,7 +47,7 @@ _changedtypes = {'B': 'b', 'h': 's', 'H': 'w', 'I': 'u'} - + class _oldtypecodes(dict): def __getitem__(self, obj): char = N.dtype(obj).char diff --git a/numpy/oldnumeric/ufuncs.py b/numpy/oldnumeric/ufuncs.py index 58fa473a6..c26050f55 100644 --- a/numpy/oldnumeric/ufuncs.py +++ b/numpy/oldnumeric/ufuncs.py @@ -17,4 +17,3 @@ from numpy import less, cosh, arcsinh, add, ceil, arctan2, floor_divide, \ arccosh, logical_or, minimum, conjugate, tan, greater, bitwise_xor, \ fabs, floor, sqrt, arctan, right_shift, absolute, sin, \ multiply, greater_equal, left_shift, exp, divide as divide_safe - diff --git a/numpy/random/setup.py b/numpy/random/setup.py index b79a80d23..bf49a768f 100644 --- a/numpy/random/setup.py +++ b/numpy/random/setup.py @@ -1,4 +1,3 @@ - from os.path import join, split def configuration(parent_package='',top_path=None): @@ -32,7 +31,7 @@ def configuration(parent_package='',top_path=None): ) config.add_data_files(('.', join('mtrand', 'randomkit.h'))) - + return config def testcode_wincrypt(): diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py index 5f4ceef17..c7688ad61 100644 --- a/numpy/testing/numpytest.py +++ b/numpy/testing/numpytest.py @@ -1,4 +1,3 @@ - import os import re import sys @@ -452,8 +451,6 @@ class NumpyTest: continue modules.append(module) - - self.test_files = [] suites = [] for module in modules: @@ -535,7 +532,7 @@ class NumpyTest: if not sys.modules.has_key(test_dir_module): sys.modules[test_dir_module] = imp.new_module(test_dir_module) - + for fn in os.listdir(test_dir): base, ext = os.path.splitext(fn) if ext != '.py': @@ -581,7 +578,7 @@ class NumpyTest: all_tests = unittest.TestSuite(suite_list) if level<0: return all_tests - + runner = unittest.TextTestRunner(verbosity=verbosity) # Use the builtin displayhook. If the tests are being run # under IPython (for instance), any doctest test suites will @@ -628,7 +625,7 @@ class NumpyTest: sys.stdout.flush() ScipyTest = NumpyTest - + def importall(package): """ Try recursively to import all subpackages under package. diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py index 6931bc36b..6ee75271d 100644 --- a/numpy/tests/test_ctypeslib.py +++ b/numpy/tests/test_ctypeslib.py @@ -1,63 +1,63 @@ -from numpy.testing import * -set_package_path() -import numpy as N +from numpy.testing import * +set_package_path() +import numpy as N from numpy.ctypeslib import ndpointer -restore_path() - -class test_ndpointer(NumpyTestCase): - def check_dtype(self): - dt = N.intc - p = ndpointer(dtype=dt) - self.assert_(p.from_param(N.array([1], dt))) - dt = '<i4' - p = ndpointer(dtype=dt) - self.assert_(p.from_param(N.array([1], dt))) - dt = N.dtype('>i4') - p = ndpointer(dtype=dt) - p.from_param(N.array([1], dt)) - self.assertRaises(TypeError, p.from_param, - N.array([1], dt.newbyteorder('swap'))) - dtnames = ['x', 'y'] - dtformats = [N.intc, N.float64] - dtdescr = {'names' : dtnames, 'formats' : dtformats} - dt = N.dtype(dtdescr) - p = ndpointer(dtype=dt) - self.assert_(p.from_param(N.zeros((10,), dt))) - samedt = N.dtype(dtdescr) - p = ndpointer(dtype=samedt) - self.assert_(p.from_param(N.zeros((10,), dt))) +restore_path() + +class test_ndpointer(NumpyTestCase): + def check_dtype(self): + dt = N.intc + p = ndpointer(dtype=dt) + self.assert_(p.from_param(N.array([1], dt))) + dt = '<i4' + p = ndpointer(dtype=dt) + self.assert_(p.from_param(N.array([1], dt))) + dt = N.dtype('>i4') + p = ndpointer(dtype=dt) + p.from_param(N.array([1], dt)) + self.assertRaises(TypeError, p.from_param, + N.array([1], dt.newbyteorder('swap'))) + dtnames = ['x', 'y'] + dtformats = [N.intc, N.float64] + dtdescr = {'names' : dtnames, 'formats' : dtformats} + dt = N.dtype(dtdescr) + p = ndpointer(dtype=dt) + self.assert_(p.from_param(N.zeros((10,), dt))) + samedt = N.dtype(dtdescr) + p = ndpointer(dtype=samedt) + self.assert_(p.from_param(N.zeros((10,), dt))) dt2 = N.dtype(dtdescr, align=True) if dt.itemsize != dt2.itemsize: self.assertRaises(TypeError, p.from_param, N.zeros((10,), dt2)) else: self.assert_(p.from_param(N.zeros((10,), dt2))) - - def check_ndim(self): - p = ndpointer(ndim=0) - self.assert_(p.from_param(N.array(1))) - self.assertRaises(TypeError, p.from_param, N.array([1])) - p = ndpointer(ndim=1) - self.assertRaises(TypeError, p.from_param, N.array(1)) - self.assert_(p.from_param(N.array([1]))) - p = ndpointer(ndim=2) - self.assert_(p.from_param(N.array([[1]]))) - - def check_shape(self): - p = ndpointer(shape=(1,2)) - self.assert_(p.from_param(N.array([[1,2]]))) - self.assertRaises(TypeError, p.from_param, N.array([[1],[2]])) - p = ndpointer(shape=()) - self.assert_(p.from_param(N.array(1))) - - def check_flags(self): - x = N.array([[1,2,3]], order='F') - p = ndpointer(flags='FORTRAN') - self.assert_(p.from_param(x)) - p = ndpointer(flags='CONTIGUOUS') - self.assertRaises(TypeError, p.from_param, x) - p = ndpointer(flags=x.flags.num) - self.assert_(p.from_param(x)) - self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]])) - -if __name__ == "__main__": - NumpyTest().run() + + def check_ndim(self): + p = ndpointer(ndim=0) + self.assert_(p.from_param(N.array(1))) + self.assertRaises(TypeError, p.from_param, N.array([1])) + p = ndpointer(ndim=1) + self.assertRaises(TypeError, p.from_param, N.array(1)) + self.assert_(p.from_param(N.array([1]))) + p = ndpointer(ndim=2) + self.assert_(p.from_param(N.array([[1]]))) + + def check_shape(self): + p = ndpointer(shape=(1,2)) + self.assert_(p.from_param(N.array([[1,2]]))) + self.assertRaises(TypeError, p.from_param, N.array([[1],[2]])) + p = ndpointer(shape=()) + self.assert_(p.from_param(N.array(1))) + + def check_flags(self): + x = N.array([[1,2,3]], order='F') + p = ndpointer(flags='FORTRAN') + self.assert_(p.from_param(x)) + p = ndpointer(flags='CONTIGUOUS') + self.assertRaises(TypeError, p.from_param, x) + p = ndpointer(flags=x.flags.num) + self.assert_(p.from_param(x)) + self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]])) + +if __name__ == "__main__": + NumpyTest().run() |