From 607842ab59b0479c485eb6fa30778f47dccc224a Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Sat, 6 Oct 2018 22:53:53 +0200 Subject: ENH: __array_function__ support for most of numpy.core With the notable exceptions of np.einsum and np.block. xref GH12028 --- numpy/core/numeric.py | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index fed3c0a9d..c859f457b 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -28,6 +28,7 @@ if sys.version_info[0] < 3: from .multiarray import newbuffer, getbuffer from . import umath +from .overrides import array_function_dispatch from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, ERR_DEFAULT, PINF, NAN) @@ -91,6 +92,11 @@ class ComplexWarning(RuntimeWarning): pass +def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None): + return (a,) + + +@array_function_dispatch(_zeros_like_dispatcher) def zeros_like(a, dtype=None, order='K', subok=True): """ Return an array of zeros with the same shape and type as a given array. @@ -205,6 +211,11 @@ def ones(shape, dtype=None, order='C'): return a +def _ones_like_dispatcher(a, dtype=None, order=None, subok=None): + return (a,) + + +@array_function_dispatch(_ones_like_dispatcher) def ones_like(a, dtype=None, order='K', subok=True): """ Return an array of ones with the same shape and type as a given array. @@ -311,6 +322,11 @@ def full(shape, fill_value, dtype=None, order='C'): return a +def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None): + return (a,) + + +@array_function_dispatch(_full_like_dispatcher) def full_like(a, fill_value, dtype=None, order='K', subok=True): """ Return a full array with the same shape and type as a given array. @@ -368,6 +384,11 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): return res +def _count_nonzero_dispatcher(a, axis=None): + return (a,) + + +@array_function_dispatch(_count_nonzero_dispatcher) def count_nonzero(a, axis=None): """ Counts the number of non-zero values in the array ``a``. @@ -787,6 +808,11 @@ def isfortran(a): return a.flags.fnc +def _argwhere_dispatcher(a): + return (a,) + + +@array_function_dispatch(_argwhere_dispatcher) def argwhere(a): """ Find the indices of array elements that are non-zero, grouped by element. @@ -828,6 +854,11 @@ def argwhere(a): return transpose(nonzero(a)) +def _flatnonzero_dispatcher(a): + return (a,) + + +@array_function_dispatch(_flatnonzero_dispatcher) def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. @@ -879,6 +910,11 @@ def _mode_from_name(mode): return mode +def _correlate_dispatcher(a, v, mode=None): + return (a, v) + + +@array_function_dispatch(_correlate_dispatcher) def correlate(a, v, mode='valid'): """ Cross-correlation of two 1-dimensional sequences. @@ -947,6 +983,11 @@ def correlate(a, v, mode='valid'): return multiarray.correlate2(a, v, mode) +def _convolve_dispatcher(a, v, mode=None): + return (a, v) + + +@array_function_dispatch(_convolve_dispatcher) def convolve(a, v, mode='full'): """ Returns the discrete, linear convolution of two one-dimensional sequences. @@ -1046,6 +1087,11 @@ def convolve(a, v, mode='full'): return multiarray.correlate(a, v[::-1], mode) +def _outer_dispatcher(a, b, out=None): + return (a, b, out) + + +@array_function_dispatch(_outer_dispatcher) def outer(a, b, out=None): """ Compute the outer product of two vectors. @@ -1130,6 +1176,11 @@ def outer(a, b, out=None): return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) +def _tensordot_dispatcher(a, b, axes=None): + return (a, b) + + +@array_function_dispatch(_tensordot_dispatcher) def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes for arrays >= 1-D. @@ -1316,6 +1367,11 @@ def tensordot(a, b, axes=2): return res.reshape(olda + oldb) +def _roll_dispatcher(a, shift, axis=None): + return (a,) + + +@array_function_dispatch(_roll_dispatcher) def roll(a, shift, axis=None): """ Roll array elements along a given axis. @@ -1405,6 +1461,11 @@ def roll(a, shift, axis=None): return result +def _rollaxis_dispatcher(a, axis, start=None): + return (a,) + + +@array_function_dispatch(_rollaxis_dispatcher) def rollaxis(a, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. @@ -1525,6 +1586,11 @@ def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): return axis +def _moveaxis_dispatcher(a, source, destination): + return (a,) + + +@array_function_dispatch(_moveaxis_dispatcher) def moveaxis(a, source, destination): """ Move axes of an array to new positions. @@ -1601,6 +1667,11 @@ def _move_axis_to_0(a, axis): return moveaxis(a, axis, 0) +def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None): + return (a, b) + + +@array_function_dispatch(_cross_dispatcher) def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): """ Return the cross product of two (arrays of) vectors. @@ -2240,6 +2311,11 @@ def identity(n, dtype=None): return eye(n, dtype=dtype) +def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): + return (a, b) + + +@array_function_dispatch(_allclose_dispatcher) def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns True if two arrays are element-wise equal within a tolerance. @@ -2311,6 +2387,11 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): return bool(res) +def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None): + return (a, b) + + +@array_function_dispatch(_isclose_dispatcher) def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ Returns a boolean array where two arrays are element-wise equal within a @@ -2426,6 +2507,11 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): return cond[()] # Flatten 0d arrays to scalars +def _array_equal_dispatcher(a1, a2): + return (a1, a2) + + +@array_function_dispatch(_array_equal_dispatcher) def array_equal(a1, a2): """ True if two arrays have the same shape and elements, False otherwise. @@ -2468,6 +2554,11 @@ def array_equal(a1, a2): return bool(asarray(a1 == a2).all()) +def _array_equiv_dispatcher(a1, a2): + return (a1, a2) + + +@array_function_dispatch(_array_equiv_dispatcher) def array_equiv(a1, a2): """ Returns True if input arrays are shape consistent and all elements equal. -- cgit v1.2.1 From 7372f8dcc6af4446e502c0daec3199dace27e863 Mon Sep 17 00:00:00 2001 From: Pierre Glaser Date: Wed, 19 Sep 2018 17:07:25 +0200 Subject: MAINT, TST import pickle from numpy.core.numeric All imports of pickle from numpy modules are now done this way: >>> from numpy.core.numeric import pickle Also, some loops on protocol numbers are added over pickle tests that were not caught from #12090 --- numpy/core/numeric.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index fed3c0a9d..7c9e41299 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -40,7 +40,13 @@ ufunc = type(sin) newaxis = None if sys.version_info[0] >= 3: - import pickle + if sys.version_info[1] in (6, 7): + try: + import pickle5 as pickle + except ImportError: + import pickle + else: + import pickle basestring = str import builtins else: -- cgit v1.2.1 From 64a855f421d7b50dd29e5e09c69d285eddfb6d1c Mon Sep 17 00:00:00 2001 From: Pierre Glaser Date: Wed, 10 Oct 2018 14:45:20 +0200 Subject: ENH implement __reduce_ex__ for np.ndarray and pickle protocol 5 --- numpy/core/numeric.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 7c9e41299..56ac69424 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1934,6 +1934,10 @@ def fromfunction(function, shape, **kwargs): return function(*args, **kwargs) +def _frombuffer(buf, dtype, shape, order): + return frombuffer(buf, dtype=dtype).reshape(shape, order=order) + + def isscalar(num): """ Returns True if the type of `num` is a scalar type. -- cgit v1.2.1 From 8bab96faf2cb740536712e49e92e133626087018 Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Tue, 23 Oct 2018 07:53:58 -0700 Subject: MAINT: set preferred __module__ for numpy functions --- numpy/core/numeric.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 6e4e585c3..5d82bbd8d 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -6,6 +6,7 @@ try: import collections.abc as collections_abc except ImportError: import collections as collections_abc +import functools import itertools import operator import sys @@ -27,8 +28,8 @@ from .multiarray import ( if sys.version_info[0] < 3: from .multiarray import newbuffer, getbuffer +from . import overrides from . import umath -from .overrides import array_function_dispatch from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, ERR_DEFAULT, PINF, NAN) @@ -55,6 +56,10 @@ else: import __builtin__ as builtins +array_function_dispatch = functools.partial( + overrides.array_function_dispatch, module='numpy') + + def loads(*args, **kwargs): # NumPy 1.15.0, 2017-12-10 warnings.warn( -- cgit v1.2.1 From 3da7c73103d653a6e431924f6f4084224b8bb73b Mon Sep 17 00:00:00 2001 From: Travis Oliphant Date: Wed, 31 Oct 2018 16:59:58 -0500 Subject: DOC: Clarify that 0d arrays are dimension-lifted to 1d in asfortranarray and ascontiguousarray --- numpy/core/numeric.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 5d82bbd8d..bfe72ceb6 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -587,7 +587,7 @@ def asanyarray(a, dtype=None, order=None): def ascontiguousarray(a, dtype=None): """ - Return a contiguous array in memory (C order). + Return a contiguous array (ndim >= 1) in memory (C order). Parameters ---------- @@ -618,13 +618,16 @@ def ascontiguousarray(a, dtype=None): >>> x.flags['C_CONTIGUOUS'] True + Note: This function returns an array with at least one-dimension (1-d) + so it will not preserve 0-d arrays. + """ return array(a, dtype, copy=False, order='C', ndmin=1) def asfortranarray(a, dtype=None): """ - Return an array laid out in Fortran order in memory. + Return an array (ndim >= 1) laid out in Fortran order in memory. Parameters ---------- @@ -655,6 +658,9 @@ def asfortranarray(a, dtype=None): >>> y.flags['F_CONTIGUOUS'] True + Note: This function returns an array with at least one-dimension (1-d) + so it will not preserve 0-d arrays. + """ return array(a, dtype, copy=False, order='F', ndmin=1) -- cgit v1.2.1 From 7f48bb921863b2d1a64f511f0d8f05a1590b2b2a Mon Sep 17 00:00:00 2001 From: Travis Oliphant Date: Wed, 31 Oct 2018 17:02:22 -0500 Subject: DOC: remove excess indentation in Note: --- numpy/core/numeric.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index bfe72ceb6..265c3636f 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -619,7 +619,7 @@ def ascontiguousarray(a, dtype=None): True Note: This function returns an array with at least one-dimension (1-d) - so it will not preserve 0-d arrays. + so it will not preserve 0-d arrays. """ return array(a, dtype, copy=False, order='C', ndmin=1) @@ -659,7 +659,7 @@ def asfortranarray(a, dtype=None): True Note: This function returns an array with at least one-dimension (1-d) - so it will not preserve 0-d arrays. + so it will not preserve 0-d arrays. """ return array(a, dtype, copy=False, order='F', ndmin=1) -- cgit v1.2.1 From 4d24bbda32d133d51940b0691bd9b428d4198eaa Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Tue, 13 Nov 2018 09:38:07 -0800 Subject: ENH: set correct __module__ for objects in numpy's public API Fixes GH-12271 Tests verify that everything in ``dir(numpy)`` either has ``__module__`` set to ``'numpy'``, or appears in an explicit whitelist of undocumented functions and exported bulitins. These should eventually be documented or removed. I also identified a handful of functions for which I had accidentally not setup dispatch for with ``__array_function__`` before, because they were listed under "ndarray methods" in ``_add_newdocs.py``. I guess that should be a lesson in trusting code comments :). --- numpy/core/numeric.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 265c3636f..aa5be1af3 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -30,6 +30,7 @@ if sys.version_info[0] < 3: from . import overrides from . import umath +from .overrides import set_module from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, ERR_DEFAULT, PINF, NAN) @@ -92,6 +93,7 @@ if sys.version_info[0] < 3: __all__.extend(['getbuffer', 'newbuffer']) +@set_module('numpy') class ComplexWarning(RuntimeWarning): """ The warning raised when casting a complex dtype to a real dtype. @@ -170,6 +172,7 @@ def zeros_like(a, dtype=None, order='K', subok=True): return res +@set_module('numpy') def ones(shape, dtype=None, order='C'): """ Return a new array of given shape and type, filled with ones. @@ -287,6 +290,7 @@ def ones_like(a, dtype=None, order='K', subok=True): return res +@set_module('numpy') def full(shape, fill_value, dtype=None, order='C'): """ Return a new array of given shape and type, filled with `fill_value`. @@ -462,6 +466,7 @@ def count_nonzero(a, axis=None): return a_bool.sum(axis=axis, dtype=np.intp) +@set_module('numpy') def asarray(a, dtype=None, order=None): """Convert the input to an array. @@ -533,6 +538,7 @@ def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order) +@set_module('numpy') def asanyarray(a, dtype=None, order=None): """Convert the input to an ndarray, but pass ndarray subclasses through. @@ -585,6 +591,7 @@ def asanyarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order, subok=True) +@set_module('numpy') def ascontiguousarray(a, dtype=None): """ Return a contiguous array (ndim >= 1) in memory (C order). @@ -625,6 +632,7 @@ def ascontiguousarray(a, dtype=None): return array(a, dtype, copy=False, order='C', ndmin=1) +@set_module('numpy') def asfortranarray(a, dtype=None): """ Return an array (ndim >= 1) laid out in Fortran order in memory. @@ -665,6 +673,7 @@ def asfortranarray(a, dtype=None): return array(a, dtype, copy=False, order='F', ndmin=1) +@set_module('numpy') def require(a, dtype=None, requirements=None): """ Return an ndarray of the provided type that satisfies requirements. @@ -763,6 +772,7 @@ def require(a, dtype=None, requirements=None): return arr +@set_module('numpy') def isfortran(a): """ Returns True if the array is Fortran contiguous but *not* C contiguous. @@ -1889,6 +1899,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): little_endian = (sys.byteorder == 'little') +@set_module('numpy') def indices(dimensions, dtype=int): """ Return an array representing the indices of a grid. @@ -1960,6 +1971,7 @@ def indices(dimensions, dtype=int): return res +@set_module('numpy') def fromfunction(function, shape, **kwargs): """ Construct an array by executing a function over each coordinate. @@ -2020,6 +2032,7 @@ def _frombuffer(buf, dtype, shape, order): return frombuffer(buf, dtype=dtype).reshape(shape, order=order) +@set_module('numpy') def isscalar(num): """ Returns True if the type of `num` is a scalar type. @@ -2096,6 +2109,7 @@ def isscalar(num): or isinstance(num, numbers.Number)) +@set_module('numpy') def binary_repr(num, width=None): """ Return the binary representation of the input number as a string. @@ -2206,6 +2220,7 @@ def binary_repr(num, width=None): return '1' * (outwidth - binwidth) + binary +@set_module('numpy') def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. @@ -2300,6 +2315,7 @@ def _maketup(descr, val): return tuple(res) +@set_module('numpy') def identity(n, dtype=None): """ Return the identity array. @@ -2640,6 +2656,7 @@ for key in _errdict.keys(): del key +@set_module('numpy') def seterr(all=None, divide=None, over=None, under=None, invalid=None): """ Set how floating-point errors are handled. @@ -2741,6 +2758,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): return old +@set_module('numpy') def geterr(): """ Get the current way of handling floating-point errors. @@ -2792,6 +2810,7 @@ def geterr(): return res +@set_module('numpy') def setbufsize(size): """ Set the size of the buffer used in ufuncs. @@ -2816,6 +2835,7 @@ def setbufsize(size): return old +@set_module('numpy') def getbufsize(): """ Return the size of the buffer used in ufuncs. @@ -2829,6 +2849,7 @@ def getbufsize(): return umath.geterrobj()[0] +@set_module('numpy') def seterrcall(func): """ Set the floating-point error callback function or log object. @@ -2921,6 +2942,7 @@ def seterrcall(func): return old +@set_module('numpy') def geterrcall(): """ Return the current callback function used on floating-point errors. @@ -2973,6 +2995,7 @@ class _unspecified(object): _Unspecified = _unspecified() +@set_module('numpy') class errstate(object): """ errstate(**kwargs) -- cgit v1.2.1 From 09992482c93f1b9e28b7958a792e6b3b709834fa Mon Sep 17 00:00:00 2001 From: Roman Yurchak Date: Sat, 24 Nov 2018 20:59:42 +0100 Subject: Use set litterals --- numpy/core/numeric.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index aa5be1af3..85f45c795 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -745,7 +745,7 @@ def require(a, dtype=None, requirements=None): if not requirements: return asanyarray(a, dtype=dtype) else: - requirements = set(possible_flags[x.upper()] for x in requirements) + requirements = {possible_flags[x.upper()] for x in requirements} if 'E' in requirements: requirements.remove('E') @@ -754,7 +754,7 @@ def require(a, dtype=None, requirements=None): subok = True order = 'A' - if requirements >= set(['C', 'F']): + if requirements >= {'C', 'F'}: raise ValueError('Cannot specify both "C" and "F" order') elif 'F' in requirements: order = 'F' -- cgit v1.2.1 From 0ee245bc6df60b911fafe81a743ec2a68a063c20 Mon Sep 17 00:00:00 2001 From: Roman Yurchak Date: Sat, 1 Dec 2018 19:03:55 +0100 Subject: MAINT: Use list and dict comprehension when possible (#12445) * Use list comprehension * More list comprehension migration * Revert key copying in dict * A few more fixes * More reverts * Use dict comprehension * Fix dict comprehension * Address review comments * More review comments * Fix for empty unpacking of zip(* * Revert zip(* unpacking altogether * Fix dict copying * More simplifications --- numpy/core/numeric.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index aa5be1af3..0289add3b 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2650,10 +2650,7 @@ _errdict = {"ignore": ERR_IGNORE, "print": ERR_PRINT, "log": ERR_LOG} -_errdict_rev = {} -for key in _errdict.keys(): - _errdict_rev[_errdict[key]] = key -del key +_errdict_rev = {value: key for key, value in _errdict.items()} @set_module('numpy') -- cgit v1.2.1 From 250861059b106371cb232456eeccd6d9e97d8f00 Mon Sep 17 00:00:00 2001 From: Tyler Reddy Date: Wed, 14 Nov 2018 11:36:59 -0800 Subject: TST, DOC: enable refguide_check * ported the refguide_check module from SciPy for usage in NumPy docstring execution/ verification; added the refguide_check run to Azure Mac OS CI * adjusted NumPy docstrings such that refguide_check passes --- numpy/core/numeric.py | 199 ++++++++++++++++++++++++-------------------------- 1 file changed, 97 insertions(+), 102 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 8768cbe56..8a8efddf3 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -160,9 +160,9 @@ def zeros_like(a, dtype=None, order='K', subok=True): >>> y = np.arange(3, dtype=float) >>> y - array([ 0., 1., 2.]) + array([0., 1., 2.]) >>> np.zeros_like(y) - array([ 0., 0., 0.]) + array([0., 0., 0.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) @@ -205,19 +205,19 @@ def ones(shape, dtype=None, order='C'): Examples -------- >>> np.ones(5) - array([ 1., 1., 1., 1., 1.]) + array([1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) - array([[ 1.], - [ 1.]]) + array([[1.], + [1.]]) >>> s = (2,2) >>> np.ones(s) - array([[ 1., 1.], - [ 1., 1.]]) + array([[1., 1.], + [1., 1.]]) """ a = empty(shape, dtype, order) @@ -280,9 +280,9 @@ def ones_like(a, dtype=None, order='K', subok=True): >>> y = np.arange(3, dtype=float) >>> y - array([ 0., 1., 2.]) + array([0., 1., 2.]) >>> np.ones_like(y) - array([ 1., 1., 1.]) + array([1., 1., 1.]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) @@ -323,8 +323,8 @@ def full(shape, fill_value, dtype=None, order='C'): Examples -------- >>> np.full((2, 2), np.inf) - array([[ inf, inf], - [ inf, inf]]) + array([[inf, inf], + [inf, inf]]) >>> np.full((2, 2), 10) array([[10, 10], [10, 10]]) @@ -385,13 +385,13 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double) - array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) + array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double) - array([ nan, nan, nan, nan, nan, nan]) + array([nan, nan, nan, nan, nan, nan]) >>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1) - array([ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) + array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) """ res = empty_like(a, dtype=dtype, order=order, subok=subok) @@ -620,8 +620,8 @@ def ascontiguousarray(a, dtype=None): -------- >>> x = np.arange(6).reshape(2,3) >>> np.ascontiguousarray(x, dtype=np.float32) - array([[ 0., 1., 2.], - [ 3., 4., 5.]], dtype=float32) + array([[0., 1., 2.], + [3., 4., 5.]], dtype=float32) >>> x.flags['C_CONTIGUOUS'] True @@ -802,7 +802,7 @@ def isfortran(a): >>> np.isfortran(a) False - >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN') + >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F') >>> b array([[1, 2, 3], [4, 5, 6]]) @@ -987,11 +987,11 @@ def correlate(a, v, mode='valid'): Examples -------- >>> np.correlate([1, 2, 3], [0, 1, 0.5]) - array([ 3.5]) + array([3.5]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") - array([ 2. , 3.5, 3. ]) + array([2. , 3.5, 3. ]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") - array([ 0.5, 2. , 3.5, 3. , 0. ]) + array([0.5, 2. , 3.5, 3. , 0. ]) Using complex sequences: @@ -1087,20 +1087,20 @@ def convolve(a, v, mode='full'): before "sliding" the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) - array([ 0. , 1. , 2.5, 4. , 1.5]) + array([0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') - array([ 1. , 2.5, 4. ]) + array([1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') - array([ 2.5]) + array([2.5]) """ a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1) @@ -1176,11 +1176,11 @@ def outer(a, b, out=None): [-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> im - array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], - [ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], - [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], - [ 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], - [ 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) + array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], + [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], + [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], + [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], + [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> grid array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], @@ -1193,9 +1193,9 @@ def outer(a, b, out=None): >>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3]) - array([[a, aa, aaa], - [b, bb, bbb], - [c, cc, ccc]], dtype=object) + array([['a', 'aa', 'aaa'], + ['b', 'bb', 'bbb'], + ['c', 'cc', 'ccc']], dtype=object) """ a = asarray(a) @@ -1264,11 +1264,11 @@ def tensordot(a, b, axes=2): >>> c.shape (5, 2) >>> c - array([[ 4400., 4730.], - [ 4532., 4874.], - [ 4664., 5018.], - [ 4796., 5162.], - [ 4928., 5306.]]) + array([[4400., 4730.], + [4532., 4874.], + [4664., 5018.], + [4796., 5162.], + [4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): @@ -1294,40 +1294,40 @@ def tensordot(a, b, axes=2): [3, 4]], [[5, 6], [7, 8]]]) - array([[a, b], - [c, d]], dtype=object) + array([['a', 'b'], + ['c', 'd']], dtype=object) >>> np.tensordot(a, A) # third argument default is 2 for double-contraction - array([abbcccdddd, aaaaabbbbbbcccccccdddddddd], dtype=object) + array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, 1) - array([[[acc, bdd], - [aaacccc, bbbdddd]], - [[aaaaacccccc, bbbbbdddddd], - [aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object) + array([[['acc', 'bdd'], + ['aaacccc', 'bbbdddd']], + [['aaaaacccccc', 'bbbbbdddddd'], + ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object) >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.) - array([[[[[a, b], - [c, d]], + array([[[[['a', 'b'], + ['c', 'd']], ... >>> np.tensordot(a, A, (0, 1)) - array([[[abbbbb, cddddd], - [aabbbbbb, ccdddddd]], - [[aaabbbbbbb, cccddddddd], - [aaaabbbbbbbb, ccccdddddddd]]], dtype=object) + array([[['abbbbb', 'cddddd'], + ['aabbbbbb', 'ccdddddd']], + [['aaabbbbbbb', 'cccddddddd'], + ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, (2, 1)) - array([[[abb, cdd], - [aaabbbb, cccdddd]], - [[aaaaabbbbbb, cccccdddddd], - [aaaaaaabbbbbbbb, cccccccdddddddd]]], dtype=object) + array([[['abb', 'cdd'], + ['aaabbbb', 'cccdddd']], + [['aaaaabbbbbb', 'cccccdddddd'], + ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, ((0, 1), (0, 1))) - array([abbbcccccddddddd, aabbbbccccccdddddddd], dtype=object) + array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, ((2, 1), (1, 0))) - array([acccbbdddd, aaaaacccccccbbbbbbdddddddd], dtype=object) + array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object) """ try: @@ -1780,7 +1780,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): >>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y) - -3 + array(-3) Multiple vector cross-products. Note that the direction of the cross product vector is defined by the `right-hand rule`. @@ -2097,10 +2097,10 @@ def isscalar(num): NumPy supports PEP 3141 numbers: >>> from fractions import Fraction - >>> isscalar(Fraction(5, 17)) + >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number - >>> isscalar(Number()) + >>> np.isscalar(Number()) True """ @@ -2339,9 +2339,9 @@ def identity(n, dtype=None): Examples -------- >>> np.identity(3) - array([[ 1., 0., 0.], - [ 0., 1., 0.], - [ 0., 0., 1.]]) + array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) """ from numpy import eye @@ -2487,23 +2487,23 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): Examples -------- >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) - array([True, False]) + array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) - array([True, True]) + array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) - array([False, True]) + array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) - array([True, False]) + array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) - array([True, True]) + array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) - array([ True, False], dtype=bool) + array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) - array([False, False], dtype=bool) + array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) - array([ True, True], dtype=bool) + array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) - array([False, True], dtype=bool) + array([False, True]) """ def within_tol(x, y, atol, rtol): with errstate(invalid='ignore'): @@ -2710,11 +2710,9 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): -------- >>> old_settings = np.seterr(all='ignore') #seterr to known value >>> np.seterr(over='raise') - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', - 'under': 'ignore'} + {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'} >>> np.seterr(**old_settings) # reset to default - {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', - 'under': 'ignore'} + {'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'} >>> np.int16(32000) * np.int16(3) 30464 @@ -2724,11 +2722,11 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): File "", line 1, in FloatingPointError: overflow encountered in short_scalars + >>> from collections import OrderedDict >>> old_settings = np.seterr(all='print') - >>> np.geterr() - {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'} + >>> OrderedDict(np.geterr()) + OrderedDict([('divide', 'print'), ('over', 'print'), ('under', 'print'), ('invalid', 'print')]) >>> np.int16(32000) * np.int16(3) - Warning: overflow encountered in short_scalars 30464 """ @@ -2779,18 +2777,17 @@ def geterr(): Examples -------- - >>> np.geterr() - {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', - 'under': 'ignore'} + >>> from collections import OrderedDict + >>> sorted(np.geterr().items()) + [('divide', 'warn'), ('invalid', 'warn'), ('over', 'warn'), ('under', 'ignore')] >>> np.arange(3.) / np.arange(3.) - array([ NaN, 1., 1.]) + array([nan, 1., 1.]) >>> oldsettings = np.seterr(all='warn', over='raise') - >>> np.geterr() - {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + >>> OrderedDict(sorted(np.geterr().items())) + OrderedDict([('divide', 'warn'), ('invalid', 'warn'), ('over', 'raise'), ('under', 'warn')]) >>> np.arange(3.) / np.arange(3.) - __main__:1: RuntimeWarning: invalid value encountered in divide - array([ NaN, 1., 1.]) + array([nan, 1., 1.]) """ maskvalue = umath.geterrobj()[1] @@ -2897,15 +2894,16 @@ def seterrcall(func): >>> saved_handler = np.seterrcall(err_handler) >>> save_err = np.seterr(all='call') + >>> from collections import OrderedDict >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 - array([ Inf, Inf, Inf]) + array([inf, inf, inf]) >>> np.seterrcall(saved_handler) - >>> np.seterr(**save_err) - {'over': 'call', 'divide': 'call', 'invalid': 'call', 'under': 'call'} + >>> OrderedDict(sorted(np.seterr(**save_err).items())) + OrderedDict([('divide', 'call'), ('invalid', 'call'), ('over', 'call'), ('under', 'call')]) Log error message: @@ -2919,14 +2917,13 @@ def seterrcall(func): >>> save_err = np.seterr(all='log') >>> np.array([1, 2, 3]) / 0.0 - LOG: Warning: divide by zero encountered in divide - - array([ Inf, Inf, Inf]) + LOG: Warning: divide by zero encountered in true_divide + array([inf, inf, inf]) >>> np.seterrcall(saved_handler) - <__main__.Log object at 0x...> - >>> np.seterr(**save_err) - {'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'} + + >>> OrderedDict(sorted(np.seterr(**save_err).items())) + OrderedDict([('divide', 'log'), ('invalid', 'log'), ('over', 'log'), ('under', 'log')]) """ if func is not None and not isinstance(func, collections_abc.Callable): @@ -2975,7 +2972,7 @@ def geterrcall(): >>> oldhandler = np.seterrcall(err_handler) >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 - array([ Inf, Inf, Inf]) + array([inf, inf, inf]) >>> cur_handler = np.geterrcall() >>> cur_handler is err_handler @@ -3023,15 +3020,14 @@ class errstate(object): Examples -------- + >>> from collections import OrderedDict >>> olderr = np.seterr(all='ignore') # Set error handling to known state. >>> np.arange(3) / 0. - array([ NaN, Inf, Inf]) + array([nan, inf, inf]) >>> with np.errstate(divide='warn'): ... np.arange(3) / 0. - ... - __main__:2: RuntimeWarning: divide by zero encountered in divide - array([ NaN, Inf, Inf]) + array([nan, inf, inf]) >>> np.sqrt(-1) nan @@ -3043,9 +3039,8 @@ class errstate(object): Outside the context the error handling behavior has not changed: - >>> np.geterr() - {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', - 'under': 'ignore'} + >>> OrderedDict(sorted(np.geterr().items())) + OrderedDict([('divide', 'ignore'), ('invalid', 'ignore'), ('over', 'ignore'), ('under', 'ignore')]) """ # Note that we don't want to run the above doctests because they will fail -- cgit v1.2.1 From 8fe81c1a69feeeee2769fee80646bae43a94d48d Mon Sep 17 00:00:00 2001 From: Nimish Telang Date: Thu, 29 Jun 2017 15:14:03 +0100 Subject: Make errstate a ContextDecorator --- numpy/core/numeric.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 8a8efddf3..1b8f36c3e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -12,6 +12,7 @@ import operator import sys import warnings import numbers +import contextlib import numpy as np from . import multiarray @@ -2990,7 +2991,7 @@ _Unspecified = _unspecified() @set_module('numpy') -class errstate(object): +class errstate(contextlib.ContextDecorator): """ errstate(**kwargs) @@ -3000,7 +3001,12 @@ class errstate(object): that context to execute with a known error handling behavior. Upon entering the context the error handling is set with `seterr` and `seterrcall`, and upon exiting it is reset to what it was before. - + + .. versionchanged:: 1.17.0 + `errstate` is also usable as a function decorator, saving + a level of indentation if an entire function is wrapped. + See :py:class:`contextlib.ContextDecorator` for more information. + Parameters ---------- kwargs : {divide, over, under, invalid} -- cgit v1.2.1 From 60981410a6be95db211491e76190259ca41b03a0 Mon Sep 17 00:00:00 2001 From: Bharat123Rox Date: Mon, 18 Feb 2019 20:55:40 +0530 Subject: DOC: Fix numpy#12959 by including negative shifts Included examples symmetric to the existing ones in np.roll with negative shifts. --- numpy/core/numeric.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1b8f36c3e..f214eb603 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1443,7 +1443,8 @@ def roll(a, shift, axis=None): >>> x = np.arange(10) >>> np.roll(x, 2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) - + >>> np.roll(x, -2) + array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], @@ -1451,12 +1452,21 @@ def roll(a, shift, axis=None): >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) + >>> np.roll(x2, -1) + array([[1, 2, 3, 4, 5], + [6, 7, 8, 9, 0]]) >>> np.roll(x2, 1, axis=0) + array([[5, 6, 7, 8, 9], + [0, 1, 2, 3, 4]]) + >>> np.roll(x2, -1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]) + >>> np.roll(x2, -1, axis=1) + array([[1, 2, 3, 4, 0], + [6, 7, 8, 9, 5]]) """ a = asanyarray(a) -- cgit v1.2.1 From 22f61e9886411d0e58a2fdd1afc364c320b41efc Mon Sep 17 00:00:00 2001 From: Bharat123Rox Date: Mon, 18 Feb 2019 21:05:03 +0530 Subject: Restore spacing --- numpy/core/numeric.py | 1 + 1 file changed, 1 insertion(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index f214eb603..c06b0cf98 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1445,6 +1445,7 @@ def roll(a, shift, axis=None): array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) + >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], -- cgit v1.2.1 From b6dc039961768bd5f3a3d7f57e8c396f8fa02815 Mon Sep 17 00:00:00 2001 From: Charles Harris Date: Thu, 21 Feb 2019 12:49:33 -0700 Subject: MAINT: Move pickle import to numpy.compat The pickle module was being imported from numpy.core.numeric. It was defined there in order to use pickle5 when available in Python3 and cpickle in Python2. The numpy.compat module seems a better place for that. --- numpy/core/numeric.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index c06b0cf98..386049410 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -15,6 +15,7 @@ import numbers import contextlib import numpy as np +from numpy.compat import pickle, basestring from . import multiarray from .multiarray import ( _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS, @@ -44,17 +45,8 @@ ufunc = type(sin) newaxis = None if sys.version_info[0] >= 3: - if sys.version_info[1] in (6, 7): - try: - import pickle5 as pickle - except ImportError: - import pickle - else: - import pickle - basestring = str import builtins else: - import cPickle as pickle import __builtin__ as builtins -- cgit v1.2.1 From 39402815350257cab421975d31bd99a96afb3151 Mon Sep 17 00:00:00 2001 From: Daniel Lawrence Date: Sat, 2 Mar 2019 13:11:36 +0000 Subject: DOC: Removed incorrect claim regarding shape constraints for np.tensordot() --- numpy/core/numeric.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 386049410..1944ce4c7 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1203,20 +1203,18 @@ def _tensordot_dispatcher(a, b, axes=None): @array_function_dispatch(_tensordot_dispatcher) def tensordot(a, b, axes=2): """ - Compute tensor dot product along specified axes for arrays >= 1-D. + Compute tensor dot product along specified axes. - Given two tensors (arrays of dimension greater than or equal to one), - `a` and `b`, and an array_like object containing two array_like - objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s - elements (components) over the axes specified by ``a_axes`` and - ``b_axes``. The third argument can be a single non-negative - integer_like scalar, ``N``; if it is such, then the last ``N`` - dimensions of `a` and the first ``N`` dimensions of `b` are summed - over. + Given two tensors,`a` and `b`, and an array_like object containing + two array_like objects, ``(a_axes, b_axes)``, sum the products of + `a`'s and `b`'s elements (components) over the axes specified by + ``a_axes`` and ``b_axes``. The third argument can be a single non-negative + integer_like scalar, ``N``; if it is such, then the last ``N``dimensions + of `a` and the first ``N`` dimensions of `b` are summed over. Parameters ---------- - a, b : array_like, len(shape) >= 1 + a, b : array_like Tensors to "dot". axes : int or (2,) array_like -- cgit v1.2.1 From 3e8818c0f3b19d76015d1ae0478a8b50701bd4b4 Mon Sep 17 00:00:00 2001 From: Daniel Lawrence Date: Sat, 2 Mar 2019 16:12:03 +0000 Subject: Fix spacing issue in tensordot docstring --- numpy/core/numeric.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1944ce4c7..42fee4eb7 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1205,11 +1205,11 @@ def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes. - Given two tensors,`a` and `b`, and an array_like object containing + Given two tensors, `a` and `b`, and an array_like object containing two array_like objects, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and ``b_axes``. The third argument can be a single non-negative - integer_like scalar, ``N``; if it is such, then the last ``N``dimensions + integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions of `a` and the first ``N`` dimensions of `b` are summed over. Parameters -- cgit v1.2.1 From 3b8bcc33e1fb75c7fed4cc0d83fd2640da5e1e77 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sat, 13 Apr 2019 11:54:26 -0700 Subject: MAINT: Move exceptions from core._internal to core._exceptions --- numpy/core/numeric.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 42fee4eb7..b4255e733 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -38,7 +38,7 @@ from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_LOG, ERR_DEFAULT, PINF, NAN) from . import numerictypes from .numerictypes import longlong, intc, int_, float_, complex_, bool_ -from ._internal import TooHardError, AxisError +from ._exceptions import TooHardError, AxisError bitwise_not = invert ufunc = type(sin) -- cgit v1.2.1 From 82641c61b1a2d6d1b8cccce5a65f4215c94b99b2 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sat, 13 Apr 2019 17:10:35 -0700 Subject: MAINT: Move asarray helpers into their own module This is a direct move, with some tweaks to imports. This breaks a cyclic imports between `core.numeric` and `core.fromnumeric`. This doesn't affect the value of `np.core.numeric.__all__` which keeps code doing `from numpy.core.numeric import *` working. --- numpy/core/numeric.py | 315 +------------------------------------------------- 1 file changed, 6 insertions(+), 309 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index b4255e733..c15b021c2 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -39,6 +39,7 @@ from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, from . import numerictypes from .numerictypes import longlong, intc, int_, float_, complex_, bool_ from ._exceptions import TooHardError, AxisError +from ._asarray import asarray, asanyarray bitwise_not = invert ufunc = type(sin) @@ -68,10 +69,9 @@ __all__ = [ 'fromstring', 'fromfile', 'frombuffer', 'int_asbuffer', 'where', 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort', 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type', - 'result_type', 'asarray', 'asanyarray', 'ascontiguousarray', - 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', + 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', - 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'require', + 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'compare_chararrays', 'putmask', 'seterr', @@ -459,312 +459,6 @@ def count_nonzero(a, axis=None): return a_bool.sum(axis=axis, dtype=np.intp) -@set_module('numpy') -def asarray(a, dtype=None, order=None): - """Convert the input to an array. - - Parameters - ---------- - a : array_like - Input data, in any form that can be converted to an array. This - includes lists, lists of tuples, tuples, tuples of tuples, tuples - of lists and ndarrays. - dtype : data-type, optional - By default, the data-type is inferred from the input data. - order : {'C', 'F'}, optional - Whether to use row-major (C-style) or - column-major (Fortran-style) memory representation. - Defaults to 'C'. - - Returns - ------- - out : ndarray - Array interpretation of `a`. No copy is performed if the input - is already an ndarray with matching dtype and order. If `a` is a - subclass of ndarray, a base class ndarray is returned. - - See Also - -------- - asanyarray : Similar function which passes through subclasses. - ascontiguousarray : Convert input to a contiguous array. - asfarray : Convert input to a floating point ndarray. - asfortranarray : Convert input to an ndarray with column-major - memory order. - asarray_chkfinite : Similar function which checks input for NaNs and Infs. - fromiter : Create an array from an iterator. - fromfunction : Construct an array by executing a function on grid - positions. - - Examples - -------- - Convert a list into an array: - - >>> a = [1, 2] - >>> np.asarray(a) - array([1, 2]) - - Existing arrays are not copied: - - >>> a = np.array([1, 2]) - >>> np.asarray(a) is a - True - - If `dtype` is set, array is copied only if dtype does not match: - - >>> a = np.array([1, 2], dtype=np.float32) - >>> np.asarray(a, dtype=np.float32) is a - True - >>> np.asarray(a, dtype=np.float64) is a - False - - Contrary to `asanyarray`, ndarray subclasses are not passed through: - - >>> issubclass(np.recarray, np.ndarray) - True - >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) - >>> np.asarray(a) is a - False - >>> np.asanyarray(a) is a - True - - """ - return array(a, dtype, copy=False, order=order) - - -@set_module('numpy') -def asanyarray(a, dtype=None, order=None): - """Convert the input to an ndarray, but pass ndarray subclasses through. - - Parameters - ---------- - a : array_like - Input data, in any form that can be converted to an array. This - includes scalars, lists, lists of tuples, tuples, tuples of tuples, - tuples of lists, and ndarrays. - dtype : data-type, optional - By default, the data-type is inferred from the input data. - order : {'C', 'F'}, optional - Whether to use row-major (C-style) or column-major - (Fortran-style) memory representation. Defaults to 'C'. - - Returns - ------- - out : ndarray or an ndarray subclass - Array interpretation of `a`. If `a` is an ndarray or a subclass - of ndarray, it is returned as-is and no copy is performed. - - See Also - -------- - asarray : Similar function which always returns ndarrays. - ascontiguousarray : Convert input to a contiguous array. - asfarray : Convert input to a floating point ndarray. - asfortranarray : Convert input to an ndarray with column-major - memory order. - asarray_chkfinite : Similar function which checks input for NaNs and - Infs. - fromiter : Create an array from an iterator. - fromfunction : Construct an array by executing a function on grid - positions. - - Examples - -------- - Convert a list into an array: - - >>> a = [1, 2] - >>> np.asanyarray(a) - array([1, 2]) - - Instances of `ndarray` subclasses are passed through as-is: - - >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) - >>> np.asanyarray(a) is a - True - - """ - return array(a, dtype, copy=False, order=order, subok=True) - - -@set_module('numpy') -def ascontiguousarray(a, dtype=None): - """ - Return a contiguous array (ndim >= 1) in memory (C order). - - Parameters - ---------- - a : array_like - Input array. - dtype : str or dtype object, optional - Data-type of returned array. - - Returns - ------- - out : ndarray - Contiguous array of same shape and content as `a`, with type `dtype` - if specified. - - See Also - -------- - asfortranarray : Convert input to an ndarray with column-major - memory order. - require : Return an ndarray that satisfies requirements. - ndarray.flags : Information about the memory layout of the array. - - Examples - -------- - >>> x = np.arange(6).reshape(2,3) - >>> np.ascontiguousarray(x, dtype=np.float32) - array([[0., 1., 2.], - [3., 4., 5.]], dtype=float32) - >>> x.flags['C_CONTIGUOUS'] - True - - Note: This function returns an array with at least one-dimension (1-d) - so it will not preserve 0-d arrays. - - """ - return array(a, dtype, copy=False, order='C', ndmin=1) - - -@set_module('numpy') -def asfortranarray(a, dtype=None): - """ - Return an array (ndim >= 1) laid out in Fortran order in memory. - - Parameters - ---------- - a : array_like - Input array. - dtype : str or dtype object, optional - By default, the data-type is inferred from the input data. - - Returns - ------- - out : ndarray - The input `a` in Fortran, or column-major, order. - - See Also - -------- - ascontiguousarray : Convert input to a contiguous (C order) array. - asanyarray : Convert input to an ndarray with either row or - column-major memory order. - require : Return an ndarray that satisfies requirements. - ndarray.flags : Information about the memory layout of the array. - - Examples - -------- - >>> x = np.arange(6).reshape(2,3) - >>> y = np.asfortranarray(x) - >>> x.flags['F_CONTIGUOUS'] - False - >>> y.flags['F_CONTIGUOUS'] - True - - Note: This function returns an array with at least one-dimension (1-d) - so it will not preserve 0-d arrays. - - """ - return array(a, dtype, copy=False, order='F', ndmin=1) - - -@set_module('numpy') -def require(a, dtype=None, requirements=None): - """ - Return an ndarray of the provided type that satisfies requirements. - - This function is useful to be sure that an array with the correct flags - is returned for passing to compiled code (perhaps through ctypes). - - Parameters - ---------- - a : array_like - The object to be converted to a type-and-requirement-satisfying array. - dtype : data-type - The required data-type. If None preserve the current dtype. If your - application requires the data to be in native byteorder, include - a byteorder specification as a part of the dtype specification. - requirements : str or list of str - The requirements list can be any of the following - - * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array - * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array - * 'ALIGNED' ('A') - ensure a data-type aligned array - * 'WRITEABLE' ('W') - ensure a writable array - * 'OWNDATA' ('O') - ensure an array that owns its own data - * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass - - See Also - -------- - asarray : Convert input to an ndarray. - asanyarray : Convert to an ndarray, but pass through ndarray subclasses. - ascontiguousarray : Convert input to a contiguous array. - asfortranarray : Convert input to an ndarray with column-major - memory order. - ndarray.flags : Information about the memory layout of the array. - - Notes - ----- - The returned array will be guaranteed to have the listed requirements - by making a copy if needed. - - Examples - -------- - >>> x = np.arange(6).reshape(2,3) - >>> x.flags - C_CONTIGUOUS : True - F_CONTIGUOUS : False - OWNDATA : False - WRITEABLE : True - ALIGNED : True - WRITEBACKIFCOPY : False - UPDATEIFCOPY : False - - >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) - >>> y.flags - C_CONTIGUOUS : False - F_CONTIGUOUS : True - OWNDATA : True - WRITEABLE : True - ALIGNED : True - WRITEBACKIFCOPY : False - UPDATEIFCOPY : False - - """ - possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C', - 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F', - 'A': 'A', 'ALIGNED': 'A', - 'W': 'W', 'WRITEABLE': 'W', - 'O': 'O', 'OWNDATA': 'O', - 'E': 'E', 'ENSUREARRAY': 'E'} - if not requirements: - return asanyarray(a, dtype=dtype) - else: - requirements = {possible_flags[x.upper()] for x in requirements} - - if 'E' in requirements: - requirements.remove('E') - subok = False - else: - subok = True - - order = 'A' - if requirements >= {'C', 'F'}: - raise ValueError('Cannot specify both "C" and "F" order') - elif 'F' in requirements: - order = 'F' - requirements.remove('F') - elif 'C' in requirements: - order = 'C' - requirements.remove('C') - - arr = array(a, dtype=dtype, order=order, copy=False, subok=subok) - - for prop in requirements: - if not arr.flags[prop]: - arr = arr.copy(order) - break - return arr - - @set_module('numpy') def isfortran(a): """ @@ -3096,7 +2790,10 @@ from . import fromnumeric from .fromnumeric import * from . import arrayprint from .arrayprint import * +from . import _asarray +from ._asarray import * extend_all(fromnumeric) extend_all(umath) extend_all(numerictypes) extend_all(arrayprint) +extend_all(_asarray) -- cgit v1.2.1 From b87a9e2784b7e5c864ebe19708b07d7211e01e29 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sat, 13 Apr 2019 13:03:45 -0700 Subject: MAINT: Move umath error helpers into their own module This is a direct move, with some tweaks to imports. For some reason, this changed the results of running the doctests, which now reflect the actual defaults for `geterrobj`. This helps to make `core.numeric` a little shorter. This doesn't affect the value of `np.core.numeric.__all__` which keeps code doing `from numpy.core.numeric import *` working. --- numpy/core/numeric.py | 450 +------------------------------------------------- 1 file changed, 7 insertions(+), 443 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index c15b021c2..34705efc7 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,11 +1,5 @@ from __future__ import division, absolute_import, print_function -try: - # Accessing collections abstract classes from collections - # has been deprecated since Python 3.3 - import collections.abc as collections_abc -except ImportError: - import collections as collections_abc import functools import itertools import operator @@ -33,13 +27,12 @@ if sys.version_info[0] < 3: from . import overrides from . import umath from .overrides import set_module -from .umath import (multiply, invert, sin, UFUNC_BUFSIZE_DEFAULT, - ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, - ERR_LOG, ERR_DEFAULT, PINF, NAN) +from .umath import (multiply, invert, sin, PINF, NAN) from . import numerictypes from .numerictypes import longlong, intc, int_, float_, complex_, bool_ from ._exceptions import TooHardError, AxisError from ._asarray import asarray, asanyarray +from ._ufunc_config import errstate bitwise_not = invert ufunc = type(sin) @@ -74,9 +67,8 @@ __all__ = [ 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', - 'identity', 'allclose', 'compare_chararrays', 'putmask', 'seterr', - 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', - 'errstate', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', + 'identity', 'allclose', 'compare_chararrays', 'putmask', + 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', @@ -2339,437 +2331,6 @@ def array_equiv(a1, a2): return bool(asarray(a1 == a2).all()) -_errdict = {"ignore": ERR_IGNORE, - "warn": ERR_WARN, - "raise": ERR_RAISE, - "call": ERR_CALL, - "print": ERR_PRINT, - "log": ERR_LOG} - -_errdict_rev = {value: key for key, value in _errdict.items()} - - -@set_module('numpy') -def seterr(all=None, divide=None, over=None, under=None, invalid=None): - """ - Set how floating-point errors are handled. - - Note that operations on integer scalar types (such as `int16`) are - handled like floating point, and are affected by these settings. - - Parameters - ---------- - all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional - Set treatment for all types of floating-point errors at once: - - - ignore: Take no action when the exception occurs. - - warn: Print a `RuntimeWarning` (via the Python `warnings` module). - - raise: Raise a `FloatingPointError`. - - call: Call a function specified using the `seterrcall` function. - - print: Print a warning directly to ``stdout``. - - log: Record error in a Log object specified by `seterrcall`. - - The default is not to change the current behavior. - divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional - Treatment for division by zero. - over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional - Treatment for floating-point overflow. - under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional - Treatment for floating-point underflow. - invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional - Treatment for invalid floating-point operation. - - Returns - ------- - old_settings : dict - Dictionary containing the old settings. - - See also - -------- - seterrcall : Set a callback function for the 'call' mode. - geterr, geterrcall, errstate - - Notes - ----- - The floating-point exceptions are defined in the IEEE 754 standard [1]_: - - - Division by zero: infinite result obtained from finite numbers. - - Overflow: result too large to be expressed. - - Underflow: result so close to zero that some precision - was lost. - - Invalid operation: result is not an expressible number, typically - indicates that a NaN was produced. - - .. [1] https://en.wikipedia.org/wiki/IEEE_754 - - Examples - -------- - >>> old_settings = np.seterr(all='ignore') #seterr to known value - >>> np.seterr(over='raise') - {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'} - >>> np.seterr(**old_settings) # reset to default - {'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'} - - >>> np.int16(32000) * np.int16(3) - 30464 - >>> old_settings = np.seterr(all='warn', over='raise') - >>> np.int16(32000) * np.int16(3) - Traceback (most recent call last): - File "", line 1, in - FloatingPointError: overflow encountered in short_scalars - - >>> from collections import OrderedDict - >>> old_settings = np.seterr(all='print') - >>> OrderedDict(np.geterr()) - OrderedDict([('divide', 'print'), ('over', 'print'), ('under', 'print'), ('invalid', 'print')]) - >>> np.int16(32000) * np.int16(3) - 30464 - - """ - - pyvals = umath.geterrobj() - old = geterr() - - if divide is None: - divide = all or old['divide'] - if over is None: - over = all or old['over'] - if under is None: - under = all or old['under'] - if invalid is None: - invalid = all or old['invalid'] - - maskvalue = ((_errdict[divide] << SHIFT_DIVIDEBYZERO) + - (_errdict[over] << SHIFT_OVERFLOW) + - (_errdict[under] << SHIFT_UNDERFLOW) + - (_errdict[invalid] << SHIFT_INVALID)) - - pyvals[1] = maskvalue - umath.seterrobj(pyvals) - return old - - -@set_module('numpy') -def geterr(): - """ - Get the current way of handling floating-point errors. - - Returns - ------- - res : dict - A dictionary with keys "divide", "over", "under", and "invalid", - whose values are from the strings "ignore", "print", "log", "warn", - "raise", and "call". The keys represent possible floating-point - exceptions, and the values define how these exceptions are handled. - - See Also - -------- - geterrcall, seterr, seterrcall - - Notes - ----- - For complete documentation of the types of floating-point exceptions and - treatment options, see `seterr`. - - Examples - -------- - >>> from collections import OrderedDict - >>> sorted(np.geterr().items()) - [('divide', 'warn'), ('invalid', 'warn'), ('over', 'warn'), ('under', 'ignore')] - >>> np.arange(3.) / np.arange(3.) - array([nan, 1., 1.]) - - >>> oldsettings = np.seterr(all='warn', over='raise') - >>> OrderedDict(sorted(np.geterr().items())) - OrderedDict([('divide', 'warn'), ('invalid', 'warn'), ('over', 'raise'), ('under', 'warn')]) - >>> np.arange(3.) / np.arange(3.) - array([nan, 1., 1.]) - - """ - maskvalue = umath.geterrobj()[1] - mask = 7 - res = {} - val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask - res['divide'] = _errdict_rev[val] - val = (maskvalue >> SHIFT_OVERFLOW) & mask - res['over'] = _errdict_rev[val] - val = (maskvalue >> SHIFT_UNDERFLOW) & mask - res['under'] = _errdict_rev[val] - val = (maskvalue >> SHIFT_INVALID) & mask - res['invalid'] = _errdict_rev[val] - return res - - -@set_module('numpy') -def setbufsize(size): - """ - Set the size of the buffer used in ufuncs. - - Parameters - ---------- - size : int - Size of buffer. - - """ - if size > 10e6: - raise ValueError("Buffer size, %s, is too big." % size) - if size < 5: - raise ValueError("Buffer size, %s, is too small." % size) - if size % 16 != 0: - raise ValueError("Buffer size, %s, is not a multiple of 16." % size) - - pyvals = umath.geterrobj() - old = getbufsize() - pyvals[0] = size - umath.seterrobj(pyvals) - return old - - -@set_module('numpy') -def getbufsize(): - """ - Return the size of the buffer used in ufuncs. - - Returns - ------- - getbufsize : int - Size of ufunc buffer in bytes. - - """ - return umath.geterrobj()[0] - - -@set_module('numpy') -def seterrcall(func): - """ - Set the floating-point error callback function or log object. - - There are two ways to capture floating-point error messages. The first - is to set the error-handler to 'call', using `seterr`. Then, set - the function to call using this function. - - The second is to set the error-handler to 'log', using `seterr`. - Floating-point errors then trigger a call to the 'write' method of - the provided object. - - Parameters - ---------- - func : callable f(err, flag) or object with write method - Function to call upon floating-point errors ('call'-mode) or - object whose 'write' method is used to log such message ('log'-mode). - - The call function takes two arguments. The first is a string describing - the type of error (such as "divide by zero", "overflow", "underflow", - or "invalid value"), and the second is the status flag. The flag is a - byte, whose four least-significant bits indicate the type of error, one - of "divide", "over", "under", "invalid":: - - [0 0 0 0 divide over under invalid] - - In other words, ``flags = divide + 2*over + 4*under + 8*invalid``. - - If an object is provided, its write method should take one argument, - a string. - - Returns - ------- - h : callable, log instance or None - The old error handler. - - See Also - -------- - seterr, geterr, geterrcall - - Examples - -------- - Callback upon error: - - >>> def err_handler(type, flag): - ... print("Floating point error (%s), with flag %s" % (type, flag)) - ... - - >>> saved_handler = np.seterrcall(err_handler) - >>> save_err = np.seterr(all='call') - >>> from collections import OrderedDict - - >>> np.array([1, 2, 3]) / 0.0 - Floating point error (divide by zero), with flag 1 - array([inf, inf, inf]) - - >>> np.seterrcall(saved_handler) - - >>> OrderedDict(sorted(np.seterr(**save_err).items())) - OrderedDict([('divide', 'call'), ('invalid', 'call'), ('over', 'call'), ('under', 'call')]) - - Log error message: - - >>> class Log(object): - ... def write(self, msg): - ... print("LOG: %s" % msg) - ... - - >>> log = Log() - >>> saved_handler = np.seterrcall(log) - >>> save_err = np.seterr(all='log') - - >>> np.array([1, 2, 3]) / 0.0 - LOG: Warning: divide by zero encountered in true_divide - array([inf, inf, inf]) - - >>> np.seterrcall(saved_handler) - - >>> OrderedDict(sorted(np.seterr(**save_err).items())) - OrderedDict([('divide', 'log'), ('invalid', 'log'), ('over', 'log'), ('under', 'log')]) - - """ - if func is not None and not isinstance(func, collections_abc.Callable): - if not hasattr(func, 'write') or not isinstance(func.write, collections_abc.Callable): - raise ValueError("Only callable can be used as callback") - pyvals = umath.geterrobj() - old = geterrcall() - pyvals[2] = func - umath.seterrobj(pyvals) - return old - - -@set_module('numpy') -def geterrcall(): - """ - Return the current callback function used on floating-point errors. - - When the error handling for a floating-point error (one of "divide", - "over", "under", or "invalid") is set to 'call' or 'log', the function - that is called or the log instance that is written to is returned by - `geterrcall`. This function or log instance has been set with - `seterrcall`. - - Returns - ------- - errobj : callable, log instance or None - The current error handler. If no handler was set through `seterrcall`, - ``None`` is returned. - - See Also - -------- - seterrcall, seterr, geterr - - Notes - ----- - For complete documentation of the types of floating-point exceptions and - treatment options, see `seterr`. - - Examples - -------- - >>> np.geterrcall() # we did not yet set a handler, returns None - - >>> oldsettings = np.seterr(all='call') - >>> def err_handler(type, flag): - ... print("Floating point error (%s), with flag %s" % (type, flag)) - >>> oldhandler = np.seterrcall(err_handler) - >>> np.array([1, 2, 3]) / 0.0 - Floating point error (divide by zero), with flag 1 - array([inf, inf, inf]) - - >>> cur_handler = np.geterrcall() - >>> cur_handler is err_handler - True - - """ - return umath.geterrobj()[2] - - -class _unspecified(object): - pass - - -_Unspecified = _unspecified() - - -@set_module('numpy') -class errstate(contextlib.ContextDecorator): - """ - errstate(**kwargs) - - Context manager for floating-point error handling. - - Using an instance of `errstate` as a context manager allows statements in - that context to execute with a known error handling behavior. Upon entering - the context the error handling is set with `seterr` and `seterrcall`, and - upon exiting it is reset to what it was before. - - .. versionchanged:: 1.17.0 - `errstate` is also usable as a function decorator, saving - a level of indentation if an entire function is wrapped. - See :py:class:`contextlib.ContextDecorator` for more information. - - Parameters - ---------- - kwargs : {divide, over, under, invalid} - Keyword arguments. The valid keywords are the possible floating-point - exceptions. Each keyword should have a string value that defines the - treatment for the particular error. Possible values are - {'ignore', 'warn', 'raise', 'call', 'print', 'log'}. - - See Also - -------- - seterr, geterr, seterrcall, geterrcall - - Notes - ----- - For complete documentation of the types of floating-point exceptions and - treatment options, see `seterr`. - - Examples - -------- - >>> from collections import OrderedDict - >>> olderr = np.seterr(all='ignore') # Set error handling to known state. - - >>> np.arange(3) / 0. - array([nan, inf, inf]) - >>> with np.errstate(divide='warn'): - ... np.arange(3) / 0. - array([nan, inf, inf]) - - >>> np.sqrt(-1) - nan - >>> with np.errstate(invalid='raise'): - ... np.sqrt(-1) - Traceback (most recent call last): - File "", line 2, in - FloatingPointError: invalid value encountered in sqrt - - Outside the context the error handling behavior has not changed: - - >>> OrderedDict(sorted(np.geterr().items())) - OrderedDict([('divide', 'ignore'), ('invalid', 'ignore'), ('over', 'ignore'), ('under', 'ignore')]) - - """ - # Note that we don't want to run the above doctests because they will fail - # without a from __future__ import with_statement - - def __init__(self, **kwargs): - self.call = kwargs.pop('call', _Unspecified) - self.kwargs = kwargs - - def __enter__(self): - self.oldstate = seterr(**self.kwargs) - if self.call is not _Unspecified: - self.oldcall = seterrcall(self.call) - - def __exit__(self, *exc_info): - seterr(**self.oldstate) - if self.call is not _Unspecified: - seterrcall(self.oldcall) - - -def _setdef(): - defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT, None] - umath.seterrobj(defval) - - -# set the default values -_setdef() - Inf = inf = infty = Infinity = PINF nan = NaN = NAN False_ = bool_(False) @@ -2792,8 +2353,11 @@ from . import arrayprint from .arrayprint import * from . import _asarray from ._asarray import * +from . import _ufunc_config +from ._ufunc_config import * extend_all(fromnumeric) extend_all(umath) extend_all(numerictypes) extend_all(arrayprint) extend_all(_asarray) +extend_all(_ufunc_config) -- cgit v1.2.1 From 0c3d18f57c842047ae23383c2eae46a042faef5d Mon Sep 17 00:00:00 2001 From: Peter Andreas Entschev Date: Thu, 25 Apr 2019 17:38:47 +0200 Subject: ENH: Add shape to *_like() array creation (#13046) * ENH: Added shape argument to *_like() array creation functions * ENH: C backend adjustments for shape argument on *_like() * TST: Added test for shape argument in *_like() functions * ENH: Added PyArray_NewLikeArrayWithShape() This change maintains backwards compatibility, rather than passing new arguments to PyArray_NewLikeArray(). * BUG: Fix for PyArray_NewLikeArrayWithShape strides and ndim == 0 Arrays created with new shapes should not take into consideration the original array's stride, and ndim == 0 should not be a case to ignore a new shape, as the caller may request a 0d array. * REL: Updates for C-API, version 1.17.x * Add comments to cversions.txt (new PyArray_NewLikeArrayWithShape function) * Increment C_API_VERSION to 1.17 in setup_common.py * Revert "REL: Updates for C-API, version 1.17.x" This reverts commit 807f512ebeb7797ad374d845e41015948afcc708. * Revert exposing PyArray_NewLikeArrayWithShape on C-API * DOC: fix versionadded for *_like() shape argument * STY: add missing spaces in array initializers * ENH: empty_like raises ValueError This occurs when shape is defined and number of dimensions match but order is 'K'. * TST: test for exception of *_like() functions * DOC: release note for shape argument in *_like() functions * DOC: fix *_like() documentation on raises * BUG: *_like() raises for non-C/F-layout arrays * TST: change *_like() shapes to prevent NPY_RELAXED_STRIDE_DEBUG=1 failure * Move empty_like() exception to C implementation * Update *_like() ValueError documentation * Rearrange stride computation for *_like() if new shape and order='K' * Change handling of order= for *_like() - If order='K' try to keep, otherwise, order='C' is implied - Do not raise ValueError anymore * Fix *_like() tests --- numpy/core/numeric.py | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 34705efc7..4b59d730d 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -90,12 +90,12 @@ class ComplexWarning(RuntimeWarning): pass -def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None): +def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_zeros_like_dispatcher) -def zeros_like(a, dtype=None, order='K', subok=True): +def zeros_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of zeros with the same shape and type as a given array. @@ -119,6 +119,12 @@ def zeros_like(a, dtype=None, order='K', subok=True): 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. + shape : int or sequence of ints, optional. + Overrides the shape of the result. If order='K' and the number of + dimensions is unchanged, will try to keep order, otherwise, + order='C' is implied. + + .. versionadded:: 1.17.0 Returns ------- @@ -150,7 +156,7 @@ def zeros_like(a, dtype=None, order='K', subok=True): array([0., 0., 0.]) """ - res = empty_like(a, dtype=dtype, order=order, subok=subok) + res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) # needed instead of a 0 to get same result as zeros for for string dtypes z = zeros(1, dtype=res.dtype) multiarray.copyto(res, z, casting='unsafe') @@ -210,12 +216,12 @@ def ones(shape, dtype=None, order='C'): return a -def _ones_like_dispatcher(a, dtype=None, order=None, subok=None): +def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_ones_like_dispatcher) -def ones_like(a, dtype=None, order='K', subok=True): +def ones_like(a, dtype=None, order='K', subok=True, shape=None): """ Return an array of ones with the same shape and type as a given array. @@ -239,6 +245,12 @@ def ones_like(a, dtype=None, order='K', subok=True): 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. + shape : int or sequence of ints, optional. + Overrides the shape of the result. If order='K' and the number of + dimensions is unchanged, will try to keep order, otherwise, + order='C' is implied. + + .. versionadded:: 1.17.0 Returns ------- @@ -270,7 +282,7 @@ def ones_like(a, dtype=None, order='K', subok=True): array([1., 1., 1.]) """ - res = empty_like(a, dtype=dtype, order=order, subok=subok) + res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) multiarray.copyto(res, 1, casting='unsafe') return res @@ -322,12 +334,12 @@ def full(shape, fill_value, dtype=None, order='C'): return a -def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None): +def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None): return (a,) @array_function_dispatch(_full_like_dispatcher) -def full_like(a, fill_value, dtype=None, order='K', subok=True): +def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): """ Return a full array with the same shape and type as a given array. @@ -349,6 +361,12 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): 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. + shape : int or sequence of ints, optional. + Overrides the shape of the result. If order='K' and the number of + dimensions is unchanged, will try to keep order, otherwise, + order='C' is implied. + + .. versionadded:: 1.17.0 Returns ------- @@ -379,7 +397,7 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) """ - res = empty_like(a, dtype=dtype, order=order, subok=subok) + res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape) multiarray.copyto(res, fill_value, casting='unsafe') return res -- cgit v1.2.1 From 38025696d7f268b47d81e215bcf33c50ca1c98c1 Mon Sep 17 00:00:00 2001 From: Bharat123rox Date: Tue, 7 May 2019 23:45:16 +0530 Subject: Use with statement to open/close files to fix LGTM alerts --- numpy/core/numeric.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 34705efc7..c2fc8da16 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1984,7 +1984,8 @@ def load(file): "np.core.numeric.load is deprecated, use pickle.load instead", DeprecationWarning, stacklevel=2) if isinstance(file, type("")): - file = open(file, "rb") + with open(file, "rb") as file_pointer: + return pickle.load(file_pointer) return pickle.load(file) -- cgit v1.2.1 From 504b287bdf4745256044f336f17c88ddcb0175dd Mon Sep 17 00:00:00 2001 From: Alexander Blinne Date: Tue, 21 May 2019 19:02:35 +0200 Subject: ENH: Add sparse option to np.core.numeric.indices (#13506) This adds a sparse keyword-option to np.core.numeric.indices. This is inspired by the same option in the np.meshgrid function. The same functionality can in principle already be achieved by using the np.ogrid index tricks like this: def indices_sparse(dimensions): return np.ogrid[tuple(slice(0, l) for l in dimensions)] However, the implementation of ogrid is much more complicated than the simple change to np.core.numeric.indices in this PR (gh-13506). --- numpy/core/numeric.py | 59 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 45 insertions(+), 14 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index e72ab3012..55e6c1cad 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1139,7 +1139,7 @@ def roll(a, shift, axis=None): array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) - + >>> x2 = np.reshape(x, (2,5)) >>> x2 array([[0, 1, 2, 3, 4], @@ -1606,11 +1606,11 @@ little_endian = (sys.byteorder == 'little') @set_module('numpy') -def indices(dimensions, dtype=int): +def indices(dimensions, dtype=int, sparse=False): """ Return an array representing the indices of a grid. - Compute an array where the subarrays contain index values 0,1,... + Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis. Parameters @@ -1619,28 +1619,38 @@ def indices(dimensions, dtype=int): The shape of the grid. dtype : dtype, optional Data type of the result. + sparse : boolean, optional + Return a sparse representation of the grid instead of a dense + representation. Default is False. + + .. versionadded:: 1.17 Returns ------- - grid : ndarray - The array of grid indices, - ``grid.shape = (len(dimensions),) + tuple(dimensions)``. + grid : one ndarray or tuple of ndarrays + If sparse is False: + Returns one array of grid indices, + ``grid.shape = (len(dimensions),) + tuple(dimensions)``. + If sparse is True: + Returns a tuple of arrays, with + ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with + dimensions[i] in the ith place See Also -------- - mgrid, meshgrid + mgrid, ogrid, meshgrid Notes ----- - The output shape is obtained by prepending the number of dimensions - in front of the tuple of dimensions, i.e. if `dimensions` is a tuple - ``(r0, ..., rN-1)`` of length ``N``, the output shape is - ``(N,r0,...,rN-1)``. + The output shape in the dense case is obtained by prepending the number + of dimensions in front of the tuple of dimensions, i.e. if `dimensions` + is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is + ``(N, r0, ..., rN-1)``. The subarrays ``grid[k]`` contains the N-D array of indices along the ``k-th`` axis. Explicitly:: - grid[k,i0,i1,...,iN-1] = ik + grid[k, i0, i1, ..., iN-1] = ik Examples -------- @@ -1665,15 +1675,36 @@ def indices(dimensions, dtype=int): Note that it would be more straightforward in the above example to extract the required elements directly with ``x[:2, :3]``. + If sparse is set to true, the grid will be returned in a sparse + representation. + + >>> i, j = np.indices((2, 3), sparse=True) + >>> i.shape + (2, 1) + >>> j.shape + (1, 3) + >>> i # row indices + array([[0], + [1]]) + >>> j # column indices + array([[0, 1, 2]]) + """ dimensions = tuple(dimensions) N = len(dimensions) shape = (1,)*N - res = empty((N,)+dimensions, dtype=dtype) + if sparse: + res = tuple() + else: + res = empty((N,)+dimensions, dtype=dtype) for i, dim in enumerate(dimensions): - res[i] = arange(dim, dtype=dtype).reshape( + idx = arange(dim, dtype=dtype).reshape( shape[:i] + (dim,) + shape[i+1:] ) + if sparse: + res = res + (idx,) + else: + res[i] = idx return res -- cgit v1.2.1 From be9a134202e097d7d279425bdb137409084fe115 Mon Sep 17 00:00:00 2001 From: jeremycl01 Date: Sat, 25 May 2019 16:58:14 -0500 Subject: DOC: update isfortran docs with return value --- numpy/core/numeric.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 55e6c1cad..3c64f9aa1 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -472,17 +472,22 @@ def count_nonzero(a, axis=None): @set_module('numpy') def isfortran(a): """ - Returns True if the array is Fortran contiguous but *not* C contiguous. - + Check if the array is Fortran contiguous but *not* C contiguous. + This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use ``a.flags.f_contiguous`` instead. - + Parameters ---------- a : ndarray Input array. + + Returns + ------- + isfortran : bool + Returns True if the array is Fortran contiguous but *not* C contiguous. Examples -- cgit v1.2.1 From a21c6902687235c6862570d8ddeb485fab07090b Mon Sep 17 00:00:00 2001 From: jeremycl01 Date: Sat, 25 May 2019 17:12:49 -0500 Subject: DOC: fixed formatting on isfortran doc --- numpy/core/numeric.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 3c64f9aa1..0eee8d10e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -473,17 +473,17 @@ def count_nonzero(a, axis=None): def isfortran(a): """ Check if the array is Fortran contiguous but *not* C contiguous. - + This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use ``a.flags.f_contiguous`` instead. - + Parameters ---------- a : ndarray Input array. - + Returns ------- isfortran : bool -- cgit v1.2.1 From 586234d66c76c870071ad55ddb22bf39e9c647fb Mon Sep 17 00:00:00 2001 From: John Law Date: Mon, 27 May 2019 09:17:39 +0800 Subject: DOC: Add return section to linalg.matrix_rank & tensordot This patch adds two return sections to them. Also one or two minor formatting issues are resolved. Addresses #13630. --- numpy/core/numeric.py | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 0eee8d10e..ea2ef900e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -934,6 +934,11 @@ def tensordot(a, b, axes=2): Or, a list of axes to be summed over, first sequence applying to `a`, second to `b`. Both elements array_like must be of the same length. + Returns + ------- + output : ndarray + The tensor dot product of the input. + See Also -------- dot, einsum -- cgit v1.2.1 From b4c1d4f93d2ed34bc27b59ece2f26a8b3b16e5e4 Mon Sep 17 00:00:00 2001 From: Antoine Dechaume Date: Fri, 2 Aug 2019 22:45:16 +0200 Subject: DOC: Fix misleading `allclose` docstring for `equal_nan` (gh-14183) There is no output array for allclose as opposed to isclose, so do not reference one. --- numpy/core/numeric.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index ea2ef900e..ff8c58867 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2124,7 +2124,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): The absolute tolerance parameter (see Notes). equal_nan : bool Whether to compare NaN's as equal. If True, NaN's in `a` will be - considered equal to NaN's in `b` in the output array. + considered equal to NaN's in `b`. .. versionadded:: 1.10.0 -- cgit v1.2.1 From dd9051c78476be2bc2cbf03ab895e8dde5ca14ca Mon Sep 17 00:00:00 2001 From: Warren Weckesser Date: Sun, 18 Aug 2019 12:07:55 -0400 Subject: BUG: core: Handle large negative np.int64 args in binary_repr. To avoid the cast to floating point that can occur when the first argument to binary_repr is a NumPy integer, the argument is converted to a Python integer at the beginning of the function. Closes gh-14289. --- numpy/core/numeric.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index ff8c58867..bbcd58abb 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1935,6 +1935,10 @@ def binary_repr(num, width=None): "will raise an error in the future.", DeprecationWarning, stacklevel=3) + # Ensure that num is a Python integer to avoid overflow or unwanted + # casts to floating point. + num = operator.index(num) + if num == 0: return '0' * (width or 1) -- cgit v1.2.1 From f9673c329cf1712bb5e28e1d14260da55a1383a9 Mon Sep 17 00:00:00 2001 From: kritisingh1 Date: Mon, 12 Aug 2019 14:13:18 +0530 Subject: DEP: Deprecate load/dump functions in favour of pickle methods --- numpy/core/numeric.py | 34 +--------------------------------- 1 file changed, 1 insertion(+), 33 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index ff8c58867..ce78463b5 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -48,14 +48,6 @@ array_function_dispatch = functools.partial( overrides.array_function_dispatch, module='numpy') -def loads(*args, **kwargs): - # NumPy 1.15.0, 2017-12-10 - warnings.warn( - "np.core.numeric.loads is deprecated, use pickle.loads instead", - DeprecationWarning, stacklevel=2) - return pickle.loads(*args, **kwargs) - - __all__ = [ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', @@ -66,7 +58,7 @@ __all__ = [ 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', - 'isclose', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', + 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'compare_chararrays', 'putmask', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', @@ -2024,30 +2016,6 @@ def base_repr(number, base=2, padding=0): return ''.join(reversed(res or '0')) -def load(file): - """ - Wrapper around cPickle.load which accepts either a file-like object or - a filename. - - Note that the NumPy binary format is not based on pickle/cPickle anymore. - For details on the preferred way of loading and saving files, see `load` - and `save`. - - See Also - -------- - load, save - - """ - # NumPy 1.15.0, 2017-12-10 - warnings.warn( - "np.core.numeric.load is deprecated, use pickle.load instead", - DeprecationWarning, stacklevel=2) - if isinstance(file, type("")): - with open(file, "rb") as file_pointer: - return pickle.load(file_pointer) - return pickle.load(file) - - # These are all essentially abbreviations # These might wind up in a special abbreviations module -- cgit v1.2.1 From b6a3ee3b7a961cfc7bcf8740c2bc89153c07f6b2 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Thu, 23 May 2019 06:41:18 -0700 Subject: ENH: Always produce a consistent shape in the result of `argwhere` Previously this would return 1d indices even though the array is zero-d. Note that using atleast1d inside numeric required an import change to avoid a circular import. --- numpy/core/numeric.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 8ada87b9f..c395b1348 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -26,6 +26,7 @@ if sys.version_info[0] < 3: from . import overrides from . import umath +from . import shape_base from .overrides import set_module from .umath import (multiply, invert, sin, PINF, NAN) from . import numerictypes @@ -545,8 +546,10 @@ def argwhere(a): Returns ------- - index_array : ndarray + index_array : (N, a.ndim) ndarray Indices of elements that are non-zero. Indices are grouped by element. + This array will have shape ``(N, a.ndim)`` where ``N`` is the number of + non-zero items. See Also -------- @@ -554,7 +557,8 @@ def argwhere(a): Notes ----- - ``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``. + ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``, + but produces a result of the correct shape for a 0D array. The output of ``argwhere`` is not suitable for indexing arrays. For this purpose use ``nonzero(a)`` instead. @@ -572,6 +576,11 @@ def argwhere(a): [1, 2]]) """ + # nonzero does not behave well on 0d, so promote to 1d + if np.ndim(a) == 0: + a = shape_base.atleast_1d(a) + # then remove the added dimension + return argwhere(a)[:,:0] return transpose(nonzero(a)) -- cgit v1.2.1 From 61774458477d0761ddd76aaf84f4b063c7e57029 Mon Sep 17 00:00:00 2001 From: Seth Troisi Date: Wed, 25 Sep 2019 19:02:05 -0700 Subject: DEP: Complete deprecation of invalid array order Fixed order=FORTRAN in docs Added release snippet --- numpy/core/numeric.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index c395b1348..6d25f864b 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -523,7 +523,7 @@ def isfortran(a): C-ordered arrays evaluate as False even if they are also FORTRAN-ordered. - >>> np.isfortran(np.array([1, 2], order='FORTRAN')) + >>> np.isfortran(np.array([1, 2], order='F')) False """ @@ -938,7 +938,7 @@ def tensordot(a, b, axes=2): Returns ------- output : ndarray - The tensor dot product of the input. + The tensor dot product of the input. See Also -------- -- cgit v1.2.1