diff options
Diffstat (limited to 'numpy')
53 files changed, 352 insertions, 116 deletions
diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py index c0a901a8d..6223dd57f 100644 --- a/numpy/_import_tools.py +++ b/numpy/_import_tools.py @@ -68,7 +68,7 @@ class PackageLoader(object): try: exec 'import %s.info as info' % (package_name) info_modules[package_name] = info - except ImportError, msg: + except ImportError as msg: self.warn('No scipy-style subpackage %r found in %s. '\ 'Ignoring: %s'\ % (package_name,':'.join(self.parent_path), msg)) @@ -87,7 +87,7 @@ class PackageLoader(object): open(info_file,filedescriptor[1]), info_file, filedescriptor) - except Exception,msg: + except Exception as msg: self.error(msg) info_module = None @@ -241,7 +241,7 @@ class PackageLoader(object): frame = self.parent_frame try: exec (cmdstr, frame.f_globals,frame.f_locals) - except Exception,msg: + except Exception as msg: self.error('%s -> failed: %s' % (cmdstr,msg)) return True else: diff --git a/numpy/build_utils/waf.py b/numpy/build_utils/waf.py index 4ef71327c..e8f63c570 100644 --- a/numpy/build_utils/waf.py +++ b/numpy/build_utils/waf.py @@ -166,7 +166,7 @@ int main () try: conf.run_c_code(**kw) - except conf.errors.ConfigurationError, e: + except conf.errors.ConfigurationError as e: conf.end_msg("failed !") if waflib.Logs.verbose > 1: raise diff --git a/numpy/core/bscript b/numpy/core/bscript index b774021e9..3d9b84018 100644 --- a/numpy/core/bscript +++ b/numpy/core/bscript @@ -30,11 +30,7 @@ from setup_common \ C99_FUNCS_SINGLE, C99_COMPLEX_TYPES, C99_COMPLEX_FUNCS, \ MANDATORY_FUNCS, C_ABI_VERSION, C_API_VERSION -try: - val = os.environ['NPY_SEPARATE_COMPILATION'] - ENABLE_SEPARATE_COMPILATION = (val != "0") -except KeyError: - ENABLE_SEPARATE_COMPILATION = False +ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0") NUMPYCONFIG_SYM = [] diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index d73f1313c..7596e3707 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -57,6 +57,10 @@ def take(a, indices, axis=None, out=None, mode='raise'): The source array. indices : array_like The indices of the values to extract. + + .. versionadded:: 1.8.0 + + Also allow scalars for indices. axis : int, optional The axis over which to select values. By default, the flattened input array is used. @@ -96,6 +100,11 @@ def take(a, indices, axis=None, out=None, mode='raise'): >>> a[indices] array([4, 3, 6]) + If `indices` is not one dimensional, the output also has these dimensions. + + >>> np.take(a, [[0, 1], [2, 3]]) + array([[4, 3], + [5, 7]]) """ try: take = a.take diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 521001575..4c5651c3a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -81,6 +81,10 @@ def zeros_like(a, dtype=None, order='K', subok=True): 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. + subok : bool, optional. + If True, then the newly created array will use the sub-class + type of 'a', otherwise it will be a base-class array. Defaults + to True. Returns ------- @@ -167,6 +171,10 @@ def ones_like(a, dtype=None, order='K', subok=True): 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. + subok : bool, optional. + If True, then the newly created array will use the sub-class + type of 'a', otherwise it will be a base-class array. Defaults + to True. Returns ------- diff --git a/numpy/core/setup.py b/numpy/core/setup.py index a1000ae0b..6a8b0fc38 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -12,11 +12,7 @@ import re from setup_common import * # Set to True to enable multiple file compilations (experimental) -try: - val = os.environ['NPY_SEPARATE_COMPILATION'] - ENABLE_SEPARATE_COMPILATION = (val != "0") -except KeyError: - ENABLE_SEPARATE_COMPILATION = False +ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0") # XXX: ugly, we use a class to avoid calling twice some expensive functions in # config.h/numpyconfig.h. I don't see a better way because distutils force diff --git a/numpy/core/src/multiarray/arrayobject.c b/numpy/core/src/multiarray/arrayobject.c index 10b750cdb..b559d4aba 100644 --- a/numpy/core/src/multiarray/arrayobject.c +++ b/numpy/core/src/multiarray/arrayobject.c @@ -1655,7 +1655,7 @@ array_alloc(PyTypeObject *type, Py_ssize_t NPY_UNUSED(nitems)) { PyObject *obj; /* nitems will always be 0 */ - obj = (PyObject *)PyArray_malloc(NPY_SIZEOF_PYARRAYOBJECT); + obj = (PyObject *)PyArray_malloc(type->tp_basicsize); PyObject_Init(obj, type); return obj; } diff --git a/numpy/core/src/multiarray/item_selection.c b/numpy/core/src/multiarray/item_selection.c index ab8480857..4adecf193 100644 --- a/numpy/core/src/multiarray/item_selection.c +++ b/numpy/core/src/multiarray/item_selection.c @@ -31,10 +31,11 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, PyArray_Descr *dtype; PyArray_FastTakeFunc *func; PyArrayObject *obj = NULL, *self, *indices; - npy_intp nd, i, j, n, m, max_item, tmp, chunk, nelem; + npy_intp nd, i, j, n, m, k, max_item, tmp, chunk, itemsize, nelem; npy_intp shape[NPY_MAXDIMS]; - char *src, *dest; + char *src, *dest, *tmp_src; int err; + npy_bool needs_refcounting; indices = NULL; self = (PyArrayObject *)PyArray_CheckAxis(self0, &axis, @@ -44,13 +45,11 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, } indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, NPY_INTP, - 1, 0); + 0, 0); if (indices == NULL) { goto fail; } - - n = m = chunk = 1; nd = PyArray_NDIM(self) + PyArray_NDIM(indices) - 1; for (i = 0; i < nd; i++) { @@ -112,9 +111,18 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, max_item = PyArray_DIMS(self)[axis]; nelem = chunk; - chunk = chunk * PyArray_DESCR(obj)->elsize; + itemsize = PyArray_ITEMSIZE(obj); + chunk = chunk * itemsize; src = PyArray_DATA(self); dest = PyArray_DATA(obj); + needs_refcounting = PyDataType_REFCHK(PyArray_DESCR(self)); + + if ((max_item == 0) && (PyArray_SIZE(obj) != 0)) { + /* Index error, since that is the usual error for raise mode */ + PyErr_SetString(PyExc_IndexError, + "cannot do a non-empty take from an empty axes."); + goto fail; + } func = PyArray_DESCR(self)->f->fasttake; if (func == NULL) { @@ -126,8 +134,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, if (check_and_adjust_index(&tmp, max_item, axis) < 0) { goto fail; } - memmove(dest, src + tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -146,8 +166,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, tmp -= max_item; } } - memmove(dest, src + tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -162,8 +194,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, else if (tmp >= max_item) { tmp = max_item - 1; } - memmove(dest, src+tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -178,7 +222,6 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, } } - PyArray_INCREF(obj); Py_XDECREF(indices); Py_XDECREF(self); if (out != NULL && out != obj) { @@ -752,6 +795,9 @@ _new_sort(PyArrayObject *op, int axis, NPY_SORTKIND which) (astride != (npy_intp) elsize) || swap; if (needcopy) { char *buffer = PyDataMem_NEW(N*elsize); + if (buffer == NULL) { + goto fail; + } while (size--) { _unaligned_strided_byte_copy(buffer, (npy_intp) elsize, it->dataptr, @@ -785,9 +831,11 @@ _new_sort(PyArrayObject *op, int axis, NPY_SORTKIND which) return 0; fail: + /* Out of memory during sorting or buffer creation */ NPY_END_THREADS; + PyErr_NoMemory(); Py_DECREF(it); - return 0; + return -1; } static PyObject* @@ -797,10 +845,10 @@ _new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which) PyArrayIterObject *it = NULL; PyArrayIterObject *rit = NULL; PyArrayObject *ret; - int needcopy = 0, i; - npy_intp N, size; - int elsize, swap; + npy_intp N, size, i; npy_intp astride, rstride, *iptr; + int elsize; + int needcopy = 0, swap; PyArray_ArgSortFunc *argsort; NPY_BEGIN_THREADS_DEF; @@ -834,7 +882,14 @@ _new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which) char *valbuffer, *indbuffer; valbuffer = PyDataMem_NEW(N*elsize); + if (valbuffer == NULL) { + goto fail; + } indbuffer = PyDataMem_NEW(N*sizeof(npy_intp)); + if (indbuffer == NULL) { + PyDataMem_FREE(valbuffer); + goto fail; + } while (size--) { _unaligned_strided_byte_copy(valbuffer, (npy_intp) elsize, it->dataptr, astride, N, elsize); @@ -880,6 +935,10 @@ _new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which) fail: NPY_END_THREADS; + if (!PyErr_Occurred()) { + /* Out of memory during sorting or buffer creation */ + PyErr_NoMemory(); + } Py_DECREF(ret); Py_XDECREF(it); Py_XDECREF(rit); @@ -954,7 +1013,8 @@ PyArray_Sort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayObject *ap = NULL, *store_arr = NULL; char *ip; - int i, n, m, elsize, orign; + npy_intp i, n, m; + int elsize, orign; int res = 0; int axis_orig = axis; int (*sort)(void *, size_t, size_t, npy_comparator); @@ -1210,13 +1270,12 @@ PyArray_LexSort(PyObject *sort_keys, int axis) PyArrayIterObject **its; PyArrayObject *ret = NULL; PyArrayIterObject *rit = NULL; - int n; + npy_intp n, N, size, i, j; + npy_intp astride, rstride, *iptr; int nd; - int needcopy = 0, i,j; - npy_intp N, size; + int needcopy = 0; int elsize; int maxelsize; - npy_intp astride, rstride, *iptr; int object = 0; PyArray_ArgSortFunc *argsort; NPY_BEGIN_THREADS_DEF; @@ -1227,11 +1286,11 @@ PyArray_LexSort(PyObject *sort_keys, int axis) "need sequence of keys with len > 0 in lexsort"); return NULL; } - mps = (PyArrayObject **) PyArray_malloc(n*NPY_SIZEOF_PYARRAYOBJECT); + mps = (PyArrayObject **) PyArray_malloc(n * sizeof(PyArrayObject *)); if (mps == NULL) { return PyErr_NoMemory(); } - its = (PyArrayIterObject **) PyArray_malloc(n*sizeof(PyArrayIterObject)); + its = (PyArrayIterObject **) PyArray_malloc(n * sizeof(PyArrayIterObject *)); if (its == NULL) { PyArray_free(mps); return PyErr_NoMemory(); @@ -1333,7 +1392,14 @@ PyArray_LexSort(PyObject *sort_keys, int axis) int *swaps; valbuffer = PyDataMem_NEW(N*maxelsize); + if (valbuffer == NULL) { + goto fail; + } indbuffer = PyDataMem_NEW(N*sizeof(npy_intp)); + if (indbuffer == NULL) { + PyDataMem_FREE(indbuffer); + goto fail; + } swaps = malloc(n*sizeof(int)); for (j = 0; j < n; j++) { swaps[j] = PyArray_ISBYTESWAPPED(mps[j]); @@ -1402,6 +1468,10 @@ PyArray_LexSort(PyObject *sort_keys, int axis) fail: NPY_END_THREADS; + if (!PyErr_Occurred()) { + /* Out of memory during sorting or buffer creation */ + PyErr_NoMemory(); + } Py_XDECREF(rit); Py_XDECREF(ret); for (i = 0; i < n; i++) { diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index 7f0e3861b..902384b0d 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -633,6 +633,7 @@ array_toscalar(PyArrayObject *self, PyObject *args) else { PyErr_SetString(PyExc_ValueError, "can only convert an array of size 1 to a Python scalar"); + return NULL; } } /* Special case of C-order flat indexing... :| */ diff --git a/numpy/core/src/npysort/mergesort.c.src b/numpy/core/src/npysort/mergesort.c.src index 1003b95d1..55dcab4fb 100644 --- a/numpy/core/src/npysort/mergesort.c.src +++ b/numpy/core/src/npysort/mergesort.c.src @@ -112,7 +112,6 @@ mergesort_@suff@(@type@ *start, npy_intp num, void *NOT_USED) pr = pl + num; pw = (@type@ *) malloc((num/2) * sizeof(@type@)); if (pw == NULL) { - PyErr_NoMemory(); return -NPY_ENOMEM; } mergesort0_@suff@(pl, pr, pw); @@ -176,7 +175,6 @@ amergesort_@suff@(@type@ *v, npy_intp *tosort, npy_intp num, void *NOT_USED) pr = pl + num; pw = (npy_intp *) malloc((num/2) * sizeof(npy_intp)); if (pw == NULL) { - PyErr_NoMemory(); return -NPY_ENOMEM; } amergesort0_@suff@(pl, pr, v, pw); @@ -259,13 +257,11 @@ mergesort_@suff@(@type@ *start, npy_intp num, PyArrayObject *arr) pr = pl + num*len; pw = (@type@ *) malloc((num/2) * elsize); if (pw == NULL) { - PyErr_NoMemory(); err = -NPY_ENOMEM; goto fail_0; } vp = (@type@ *) malloc(elsize); if (vp == NULL) { - PyErr_NoMemory(); err = -NPY_ENOMEM; goto fail_1; } @@ -335,7 +331,6 @@ amergesort_@suff@(@type@ *v, npy_intp *tosort, npy_intp num, PyArrayObject *arr) pr = pl + num; pw = (npy_intp *) malloc((num/2) * sizeof(npy_intp)); if (pw == NULL) { - PyErr_NoMemory(); return -NPY_ENOMEM; } amergesort0_@suff@(pl, pr, v, pw, len); diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index 31a206e1c..f1cf36b5b 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -9,7 +9,7 @@ from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \ def assert_raises_fpe(strmatch, callable, *args, **kwargs): try: callable(*args, **kwargs) - except FloatingPointError, exc: + except FloatingPointError as exc: assert_(str(exc).find(strmatch) >= 0, "Did not raise floating point %s error" % strmatch) else: diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py index af10df9b3..2f9c5d4d2 100644 --- a/numpy/core/tests/test_indexerrors.py +++ b/numpy/core/tests/test_indexerrors.py @@ -10,6 +10,8 @@ class TestIndexErrors(TestCase): x = np.empty((2, 3, 0, 4)) assert_raises(IndexError, x.take, [0], axis=2) assert_raises(IndexError, x.take, [1], axis=2) + assert_raises(IndexError, x.take, [0], axis=2, mode='wrap') + assert_raises(IndexError, x.take, [0], axis=2, mode='clip') def test_take_from_object(self): # Check exception taking from object array @@ -21,6 +23,8 @@ class TestIndexErrors(TestCase): assert_raises(IndexError, d.take, [1], axis=1) assert_raises(IndexError, d.take, [0], axis=1) assert_raises(IndexError, d.take, [0]) + assert_raises(IndexError, d.take, [0], mode='wrap') + assert_raises(IndexError, d.take, [0], mode='clip') def test_multiindex_exceptions(self): a = np.empty(5, dtype=object) diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py new file mode 100644 index 000000000..47de43012 --- /dev/null +++ b/numpy/core/tests/test_item_selection.py @@ -0,0 +1,63 @@ +import numpy as np +from numpy.testing import * +import sys, warnings + + +class TestTake(TestCase): + def test_simple(self): + a = [[1, 2], [3, 4]] + a_str = [[b'1', b'2'],[b'3', b'4']] + modes = ['raise', 'wrap', 'clip'] + indices = [-1, 4] + index_arrays = [np.empty(0, dtype=np.intp), + np.empty(tuple(), dtype=np.intp), + np.empty((1,1), dtype=np.intp)] + real_indices = {} + real_indices['raise'] = {-1:1, 4:IndexError} + real_indices['wrap'] = {-1:1, 4:0} + real_indices['clip'] = {-1:0, 4:1} + # Currently all types but object, use the same function generation. + # So it should not be necessary to test all. However test also a non + # refcounted struct on top of object. + types = np.int, np.object, np.dtype([('', 'i', 2)]) + for t in types: + # ta works, even if the array may be odd if buffer interface is used + ta = np.array(a if np.issubdtype(t, np.number) else a_str, dtype=t) + tresult = list(ta.T.copy()) + for index_array in index_arrays: + if index_array.size != 0: + tresult[0].shape = (2,) + index_array.shape + tresult[1].shape = (2,) + index_array.shape + for mode in modes: + for index in indices: + real_index = real_indices[mode][index] + if real_index is IndexError and index_array.size != 0: + index_array.put(0, index) + assert_raises(IndexError, ta.take, index_array, + mode=mode, axis=1) + elif index_array.size != 0: + index_array.put(0, index) + res = ta.take(index_array, mode=mode, axis=1) + assert_array_equal(res, tresult[real_index]) + else: + res = ta.take(index_array, mode=mode, axis=1) + assert_(res.shape == (2,) + index_array.shape) + + + def test_refcounting(self): + objects = [object() for i in xrange(10)] + for mode in ('raise', 'clip', 'wrap'): + a = np.array(objects) + b = np.array([2, 2, 4, 5, 3, 5]) + a.take(b, out=a[:6]) + del a + assert_(all(sys.getrefcount(o) == 3 for o in objects)) + # not contiguous, example: + a = np.array(objects * 2)[::2] + a.take(b, out=a[:6]) + del a + assert_(all(sys.getrefcount(o) == 3 for o in objects)) + + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py index 4175ceeac..99046ca2a 100644 --- a/numpy/core/tests/test_machar.py +++ b/numpy/core/tests/test_machar.py @@ -21,7 +21,7 @@ class TestMachAr(TestCase): try: try: self._run_machar_highprec() - except FloatingPointError, e: + except FloatingPointError as e: self.fail("Caught %s exception, should not have been raised." % e) finally: seterr(**serrstate) diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index 4abe5e2ff..f40ac68a8 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -632,7 +632,7 @@ def test_iter_broadcasting_errors(): [], [['readonly'], ['readonly'], ['writeonly','no_broadcast']]) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain the shape of the 3rd operand assert_(msg.find('(2,3)') >= 0, @@ -647,7 +647,7 @@ def test_iter_broadcasting_errors(): op_axes=[[0,1], [0,np.newaxis]], itershape=(4,3)) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain "shape->remappedshape" for each operand assert_(msg.find('(2,3)->(2,3)') >= 0, @@ -664,7 +664,7 @@ def test_iter_broadcasting_errors(): [], [['writeonly','no_broadcast'], ['readonly']]) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain the shape of the bad operand assert_(msg.find('(2,1,1)') >= 0, diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index b6a9c5157..6b5f86e5a 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -269,7 +269,7 @@ class TestFloatExceptions(TestCase): flop(x, y) assert_(False, "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) - except FloatingPointError, exc: + except FloatingPointError as exc: assert_(str(exc).find(fpeerr) >= 0, "Type %s raised wrong fpe error '%s'." % (ftype, exc)) diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index d40275ef4..aed262ad2 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -225,7 +225,7 @@ def test_scalar_format(): try: assert_equal(fmat.format(val), fmat.format(valtype(val)), "failed with val %s, type %s" % (val, valtype)) - except ValueError, e: + except ValueError as e: assert_(False, "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" % (fmat, repr(val), repr(valtype), str(e))) diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 1cf2e6e85..235918718 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -626,6 +626,17 @@ class TestRegression(TestCase): np.take(x,[0,2],axis=1,out=b) assert_array_equal(a,b) + def test_take_object_fail(self): + # Issue gh-3001 + d = 123. + a = np.array([d, 1], dtype=object) + ref_d = sys.getrefcount(d) + try: + a.take([0, 100]) + except IndexError: + pass + assert_(ref_d == sys.getrefcount(d)) + def test_array_str_64bit(self, level=rlevel): """Ticket #501""" s = np.array([1, np.nan],dtype=np.float64) @@ -1068,6 +1079,11 @@ class TestRegression(TestCase): assert_( a[0].tolist() == b[0]) assert_( a[1].tolist() == b[1]) + def test_nonscalar_item_method(self): + # Make sure that .item() fails graciously when it should + a = np.arange(5) + assert_raises(ValueError, a.item) + def test_char_array_creation(self, level=rlevel): a = np.array('123', dtype='c') b = np.array(asbytes_nested(['1','2','3'])) @@ -1180,10 +1196,10 @@ class TestRegression(TestCase): good = 'Maximum allowed dimension exceeded' try: np.empty(sz) - except ValueError, e: + except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) - except Exception, e: + except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_huge_arange(self): @@ -1194,10 +1210,10 @@ class TestRegression(TestCase): try: a = np.arange(sz) self.assertTrue(np.size == sz) - except ValueError, e: + except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) - except Exception, e: + except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_fromiter_bytes(self): @@ -1407,7 +1423,7 @@ class TestRegression(TestCase): c = a.astype(y) try: np.dot(b, c) - except TypeError, e: + except TypeError as e: failures.append((x, y)) if failures: raise AssertionError("Failures: %r" % failures) diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index 367b08f49..229a5f0ba 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -40,8 +40,8 @@ in-place. For example:: We wrap it using: ->>> lib.foo_func.restype = None #doctest: +SKIP ->>> lib.foo.argtypes = [array_1d_double, c_int] #doctest: +SKIP +>>> _lib.foo_func.restype = None #doctest: +SKIP +>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP Then, we're ready to call ``foo_func``: @@ -126,7 +126,7 @@ else: try: libpath = os.path.join(libdir, ln) return ctypes.cdll[libpath] - except OSError, e: + except OSError as e: exc = e raise exc diff --git a/numpy/distutils/interactive.py b/numpy/distutils/interactive.py index e3dba04eb..896a7d91e 100644 --- a/numpy/distutils/interactive.py +++ b/numpy/distutils/interactive.py @@ -87,7 +87,7 @@ def interactive_sys_argv(argv): import atexit atexit.register(readline.write_history_file, histfile) except AttributeError: pass - except Exception, msg: + except Exception as msg: print msg task_dict = {'i':show_information, @@ -178,7 +178,7 @@ def interactive_sys_argv(argv): print '-'*68 try: task_func(argv,readline) - except Exception,msg: + except Exception as msg: print 'Failed running task %s: %s' % (task,msg) break print '-'*68 diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 4f64623ed..9eed5d0f6 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -238,11 +238,11 @@ def parse_meta(config): d[name] = value for k in ['name', 'description', 'version']: - if not d.has_key(k): + if not k in d: raise FormatError("Option %s (section [meta]) is mandatory, " "but not found" % k) - if not d.has_key('requires'): + if not 'requires' in d: d['requires'] = [] return d @@ -313,7 +313,7 @@ def _read_config_imp(filenames, dirs=None): # Update var dict for variables not in 'top' config file for k, v in nvars.items(): - if not vars.has_key(k): + if not k in vars: vars[k] = v # Update sec dict @@ -328,7 +328,7 @@ def _read_config_imp(filenames, dirs=None): # FIXME: document this. If pkgname is defined in the variables section, and # there is no pkgdir variable defined, pkgdir is automatically defined to # the path of pkgname. This requires the package to be imported to work - if not vars.has_key("pkgdir") and vars.has_key("pkgname"): + if not 'pkgdir' in vars and "pkgname" in vars: pkgname = vars["pkgname"] if not pkgname in sys.modules: raise ValueError("You should import %s to get information on %s" % diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 4dd3d4b6b..38a8b25a5 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -1667,7 +1667,7 @@ class _numpy_info(system_info): ## (self.modulename.upper()+'_VERSION_HEX', ## hex(vstr2hex(module.__version__))), ## ) -## except Exception,msg: +## except Exception as msg: ## print msg dict_append(info, define_macros=macros) include_dirs = self.get_include_dirs() diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index dd8277aaf..42d506d74 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -192,7 +192,7 @@ if os.path.isfile('.f2py_f2cmap'): else: errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"%(k,k1,d[k][k1],d[k][k1],c2py_map.keys())) outmess('Succesfully applied user defined changes from .f2py_f2cmap\n') - except Exception, msg: + except Exception as msg: errmess('Failed to apply user defined changes from .f2py_f2cmap: %s. Skipping.\n' % (msg)) cformat_map={'double':'%g', 'float':'%g', diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 5d664e399..f610548d6 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -993,7 +993,7 @@ def analyzeline(m,case,line): replace(',','+1j*(') try: v = eval(initexpr,{},params) - except (SyntaxError,NameError,TypeError),msg: + except (SyntaxError,NameError,TypeError) as msg: errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n'\ % (initexpr, msg)) continue @@ -2034,7 +2034,7 @@ def get_parameters(vars, global_params={}): l = markoutercomma(v[1:-1]).split('@,@') try: params[n] = eval(v,g_params,params) - except Exception,msg: + except Exception as msg: params[n] = v #print params outmess('get_parameters: got "%s" on %s\n' % (msg,`v`)) @@ -2062,7 +2062,7 @@ def _eval_scalar(value,params): value = str(eval(value,{},params)) except (NameError, SyntaxError): return value - except Exception,msg: + except Exception as msg: errmess('"%s" in evaluating %r '\ '(available names: %s)\n' \ % (msg,value,params.keys())) @@ -2805,7 +2805,7 @@ if __name__ == "__main__": try: open(l).close() files.append(l) - except IOError,detail: + except IOError as detail: errmess('IOError: %s\n'%str(detail)) else: funcs.append(l) diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py index 3b517a5c9..e45f9950e 100644 --- a/numpy/f2py/diagnose.py +++ b/numpy/f2py/diagnose.py @@ -54,7 +54,7 @@ def run(): try: print 'Found new numpy version %r in %s' % \ (numpy.__version__, numpy.__file__) - except Exception,msg: + except Exception as msg: print 'error:', msg print '------' @@ -62,7 +62,7 @@ def run(): try: print 'Found f2py2e version %r in %s' % \ (f2py2e.__version__.version,f2py2e.__file__) - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' @@ -77,7 +77,7 @@ def run(): numpy_distutils.numpy_distutils_version.numpy_distutils_version, numpy_distutils.__file__) print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' try: @@ -91,10 +91,10 @@ def run(): for compiler_class in build_flib.all_compilers: compiler_class(verbose=1).is_available() print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg,'(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)' print '------' try: @@ -110,10 +110,10 @@ def run(): print 'Checking availability of supported Fortran compilers:' fcompiler.show_fcompilers() print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' try: @@ -128,7 +128,7 @@ def run(): from numpy_distutils.command.cpuinfo import cpuinfo print 'ok' print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg,'(ignore it)' print 'Importing numpy_distutils.cpuinfo ...', from numpy_distutils.cpuinfo import cpuinfo @@ -140,7 +140,7 @@ def run(): if name[0]=='_' and name[1]!='_' and getattr(cpu,name[1:])(): print name[1:], print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' os.chdir(_path) diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index 4e6d2587f..a5935c51b 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -235,7 +235,7 @@ def scaninputline(inputline): try: open(l).close() files.append(l) - except IOError,detail: + except IOError as detail: errmess('IOError: %s. Skipping file "%s".\n'%(str(detail),l)) elif f==-1: skipfuncs.append(l) elif f==0: onlyfuncs.append(l) diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index be85a308a..c1b927c1c 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -297,7 +297,7 @@ class _test_shared_memory: try: a = self.array([2],intent.in_.inout,self.num2seq) - except TypeError,msg: + except TypeError as msg: if not str(msg).startswith('failed to initialize intent(inout|inplace|cache) array'): raise else: @@ -313,7 +313,7 @@ class _test_shared_memory: shape = (len(self.num23seq),len(self.num23seq[0])) try: a = self.array(shape,intent.in_.inout,obj) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(inout) array'): raise else: @@ -398,7 +398,7 @@ class _test_shared_memory: try: a = self.array(shape,intent.in_.cache,obj[::-1]) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: @@ -411,7 +411,7 @@ class _test_shared_memory: shape = (len(self.num2seq),) try: a = self.array(shape,intent.in_.cache,obj) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: @@ -429,7 +429,7 @@ class _test_shared_memory: shape = (-1,3) try: a = self.array(shape,intent.cache.hide,None) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: @@ -456,7 +456,7 @@ class _test_shared_memory: shape = (-1,3) try: a = self.array(shape,intent.hide,None) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index a5816b96f..627bc0af9 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -71,7 +71,7 @@ def _memoize(func): if key not in memo: try: memo[key] = func(*a, **kw) - except Exception, e: + except Exception as e: memo[key] = e raise ret = memo[key] diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 1e508f3e5..bff582f7d 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -334,7 +334,7 @@ def read_array_header_1_0(fp): # "descr" : dtype.descr try: d = safe_eval(header) - except SyntaxError, e: + except SyntaxError as e: msg = "Cannot parse header: %r\nException: %r" raise ValueError(msg % (header, e)) if not isinstance(d, dict): @@ -356,7 +356,7 @@ def read_array_header_1_0(fp): raise ValueError(msg % (d['fortran_order'],)) try: dtype = numpy.dtype(d['descr']) - except TypeError, e: + except TypeError as e: msg = "descr is not a valid dtype descriptor: %r" raise ValueError(msg % (d['descr'],)) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 65f4ecb05..02dd0ceaf 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1381,8 +1381,10 @@ def _nanop(op, fill, a, axis=None): y = array(a, subok=True) # We only need to take care of NaN's in floating point arrays - if np.issubdtype(y.dtype, np.integer): + dt = y.dtype + if np.issubdtype(dt, np.integer) or np.issubdtype(dt, np.bool_): return op(y, axis=axis) + mask = isnan(a) # y[mask] = fill # We can't use fancy indexing here as it'll mess w/ MaskedArrays @@ -3051,7 +3053,7 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False): [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 - >>> np.percentile(a, 0.5, axis=0) + >>> np.percentile(a, 50, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.percentile(a, 50, axis=1) array([ 7., 2.]) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 852c5f6fd..15a1a559d 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -535,7 +535,9 @@ class ndindex(object): # Fixing nditer would be more work but should be done eventually, # and then this entire __new__ method can be removed. def __new__(cls, *shape): - if len(shape) == 0 or (len(shape) == 1 and len(shape[0]) == 0): + if len(shape) == 1 and isinstance(shape[0], tuple): + shape = shape[0] + if len(shape) == 0: class zero_dim_iter(object): def __init__(self): self._N = 1 diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index ed5af516f..3f8697507 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -92,7 +92,7 @@ class TestDataSourceOpen(TestCase): self.assertRaises(IOError, self.ds.open, url) try: self.ds.open(url) - except IOError, e: + except IOError as e: # Regression test for bug fixed in r4342. assert_(e.errno is None) diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index 43160ffb7..a6e65ef56 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -245,6 +245,10 @@ def test_ndindex(): x = list(np.ndindex((1, 2, 3))) assert_array_equal(x, expected) + # Test use of scalars and tuples + x = list(np.ndindex((3,))) + assert_array_equal(x, list(np.ndindex(3))) + # Make sure size argument is optional x = list(np.ndindex()) assert_equal(x, [()]) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index f8caeedb6..b7fa94448 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -151,7 +151,7 @@ class TestSavezLoad(RoundtripTest, TestCase): arr = np.random.randn(500, 500) try: np.savez(tmp, arr=arr) - except OSError, err: + except OSError as err: error_list.append(err) finally: os.remove(tmp) @@ -207,7 +207,7 @@ class TestSavezLoad(RoundtripTest, TestCase): for i in range(1, 1025): try: np.load(tmp)["data"] - except Exception, e: + except Exception as e: raise AssertionError("Failed to load data from a file: %s" % e) finally: os.remove(tmp) diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index 71400d112..270da73e3 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -218,5 +218,14 @@ class TestRegression(TestCase): data = [((((0,1), (2,3), (4,5)), ((6,7), (8,9), (10,11))),)] assert_equal(x, np.array(data, dtype=dt)) + def test_nansum_with_boolean(self): + # gh-2978 + a = np.zeros(2, dtype=np.bool) + try: + np.nansum(a) + except: + raise AssertionError() + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index dc6c16767..820e6d8f9 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -1154,11 +1154,11 @@ def safe_eval(source): walker = SafeEval() try: ast = compiler.parse(source, mode="eval") - except SyntaxError, err: + except SyntaxError as err: raise try: return walker.visit(ast) - except SyntaxError, err: + except SyntaxError as err: raise #----------------------------------------------------------------------------- diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index 623939863..cfb412882 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -63,7 +63,7 @@ class LinalgTestCase(object): try: self.do(a, b) raise AssertionError("%s should fail with empty matrices", self.__name__[5:]) - except linalg.LinAlgError, e: + except linalg.LinAlgError as e: pass def test_nonarray(self): diff --git a/numpy/ma/core.py b/numpy/ma/core.py index dbd619b80..861ca268d 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -110,7 +110,7 @@ def get_object_signature(obj): """ try: sig = formatargspec(*getargspec(obj)) - except TypeError, errmsg: + except TypeError as errmsg: sig = '' # msg = "Unable to retrieve the signature of %s '%s'\n"\ # "(Initial error message: %s)" diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 00cac2527..afeafcb68 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -1742,8 +1742,14 @@ def chebfit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 0b637f40a..2beb848ae 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -1519,8 +1519,14 @@ def hermfit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index c5abe03ca..c183a5a86 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -1515,8 +1515,14 @@ def hermefit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index 3533343b0..f0c1268bf 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -1518,8 +1518,14 @@ def lagfit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index 1216e29f4..0efd13ffa 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -1543,8 +1543,14 @@ def legfit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 324bec9c0..8d7251b19 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -1365,8 +1365,14 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None): if rcond is None : rcond = len(x)*np.finfo(x.dtype).eps - # scale the design matrix and solve the least squares equation - scl = np.sqrt((lhs*lhs).sum(1)) + # Determine the norms of the design matrix columns. + if issubclass(lhs.dtype.type, np.complexfloating): + scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1)) + else: + scl = np.sqrt(np.square(lhs).sum(1)) + scl[scl == 0] = 1 + + # Solve the least squares problem. c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) c = (c.T/scl).T diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py index 331cc17bc..95da83631 100644 --- a/numpy/polynomial/tests/test_chebyshev.py +++ b/numpy/polynomial/tests/test_chebyshev.py @@ -435,6 +435,10 @@ class TestFitting(TestCase): # wcoef2d = cheb.chebfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(cheb.chebfit(x, x, 1), [0, 1]) class TestGauss(TestCase): diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py index b5649a693..a0ef3b515 100644 --- a/numpy/polynomial/tests/test_hermite.py +++ b/numpy/polynomial/tests/test_hermite.py @@ -425,6 +425,10 @@ class TestFitting(TestCase): # wcoef2d = herm.hermfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(herm.hermfit(x, x, 1), [0, .5]) class TestGauss(TestCase): diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py index 018fe8595..f6bfe5e5e 100644 --- a/numpy/polynomial/tests/test_hermite_e.py +++ b/numpy/polynomial/tests/test_hermite_e.py @@ -422,6 +422,10 @@ class TestFitting(TestCase): # wcoef2d = herme.hermefit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(herme.hermefit(x, x, 1), [0, 1]) class TestGauss(TestCase): diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py index 14fafe37d..b6e0376a2 100644 --- a/numpy/polynomial/tests/test_laguerre.py +++ b/numpy/polynomial/tests/test_laguerre.py @@ -420,6 +420,10 @@ class TestFitting(TestCase): # wcoef2d = lag.lagfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(lag.lagfit(x, x, 1), [1, -1]) class TestGauss(TestCase): diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py index cdfaa96f1..3180db907 100644 --- a/numpy/polynomial/tests/test_legendre.py +++ b/numpy/polynomial/tests/test_legendre.py @@ -423,6 +423,10 @@ class TestFitting(TestCase): # wcoef2d = leg.legfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(leg.legfit(x, x, 1), [0, 1]) class TestGauss(TestCase): diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py index bae711cbf..bd09c07f6 100644 --- a/numpy/polynomial/tests/test_polynomial.py +++ b/numpy/polynomial/tests/test_polynomial.py @@ -440,6 +440,11 @@ class TestMisc(TestCase) : # wcoef2d = poly.polyfit(x, np.array([yw,yw]).T, 3, w=w) assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + # test scaling with complex values x points whose square + # is zero when summed. + x = [1, 1j, -1, -1j] + assert_almost_equal(poly.polyfit(x, x, 1), [0, 1]) + def test_polytrim(self) : coef = [2, -1, 1, 0] diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py index 683df7a01..f72626cf0 100644 --- a/numpy/testing/numpytest.py +++ b/numpy/testing/numpytest.py @@ -43,7 +43,7 @@ def importall(package): name = package_name+'.'+subpackage_name try: exec 'import %s as m' % (name) - except Exception, msg: + except Exception as msg: print 'Failed importing %s: %s' %(name, msg) continue importall(m) diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 16ed0f803..2d3965594 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -643,7 +643,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, names=('x', 'y')) if not cond : raise AssertionError(msg) - except ValueError, e: + except ValueError as e: import traceback efmt = traceback.format_exc() header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header) diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py index ac351191a..7bb93dd9b 100644 --- a/numpy/tests/test_ctypeslib.py +++ b/numpy/tests/test_ctypeslib.py @@ -18,7 +18,7 @@ class TestLoadLibrary(TestCase): try: cdll = load_library('multiarray', np.core.multiarray.__file__) - except ImportError, e: + except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print msg @@ -35,7 +35,7 @@ class TestLoadLibrary(TestCase): np.core.multiarray.__file__) except ImportError: print "No distutils available, skipping test." - except ImportError, e: + except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print msg |