From 4feb97e66000b17baa15b8486a7c1f9608865e78 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 26 Mar 2017 10:22:21 +0100 Subject: MAINT: have _validate_axis delegate to normalize_axis_index They were only separate before due to a requirement of a better error message --- numpy/core/numeric.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 01dd46c3c..eabf7962a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -441,7 +441,7 @@ def count_nonzero(a, axis=None): nullstr = a.dtype.type('') return (a != nullstr).sum(axis=axis, dtype=np.intp) - axis = asarray(_validate_axis(axis, a.ndim, 'axis')) + axis = asarray(_validate_axis(axis, a.ndim)) counts = np.apply_along_axis(multiarray.count_nonzero, axis[0], a) if axis.size == 1: @@ -1544,17 +1544,17 @@ def rollaxis(a, axis, start=0): return a.transpose(axes) -def _validate_axis(axis, ndim, argname): +def _validate_axis(axis, ndim, argname=None): try: axis = [operator.index(axis)] except TypeError: axis = list(axis) - axis = [a + ndim if a < 0 else a for a in axis] - if not builtins.all(0 <= a < ndim for a in axis): - raise AxisError('invalid axis for this array in `%s` argument' % - argname) + axis = [normalize_axis_index(ax, ndim, argname) for ax in axis] if len(set(axis)) != len(axis): - raise ValueError('repeated axis in `%s` argument' % argname) + if argname: + raise ValueError('repeated axis in `%s` argument' % argname) + else: + raise ValueError('repeated axis') return axis -- cgit v1.2.1 From 09d4d35bb979dd0d5d0781946f59f362765eca66 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 26 Mar 2017 10:23:53 +0100 Subject: MAINT: Use normalize_axis_index in cross Previously we did not, as this wouldn't say which axis argument was the cause of the problem. --- numpy/core/numeric.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index eabf7962a..e1352ee6c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1752,11 +1752,9 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): a = asarray(a) b = asarray(b) # Check axisa and axisb are within bounds - axis_msg = "'axis{0}' out of bounds" - if axisa < -a.ndim or axisa >= a.ndim: - raise ValueError(axis_msg.format('a')) - if axisb < -b.ndim or axisb >= b.ndim: - raise ValueError(axis_msg.format('b')) + axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa') + axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') + # Move working axis to the end of the shape a = rollaxis(a, axisa, a.ndim) b = rollaxis(b, axisb, b.ndim) @@ -1770,8 +1768,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): if a.shape[-1] == 3 or b.shape[-1] == 3: shape += (3,) # Check axisc is within bounds - if axisc < -len(shape) or axisc >= len(shape): - raise ValueError(axis_msg.format('c')) + axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc') dtype = promote_types(a.dtype, b.dtype) cp = empty(shape, dtype) -- cgit v1.2.1 From b6850e9c00055666fe9bd5f984750743ffcb85d2 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 26 Mar 2017 10:50:54 +0100 Subject: MAINT: use normalize_axis_index in np.roll Interestingly np.roll allows axes to be repeated. --- numpy/core/numeric.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index e1352ee6c..afa10747c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1460,16 +1460,14 @@ def roll(a, shift, axis=None): return roll(a.ravel(), shift, 0).reshape(a.shape) else: + axis = _validate_axis(axis, a.ndim, allow_duplicate=True) broadcasted = broadcast(shift, axis) if broadcasted.ndim > 1: raise ValueError( "'shift' and 'axis' should be scalars or 1D sequences") shifts = {ax: 0 for ax in range(a.ndim)} for sh, ax in broadcasted: - if -a.ndim <= ax < a.ndim: - shifts[ax % a.ndim] += sh - else: - raise ValueError("'axis' entry is out of bounds") + shifts[ax] += sh rolls = [((slice(None), slice(None)),)] * a.ndim for ax, offset in shifts.items(): @@ -1544,13 +1542,13 @@ def rollaxis(a, axis, start=0): return a.transpose(axes) -def _validate_axis(axis, ndim, argname=None): +def _validate_axis(axis, ndim, argname=None, allow_duplicate=False): try: axis = [operator.index(axis)] except TypeError: axis = list(axis) axis = [normalize_axis_index(ax, ndim, argname) for ax in axis] - if len(set(axis)) != len(axis): + if not allow_duplicate and len(set(axis)) != len(axis): if argname: raise ValueError('repeated axis in `%s` argument' % argname) else: -- cgit v1.2.1 From 17466ad1839718c091c629bb647e881b7922a148 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 26 Mar 2017 11:30:23 +0100 Subject: MAINT: Rename _validate_axis, and document it --- numpy/core/numeric.py | 58 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 8 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index afa10747c..632266310 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -441,7 +441,7 @@ def count_nonzero(a, axis=None): nullstr = a.dtype.type('') return (a != nullstr).sum(axis=axis, dtype=np.intp) - axis = asarray(_validate_axis(axis, a.ndim)) + axis = asarray(normalize_axis_tuple(axis, a.ndim)) counts = np.apply_along_axis(multiarray.count_nonzero, axis[0], a) if axis.size == 1: @@ -1460,7 +1460,7 @@ def roll(a, shift, axis=None): return roll(a.ravel(), shift, 0).reshape(a.shape) else: - axis = _validate_axis(axis, a.ndim, allow_duplicate=True) + axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True) broadcasted = broadcast(shift, axis) if broadcasted.ndim > 1: raise ValueError( @@ -1542,15 +1542,57 @@ def rollaxis(a, axis, start=0): return a.transpose(axes) -def _validate_axis(axis, ndim, argname=None, allow_duplicate=False): +def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): + """ + Normalizes an axis argument into a tuple of non-negative integer axes. + + This handles shorthands such as ``1`` and converts them to ``(1,)``, + as well as performing the handling of negative indices covered by + `normalize_axis_index`. + + By default, this forbids axes from being specified multiple times. + + Used internally by multi-axis-checking logic. + + .. versionadded:: 1.13.0 + + Parameters + ---------- + axis : int, iterable of int + The un-normalized index or indices of the axis. + ndim : int + The number of dimensions of the array that `axis` should be normalized + against. + argname : str, optional + A prefix to put before the error message, typically the name of the + argument. + allow_duplicate : bool, optional + If False, the default, disallow an axis from being specified twice. + + Returns + ------- + normalized_axes : tuple of int + The normalized axis index, such that `0 <= normalized_axis < ndim` + + Raises + ------ + AxisError + If any axis provided is out of range + ValueError + If an axis is repeated + + See also + -------- + normalize_axis_index : normalizing a single scalar axis + """ try: axis = [operator.index(axis)] except TypeError: - axis = list(axis) - axis = [normalize_axis_index(ax, ndim, argname) for ax in axis] + axis = tuple(axis) + axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis) if not allow_duplicate and len(set(axis)) != len(axis): if argname: - raise ValueError('repeated axis in `%s` argument' % argname) + raise ValueError('repeated axis in `{}` argument'.format(argname)) else: raise ValueError('repeated axis') return axis @@ -1612,8 +1654,8 @@ def moveaxis(a, source, destination): a = asarray(a) transpose = a.transpose - source = _validate_axis(source, a.ndim, 'source') - destination = _validate_axis(destination, a.ndim, 'destination') + source = normalize_axis_tuple(source, a.ndim, 'source') + destination = normalize_axis_tuple(destination, a.ndim, 'destination') if len(source) != len(destination): raise ValueError('`source` and `destination` arguments must have ' 'the same number of elements') -- cgit v1.2.1 From 8427866e4fb038f8d3af317e04a9cc9808bea8ca Mon Sep 17 00:00:00 2001 From: Stefan Peterson Date: Tue, 4 Apr 2017 10:58:20 +0200 Subject: DOC: Fix for issues #7622 and #7914 --- 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 632266310..c89b4097a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2145,8 +2145,8 @@ def fromfunction(function, shape, **kwargs): The function is called with N parameters, where N is the rank of `shape`. Each parameter represents the coordinates of the array varying along a specific axis. For example, if `shape` - were ``(2, 2)``, then the parameters in turn be (0, 0), (0, 1), - (1, 0), (1, 1). + were ``(2, 2)``, then the parameters would be + ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])`` shape : (N,) tuple of ints Shape of the output array, which also determines the shape of the coordinate arrays passed to `function`. -- cgit v1.2.1 From 0c4f621ad18ce4fbf6740943de59c4e2d5c7841c Mon Sep 17 00:00:00 2001 From: Juan Nunez-Iglesias Date: Sun, 9 Apr 2017 12:41:28 +1000 Subject: DOC: Replace reference to np.swapaxis with np.swapaxes (#8914) DOC: Replace reference to np.swapaxis with np.swapaxes The former function does not exist. --- 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 c89b4097a..2c0205175 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1639,7 +1639,7 @@ def moveaxis(a, source, destination): >>> np.transpose(x).shape (5, 4, 3) - >>> np.swapaxis(x, 0, -1).shape + >>> np.swapaxes(x, 0, -1).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1], [-1, -2]).shape (5, 4, 3) -- cgit v1.2.1 From f81a7a34dbd4aa95e904e52a4e8ecf61ae301241 Mon Sep 17 00:00:00 2001 From: Mads Ohm Larsen Date: Wed, 19 Apr 2017 11:48:17 +0200 Subject: DEP: Remove alter/restore dot methods --- numpy/core/numeric.py | 58 +-------------------------------------------------- 1 file changed, 1 insertion(+), 57 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 2c0205175..6b4a93ce0 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -53,7 +53,7 @@ __all__ = [ 'min_scalar_type', 'result_type', 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'ones_like', 'correlate', 'convolve', 'inner', 'dot', - 'outer', 'vdot', 'alterdot', 'restoredot', 'roll', + 'outer', 'vdot', 'roll', 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', 'fromiter', @@ -1154,62 +1154,6 @@ def outer(a, b, out=None): return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out) -def alterdot(): - """ - Change `dot`, `vdot`, and `inner` to use accelerated BLAS functions. - - Typically, as a user of NumPy, you do not explicitly call this - function. If NumPy is built with an accelerated BLAS, this function is - automatically called when NumPy is imported. - - When NumPy is built with an accelerated BLAS like ATLAS, these - functions are replaced to make use of the faster implementations. The - faster implementations only affect float32, float64, complex64, and - complex128 arrays. Furthermore, the BLAS API only includes - matrix-matrix, matrix-vector, and vector-vector products. Products of - arrays with larger dimensionalities use the built in functions and are - not accelerated. - - .. note:: Deprecated in NumPy 1.10.0 - The cblas functions have been integrated into the multarray - module and alterdot now longer does anything. It will be - removed in NumPy 1.11.0. - - See Also - -------- - restoredot : `restoredot` undoes the effects of `alterdot`. - - """ - # 2014-08-13, 1.10 - warnings.warn("alterdot no longer does anything.", - DeprecationWarning, stacklevel=2) - - -def restoredot(): - """ - Restore `dot`, `vdot`, and `innerproduct` to the default non-BLAS - implementations. - - Typically, the user will only need to call this when troubleshooting - and installation problem, reproducing the conditions of a build without - an accelerated BLAS, or when being very careful about benchmarking - linear algebra operations. - - .. note:: Deprecated in NumPy 1.10.0 - The cblas functions have been integrated into the multarray - module and restoredot now longer does anything. It will be - removed in NumPy 1.11.0. - - See Also - -------- - alterdot : `restoredot` undoes the effects of `alterdot`. - - """ - # 2014-08-13, 1.10 - warnings.warn("restoredot no longer does anything.", - DeprecationWarning, stacklevel=2) - - def tensordot(a, b, axes=2): """ Compute tensor dot product along specified axes for arrays >= 1-D. -- cgit v1.2.1 From d2b06fe879f5b2b14de3dad0f517561a0c815df0 Mon Sep 17 00:00:00 2001 From: Allan Haldane Date: Mon, 24 Apr 2017 19:38:59 -0400 Subject: ENH: str/repr fixed for 0d-arrays 0d arrays now use the arrayprint.py formatters to print themselves. Deprecates 'style' argument to array2string. Integer scalars are no longer printed using the function set with ``np.set_print_function``. --- 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 6b4a93ce0..1dde02400 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1936,7 +1936,7 @@ def array_str(a, max_line_width=None, precision=None, suppress_small=None): '[0 1 2]' """ - return array2string(a, max_line_width, precision, suppress_small, ' ', "", str) + return array2string(a, max_line_width, precision, suppress_small, ' ', "") def set_string_function(f, repr=True): -- cgit v1.2.1 From cbaa809820656bf39f4ec78a9bec1426239ce440 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sat, 3 Jun 2017 13:23:46 +0100 Subject: MAINT: Don't internally use the one-argument where nonzero is a clearer spelling --- 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 1dde02400..da9e83a1c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -838,7 +838,7 @@ def argwhere(a): ``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``. The output of ``argwhere`` is not suitable for indexing arrays. - For this purpose use ``where(a)`` instead. + For this purpose use ``nonzero(a)`` instead. Examples -------- -- cgit v1.2.1 From 1608e53072b035bd40de7a202e75354f0e802120 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sat, 3 Jun 2017 13:41:26 +0100 Subject: BUG: KeyboardInterrupt is swallowed all over the place Bare except is very rarely the right thing --- numpy/core/numeric.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1dde02400..9073ca5ff 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1278,7 +1278,7 @@ def tensordot(a, b, axes=2): """ try: iter(axes) - except: + except Exception: axes_a = list(range(-axes, 0)) axes_b = list(range(0, axes)) else: @@ -2597,7 +2597,7 @@ def array_equal(a1, a2): """ try: a1, a2 = asarray(a1), asarray(a2) - except: + except Exception: return False if a1.shape != a2.shape: return False @@ -2641,11 +2641,11 @@ def array_equiv(a1, a2): """ try: a1, a2 = asarray(a1), asarray(a2) - except: + except Exception: return False try: multiarray.broadcast(a1, a2) - except: + except Exception: return False return bool(asarray(a1 == a2).all()) -- cgit v1.2.1 From 0975f34260422f81211eb9087f4712598aaa5118 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 4 Jun 2017 12:28:14 +0100 Subject: DOC: Link to ufunc.outer from np.outer [ci skip] --- numpy/core/numeric.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 83f2ce838..013c8a92a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1106,7 +1106,10 @@ def outer(a, b, out=None): See also -------- - inner, einsum + inner + einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent. + ufunc.outer : A generalization to N dimensions and other operations. + ``np.multiply.outer(a.ravel(), b.ravel())`` is the equivalent. References ---------- -- cgit v1.2.1 From 4f8d9523ef29267932c933bd7e06b0a4e59b1df0 Mon Sep 17 00:00:00 2001 From: Pim de Haan Date: Sat, 10 Jun 2017 18:57:04 +0200 Subject: ENH: Make 0-length dim handling of tensordot consistent with dot/einsum --- numpy/core/numeric.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 013c8a92a..f8ca49429 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -22,9 +22,9 @@ if sys.version_info[0] < 3: from .multiarray import newbuffer, getbuffer from . import umath -from .umath import (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, UFUNC_BUFSIZE_DEFAULT, + ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, + ERR_LOG, ERR_DEFAULT, PINF, NAN) from . import numerictypes from .numerictypes import longlong, intc, int_, float_, complex_, bool_ from ._internal import TooHardError, AxisError @@ -1326,7 +1326,7 @@ def tensordot(a, b, axes=2): N2 = 1 for axis in axes_a: N2 *= as_[axis] - newshape_a = (-1, N2) + newshape_a = (multiply.reduce([as_[ax] for ax in notin]), N2) olda = [as_[axis] for axis in notin] notin = [k for k in range(ndb) if k not in axes_b] @@ -1334,7 +1334,7 @@ def tensordot(a, b, axes=2): N2 = 1 for axis in axes_b: N2 *= bs[axis] - newshape_b = (N2, -1) + newshape_b = (N2, multiply.reduce([bs[ax] for ax in notin])) oldb = [bs[axis] for axis in notin] at = a.transpose(newaxes_a).reshape(newshape_a) -- cgit v1.2.1 From e3b5e88ae6c0b546dd63b869f32427553ad36e57 Mon Sep 17 00:00:00 2001 From: Daniel Smith Date: Tue, 18 Jul 2017 10:35:51 -0400 Subject: ENH: Einsum calls BLAS if it advantageous to do so (#9425) * Einsum now optionally uses BLAS * The einsum call is now optimized by default * cleans up the dot logic * MAINT: Correct spelling, tranpose <- transpose. --- 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 f8ca49429..b535cf846 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1326,7 +1326,7 @@ def tensordot(a, b, axes=2): N2 = 1 for axis in axes_a: N2 *= as_[axis] - newshape_a = (multiply.reduce([as_[ax] for ax in notin]), N2) + newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2) olda = [as_[axis] for axis in notin] notin = [k for k in range(ndb) if k not in axes_b] @@ -1334,7 +1334,7 @@ def tensordot(a, b, axes=2): N2 = 1 for axis in axes_b: N2 *= bs[axis] - newshape_b = (N2, multiply.reduce([bs[ax] for ax in notin])) + newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin]))) oldb = [bs[axis] for axis in notin] at = a.transpose(newaxes_a).reshape(newshape_a) -- cgit v1.2.1 From 622fde5cb586dbcf101aceda882a7b98d91f7e1b Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Sun, 30 Jul 2017 21:17:20 -0700 Subject: DOC: fix versionadded in docstring for moveaxis --- 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 b535cf846..02f9be3a9 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1551,7 +1551,7 @@ def moveaxis(a, source, destination): Other axes remain in their original order. - .. versionadded::1.11.0 + .. versionadded:: 1.11.0 Parameters ---------- -- cgit v1.2.1 From 2b781f8967488dc007f8f0a1e6a7f49208788d12 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 1 Aug 2017 20:29:36 +0000 Subject: MAINT/DOC: Use builtin when np.{x} is builtins.{x}. This is the case for x in {int, bool, str, float, complex, object}. Using the np.{x} version is deceptive as it suggests that there is a difference. This change doesn't affect any external behaviour. The `long` type is missing in python 3, so np.long is still useful --- numpy/core/numeric.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 02f9be3a9..13a99505c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -133,7 +133,7 @@ def zeros_like(a, dtype=None, order='K', subok=True): array([[0, 0, 0], [0, 0, 0]]) - >>> y = np.arange(3, dtype=np.float) + >>> y = np.arange(3, dtype=float) >>> y array([ 0., 1., 2.]) >>> np.zeros_like(y) @@ -176,7 +176,7 @@ def ones(shape, dtype=None, order='C'): >>> np.ones(5) array([ 1., 1., 1., 1., 1.]) - >>> np.ones((5,), dtype=np.int) + >>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) @@ -243,7 +243,7 @@ def ones_like(a, dtype=None, order='K', subok=True): array([[1, 1, 1], [1, 1, 1]]) - >>> y = np.arange(3, dtype=np.float) + >>> y = np.arange(3, dtype=float) >>> y array([ 0., 1., 2.]) >>> np.ones_like(y) @@ -344,7 +344,7 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): Examples -------- - >>> x = np.arange(6, dtype=np.int) + >>> x = np.arange(6, dtype=int) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) -- cgit v1.2.1 From 0ab1a2b12baabe3bd7063e2963c83482a4f57016 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 1 Aug 2017 17:41:28 +0000 Subject: MAINT: Simplify test for string-likes --- numpy/core/numeric.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 13a99505c..7d53f2b68 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -436,8 +436,7 @@ def count_nonzero(a, axis=None): if issubdtype(a.dtype, np.number): return (a != 0).sum(axis=axis, dtype=np.intp) - if (issubdtype(a.dtype, np.string_) or - issubdtype(a.dtype, np.unicode_)): + if issubdtype(a.dtype, np.character): nullstr = a.dtype.type('') return (a != nullstr).sum(axis=axis, dtype=np.intp) -- cgit v1.2.1 From 029863eae86b9df2de4b9a9843ca8f88c99130df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nico=20Schl=C3=B6mer?= Date: Fri, 11 Aug 2017 03:01:06 +0200 Subject: MAINT: Use moveaxis instead of rollaxis internally (#9475) Also add a hint to the documentation advising the use of moveaxis over rollaxis. Tests for rollaxis are left alone. --- numpy/core/numeric.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 7d53f2b68..e9bb39ad4 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1435,6 +1435,10 @@ def rollaxis(a, axis, start=0): """ Roll the specified axis backwards, until it lies in a given position. + This function continues to be supported for backward compatibility, but you + should prefer `moveaxis`. The `moveaxis` function was added in NumPy + 1.11. + Parameters ---------- a : ndarray @@ -1617,7 +1621,7 @@ def moveaxis(a, source, destination): # fix hack in scipy which imports this function def _move_axis_to_0(a, axis): - return rollaxis(a, axis, 0) + return moveaxis(a, axis, 0) def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): @@ -1742,8 +1746,8 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb') # Move working axis to the end of the shape - a = rollaxis(a, axisa, a.ndim) - b = rollaxis(b, axisb, b.ndim) + a = moveaxis(a, axisa, -1) + b = moveaxis(b, axisb, -1) msg = ("incompatible dimensions for cross product\n" "(dimension must be 2 or 3)") if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3): @@ -1814,8 +1818,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): multiply(a0, b1, out=cp2) cp2 -= a1 * b0 - # This works because we are moving the last axis - return rollaxis(cp, -1, axisc) + return moveaxis(cp, -1, axisc) # Use numarray's printing function -- cgit v1.2.1 From ae17d2c93dfac88cca9859d8b49490deb3991f41 Mon Sep 17 00:00:00 2001 From: Christoph Boeddeker Date: Sun, 13 Aug 2017 22:58:30 +0200 Subject: DOC: add example for isscalar on strings (#9361) --- numpy/core/numeric.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index e9bb39ad4..ed350de7f 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2159,6 +2159,8 @@ def isscalar(num): False >>> np.isscalar(False) True + >>> np.isscalar('numpy') + True """ if isinstance(num, generic): -- cgit v1.2.1 From 09257ce4dba8abf375c0d37278e842bd5dccda2d Mon Sep 17 00:00:00 2001 From: Julian Taylor Date: Fri, 1 Sep 2017 13:40:07 +0200 Subject: BUG: ensure consistent result dtype of count_nonzero The slowpath using apply_along_axis for size 1 axis did not ensure that the dtype is intp like all other paths. This caused inconsistent dtypes on windows where the default integer type is int32. Closes gh-9468 --- 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 6b4a93ce0..6b1c6e86e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -445,7 +445,7 @@ def count_nonzero(a, axis=None): counts = np.apply_along_axis(multiarray.count_nonzero, axis[0], a) if axis.size == 1: - return counts + return counts.astype(np.intp, copy=False) else: # for subsequent axis numbers, that number decreases # by one in this new 'counts' array if it was larger -- cgit v1.2.1 From cd76e630972c67364dfb12f2fc264becd8e40d12 Mon Sep 17 00:00:00 2001 From: Jeroen Demeyer Date: Fri, 15 Sep 2017 12:22:51 +0200 Subject: PEP 3141 numbers should be considered scalars --- numpy/core/numeric.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index fde08490a..282fcbad0 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -5,6 +5,7 @@ import itertools import operator import sys import warnings +import numbers import numpy as np from . import multiarray @@ -2162,11 +2163,19 @@ def isscalar(num): >>> np.isscalar('numpy') True + NumPy supports PEP 3141 numbers: + + >>> from fractions import Fraction + >>> isscalar(Fraction(5, 17)) + True + >>> from numbers import Number + >>> isscalar(Number()) + True + """ - if isinstance(num, generic): - return True - else: - return type(num) in ScalarType + return (isinstance(num, generic) + or type(num) in ScalarType + or isinstance(num, numbers.Number)) def binary_repr(num, width=None): -- cgit v1.2.1 From 4df78667e5b38560310f2e5e4e6b980821cce43d Mon Sep 17 00:00:00 2001 From: Spencer Hill Date: Mon, 18 Sep 2017 12:16:58 -0700 Subject: DOC allclose doesn't require matching shapes Closes https://github.com/numpy/numpy/issues/5654 --- 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 fde08490a..1f5d24936 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2448,6 +2448,10 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): The above equation is not symmetric in `a` and `b`, so that `allclose(a, b)` might be different from `allclose(b, a)` in some rare cases. + + The comparison of `a` and `b` includes standard broadcasting, + which means that `a` and `b` need not have the same shape in order for + allclose(a, b) to evaluate to True. (The same is true for `np.equals`.) Examples -------- -- cgit v1.2.1 From 08d60af925bb31e08259301a11b47b7d6f390ef2 Mon Sep 17 00:00:00 2001 From: Spencer Hill Date: Mon, 18 Sep 2017 13:32:18 -0700 Subject: Add equals to See Also; remove 'np.' --- 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 1f5d24936..4b78c16fd 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2436,7 +2436,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): See Also -------- - isclose, all, any + isclose, all, any, equals Notes ----- @@ -2451,7 +2451,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): The comparison of `a` and `b` includes standard broadcasting, which means that `a` and `b` need not have the same shape in order for - allclose(a, b) to evaluate to True. (The same is true for `np.equals`.) + allclose(a, b) to evaluate to True. (The same is true for `equals`.) Examples -------- -- cgit v1.2.1 From 687d7b8675f8cbc216c822574eb5bcb92007b412 Mon Sep 17 00:00:00 2001 From: Spencer Hill Date: Tue, 19 Sep 2017 21:31:06 -0700 Subject: [ci skip] requested updates [ci skip] --- numpy/core/numeric.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 4b78c16fd..e30df8b4e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2436,7 +2436,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): See Also -------- - isclose, all, any, equals + isclose, all, any, equal Notes ----- @@ -2446,12 +2446,13 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) The above equation is not symmetric in `a` and `b`, so that - `allclose(a, b)` might be different from `allclose(b, a)` in + ``allclose(a, b)`` might be different from ``allclose(b, a)`` in some rare cases. - - The comparison of `a` and `b` includes standard broadcasting, - which means that `a` and `b` need not have the same shape in order for - allclose(a, b) to evaluate to True. (The same is true for `equals`.) + + The comparison of `a` and `b` uses standard broadcasting, which + means that `a` and `b` need not have the same shape in order for + ``allclose(a, b)`` to evaluate to True. The same is true for + ``equal`` but not ``array_equal``. Examples -------- -- cgit v1.2.1 From 4031845251f6fd59da8840698bf36f4c7e974818 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 19 Sep 2017 23:01:50 -0700 Subject: MAINT: Remove unnecessary special-casing of scalars in isclose This means that this returns an `np.bool_` instead of a `bool`, but that seems more sensible anyway. The code was likely written this way for when scalar boolean indices didn't work --- numpy/core/numeric.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index fde08490a..c3c34666f 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2528,13 +2528,10 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): """ def within_tol(x, y, atol, rtol): with errstate(invalid='ignore'): - result = less_equal(abs(x-y), atol + rtol * abs(y)) - if isscalar(a) and isscalar(b): - result = bool(result) - return result + return less_equal(abs(x-y), atol + rtol * abs(y)) - x = array(a, copy=False, subok=True, ndmin=1) - y = array(b, copy=False, subok=True, ndmin=1) + x = asanyarray(a) + y = asanyarray(b) # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT). # This will cause casting of x later. Also, make sure to allow subclasses @@ -2561,12 +2558,11 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): if equal_nan: # Make NaN == NaN both_nan = isnan(x) & isnan(y) + + # Needed to treat masked arrays correctly. = True would not work. cond[both_nan] = both_nan[both_nan] - if isscalar(a) and isscalar(b): - return bool(cond) - else: - return cond + return cond[()] # Flatten 0d arrays to scalars def array_equal(a1, a2): -- cgit v1.2.1 From 7ad345e0e8f11ca68e21f20eed71df97a9fb70a4 Mon Sep 17 00:00:00 2001 From: Allan Haldane Date: Wed, 20 Sep 2017 18:01:56 -0400 Subject: MAINT: cleanup circular import b/w arrayprint.py,numeric.py Moves array_repr, array_str, g/set_printoptions to arrayprint.py --- numpy/core/numeric.py | 256 +++++++------------------------------------------- 1 file changed, 33 insertions(+), 223 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index fde08490a..dee069051 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -46,28 +46,23 @@ loads = pickle.loads __all__ = [ 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', - 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', - 'dtype', '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', 'correlate', 'convolve', 'inner', 'dot', - 'outer', 'vdot', 'roll', - 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'array2string', - 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', - 'set_string_function', 'little_endian', 'require', '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', 'False_', - 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', - 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', 'matmul', - 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', - 'TooHardError', 'AxisError' - ] - + 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', + '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', + 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll', + 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'require', + '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', + 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', + 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', + 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', + 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError' ] if sys.version_info[0] < 3: __all__.extend(['getbuffer', 'newbuffer']) @@ -363,20 +358,6 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): multiarray.copyto(res, fill_value, casting='unsafe') return res - -def extend_all(module): - adict = {} - for a in __all__: - adict[a] = 1 - try: - mall = getattr(module, '__all__') - except AttributeError: - mall = [k for k in module.__dict__.keys() if not k.startswith('_')] - for a in mall: - if a not in adict: - __all__.append(a) - - def count_nonzero(a, axis=None): """ Counts the number of non-zero values in the array ``a``. @@ -1820,193 +1801,6 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): return moveaxis(cp, -1, axisc) - -# Use numarray's printing function -from .arrayprint import array2string, get_printoptions, set_printoptions - - -_typelessdata = [int_, float_, complex_] -if issubclass(intc, int): - _typelessdata.append(intc) - - -if issubclass(longlong, int): - _typelessdata.append(longlong) - - -def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): - """ - Return the string representation of an array. - - Parameters - ---------- - arr : ndarray - Input array. - max_line_width : int, optional - The maximum number of columns the string should span. Newline - characters split the string appropriately after array elements. - precision : int, optional - Floating point precision. Default is the current printing precision - (usually 8), which can be altered using `set_printoptions`. - suppress_small : bool, optional - Represent very small numbers as zero, default is False. Very small - is defined by `precision`, if the precision is 8 then - numbers smaller than 5e-9 are represented as zero. - - Returns - ------- - string : str - The string representation of an array. - - See Also - -------- - array_str, array2string, set_printoptions - - Examples - -------- - >>> np.array_repr(np.array([1,2])) - 'array([1, 2])' - >>> np.array_repr(np.ma.array([0.])) - 'MaskedArray([ 0.])' - >>> np.array_repr(np.array([], np.int32)) - 'array([], dtype=int32)' - - >>> x = np.array([1e-6, 4e-7, 2, 3]) - >>> np.array_repr(x, precision=6, suppress_small=True) - 'array([ 0.000001, 0. , 2. , 3. ])' - - """ - if type(arr) is not ndarray: - class_name = type(arr).__name__ - else: - class_name = "array" - - if arr.size > 0 or arr.shape == (0,): - lst = array2string(arr, max_line_width, precision, suppress_small, - ', ', class_name + "(") - else: # show zero-length shape unless it is (0,) - lst = "[], shape=%s" % (repr(arr.shape),) - - skipdtype = (arr.dtype.type in _typelessdata) and arr.size > 0 - - if skipdtype: - return "%s(%s)" % (class_name, lst) - else: - typename = arr.dtype.name - # Quote typename in the output if it is "complex". - if typename and not (typename[0].isalpha() and typename.isalnum()): - typename = "'%s'" % typename - - lf = ' ' - if issubclass(arr.dtype.type, flexible): - if arr.dtype.names: - typename = "%s" % str(arr.dtype) - else: - typename = "'%s'" % str(arr.dtype) - lf = '\n'+' '*len(class_name + "(") - return "%s(%s,%sdtype=%s)" % (class_name, lst, lf, typename) - - -def array_str(a, max_line_width=None, precision=None, suppress_small=None): - """ - Return a string representation of the data in an array. - - The data in the array is returned as a single string. This function is - similar to `array_repr`, the difference being that `array_repr` also - returns information on the kind of array and its data type. - - Parameters - ---------- - a : ndarray - Input array. - max_line_width : int, optional - Inserts newlines if text is longer than `max_line_width`. The - default is, indirectly, 75. - precision : int, optional - Floating point precision. Default is the current printing precision - (usually 8), which can be altered using `set_printoptions`. - suppress_small : bool, optional - Represent numbers "very close" to zero as zero; default is False. - Very close is defined by precision: if the precision is 8, e.g., - numbers smaller (in absolute value) than 5e-9 are represented as - zero. - - See Also - -------- - array2string, array_repr, set_printoptions - - Examples - -------- - >>> np.array_str(np.arange(3)) - '[0 1 2]' - - """ - return array2string(a, max_line_width, precision, suppress_small, ' ', "") - - -def set_string_function(f, repr=True): - """ - Set a Python function to be used when pretty printing arrays. - - Parameters - ---------- - f : function or None - Function to be used to pretty print arrays. The function should expect - a single array argument and return a string of the representation of - the array. If None, the function is reset to the default NumPy function - to print arrays. - repr : bool, optional - If True (default), the function for pretty printing (``__repr__``) - is set, if False the function that returns the default string - representation (``__str__``) is set. - - See Also - -------- - set_printoptions, get_printoptions - - Examples - -------- - >>> def pprint(arr): - ... return 'HA! - What are you going to do now?' - ... - >>> np.set_string_function(pprint) - >>> a = np.arange(10) - >>> a - HA! - What are you going to do now? - >>> print(a) - [0 1 2 3 4 5 6 7 8 9] - - We can reset the function to the default: - - >>> np.set_string_function(None) - >>> a - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - - `repr` affects either pretty printing or normal string representation. - Note that ``__repr__`` is still affected by setting ``__str__`` - because the width of each array element in the returned string becomes - equal to the length of the result of ``__str__()``. - - >>> x = np.arange(4) - >>> np.set_string_function(lambda x:'random', repr=False) - >>> x.__str__() - 'random' - >>> x.__repr__() - 'array([ 0, 1, 2, 3])' - - """ - if f is None: - if repr: - return multiarray.set_string_function(array_repr, 1) - else: - return multiarray.set_string_function(array_str, 0) - else: - return multiarray.set_string_function(f, repr) - - -set_string_function(array_str, 0) -set_string_function(array_repr, 1) - little_endian = (sys.byteorder == 'little') @@ -3092,10 +2886,26 @@ nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) + +def extend_all(module): + adict = {} + for a in __all__: + adict[a] = 1 + try: + mall = getattr(module, '__all__') + except AttributeError: + mall = [k for k in module.__dict__.keys() if not k.startswith('_')] + for a in mall: + if a not in adict: + __all__.append(a) + from .umath import * from .numerictypes import * from . import fromnumeric from .fromnumeric import * +from . import arrayprint +from .arrayprint import * extend_all(fromnumeric) extend_all(umath) extend_all(numerictypes) +extend_all(arrayprint) -- cgit v1.2.1 From 42fcdd0cc381a96d8096af7acda007317d08851f Mon Sep 17 00:00:00 2001 From: Charles Harris Date: Sat, 23 Sep 2017 09:07:46 -0600 Subject: MAINT: Use single backticks when link needed. [ci skip] --- 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 e30df8b4e..495bd7fad 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2452,7 +2452,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): The comparison of `a` and `b` uses standard broadcasting, which means that `a` and `b` need not have the same shape in order for ``allclose(a, b)`` to evaluate to True. The same is true for - ``equal`` but not ``array_equal``. + `equal` but not `array_equal`. Examples -------- -- cgit v1.2.1 From 6fbbadb676dfa7cee56be3bd17b92bde661f8869 Mon Sep 17 00:00:00 2001 From: hemildesai Date: Tue, 19 Sep 2017 22:01:29 -0700 Subject: DEP: Deprecate truth testing on empty arrays Fixes #9583 --- 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 ce17a1900..5b10361fe 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -406,7 +406,7 @@ def count_nonzero(a, axis=None): array([2, 3]) """ - if axis is None or axis == (): + if axis is None or (isinstance(axis, tuple) and axis == ()): return multiarray.count_nonzero(a) a = asanyarray(a) -- cgit v1.2.1 From fb168b8a5ee222ff352d20bfc1efab9009d68347 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Wed, 11 Oct 2017 00:56:26 -0700 Subject: MAINT: Fix all special-casing of dtypes in `count_nonzero` A quick profile reveals that `int.astype(bool)` is faster than `int == 0` anyway --- numpy/core/numeric.py | 32 ++++++-------------------------- 1 file changed, 6 insertions(+), 26 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 5b10361fe..6d29785da 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -411,33 +411,13 @@ def count_nonzero(a, axis=None): a = asanyarray(a) - if a.dtype == bool: - return a.sum(axis=axis, dtype=np.intp) - - if issubdtype(a.dtype, np.number): - return (a != 0).sum(axis=axis, dtype=np.intp) - - if issubdtype(a.dtype, np.character): - nullstr = a.dtype.type('') - return (a != nullstr).sum(axis=axis, dtype=np.intp) - - axis = asarray(normalize_axis_tuple(axis, a.ndim)) - counts = np.apply_along_axis(multiarray.count_nonzero, axis[0], a) - - if axis.size == 1: - return counts.astype(np.intp, copy=False) + # TODO: this works around .astype(bool) not working properly (gh-9847) + if np.issubdtype(a.dtype, np.character): + a_bool = a != a.dtype.type() else: - # for subsequent axis numbers, that number decreases - # by one in this new 'counts' array if it was larger - # than the first axis upon which 'count_nonzero' was - # applied but remains unchanged if that number was - # smaller than that first axis - # - # this trick enables us to perform counts on object-like - # elements across multiple axes very quickly because integer - # addition is very well optimized - return counts.sum(axis=tuple(axis[1:] - ( - axis[1:] > axis[0])), dtype=np.intp) + a_bool = a.astype(np.bool_, copy=False) + + return a_bool.sum(axis=axis, dtype=np.intp) def asarray(a, dtype=None, order=None): -- cgit v1.2.1 From 3856a73ec59d9dcf8252a2d38b43191eacacbd2e Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 17 Oct 2017 20:41:39 -0700 Subject: BUG: count_nonzero treats empty axis tuples strangely Fixes #9728 This bug was introduced with the `axis` keyword in #7177, as a misguided optimization. --- 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 6d29785da..1f8f5d43e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -406,7 +406,7 @@ def count_nonzero(a, axis=None): array([2, 3]) """ - if axis is None or (isinstance(axis, tuple) and axis == ()): + if axis is None: return multiarray.count_nonzero(a) a = asanyarray(a) -- cgit v1.2.1 From 1368cbb696ae27b849eed67b4fd31c550a55dad5 Mon Sep 17 00:00:00 2001 From: Matti Picus Date: Wed, 8 Nov 2017 22:49:19 +0200 Subject: DEP, ENH: deprecate UPDATEIFCOPY (except for nditer) and replace with WRITEBACKIFCOPY (#9639) * ENH: add API to resolve UPDATEONCOPY outside dealloc, test and use * BUG: Fix usage of keyword "from" as argument name for "can_cast". Also removed inconsistency between the second argument name between documentation ("totype") and code ("to"). * UPDATEIFCOPY -> WRITEBACKIFCOPY, documentation * fixes for review * review2, fix new test * fix new test for using self.assert_deprecated * change deprecation logic as per review * new logic exposed places where PyArray_ResolveWritebackIfCopy not called * deprecate PyArray_XDECREF_ERR in favor of PyArray_DiscardWritebackIfCopy * code review changes * clean up merge cruft * fix from review * fixes from review * extend the release note --- numpy/core/numeric.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index bf3f43444..25f4d6c35 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -666,6 +666,7 @@ def require(a, dtype=None, requirements=None): OWNDATA : False WRITEABLE : True ALIGNED : True + WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) @@ -675,6 +676,7 @@ def require(a, dtype=None, requirements=None): OWNDATA : True WRITEABLE : True ALIGNED : True + WRITEBACKIFCOPY : False UPDATEIFCOPY : False """ -- cgit v1.2.1 From ac6b1a902b99e340cf7eeeeb7392c91e38db9dd8 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Mon, 13 Nov 2017 23:45:45 -0800 Subject: ENH: don't show boolean dtype, as it is implied --- 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 25f4d6c35..ac64b0537 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1193,7 +1193,7 @@ def tensordot(a, b, axes=2): [ True, True], [ True, True], [ True, True], - [ True, True]], dtype=bool) + [ True, True]]) An extended example taking advantage of the overloading of + and \\*: @@ -1901,7 +1901,7 @@ def fromfunction(function, shape, **kwargs): >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) array([[ True, False, False], [False, True, False], - [False, False, True]], dtype=bool) + [False, False, True]]) >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) array([[0, 1, 2], -- cgit v1.2.1 From b023d734eeec42a2a1064eaed4de12fd676f1de0 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 10 Dec 2017 10:08:44 -0800 Subject: DEP: Deprecate the pickle aliases * The np.ma functions are misleading, as they do not actually do anything special for ma.array * The np.loads functions doesn't even have numpy-specific documentation, and does not behave consistently with `np.load` * The string overloads of np.ma.load and np.ma.dump do not work well on python 3, as they make assumptions about whether a binary or text pickle file is used (gh-5491) --- 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 ac64b0537..431467a5a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -42,7 +42,13 @@ else: import cPickle as pickle import __builtin__ as builtins -loads = pickle.loads + +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__ = [ @@ -2134,6 +2140,10 @@ def load(file): 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("")): file = open(file, "rb") return pickle.load(file) -- cgit v1.2.1 From 2d761b6ac092b93cb011db524e9f230957e5ff0f Mon Sep 17 00:00:00 2001 From: xoviat Date: Tue, 26 Dec 2017 12:29:52 -0600 Subject: DOC: add warning to isclose function (#10214) * DOC: add warning to isclose function The default absolute tolerance for isclose can result in misleading results when the numbers being compared are much less than one. See gh-10161 for discussion. * DOC: compare numpy.isclose to math.isclose function. * DOC: somewhat clarify the warning for the isclose function * DOC: clarify notes for isclose function * DOC: clarify that atol should be reduced for small numbers * DOC: update based on feedback * DOC: update based on feedback [skip-ci] --- numpy/core/numeric.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 431467a5a..123bff2ec 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2276,6 +2276,9 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. + + .. warning:: The default `atol` is not appropriate for comparing numbers + that are much smaller than one (see Notes). Parameters ---------- @@ -2309,9 +2312,15 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) - The above equation is not symmetric in `a` and `b`, so that - `isclose(a, b)` might be different from `isclose(b, a)` in - some rare cases. + Unlike the built-in `math.isclose`, the above equation is not symmetric + in `a` and `b` -- it assumes `b` is the reference value -- so that + `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore, + the default value of atol is not zero, and is used to determine what + small values should be considered close to zero. The default value is + appropriate for expected values of order unity: if the expected values + are significantly smaller than one, it can result in false positives. + `atol` should be carefully selected for the use case at hand. A zero value + for `atol` will result in `False` if either `a` or `b` is zero. Examples -------- @@ -2325,6 +2334,14 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): array([True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([True, True]) + >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) + array([ True, False], dtype=bool) + >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) + array([False, False], dtype=bool) + >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) + array([ True, True], dtype=bool) + >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) + array([False, True], dtype=bool) """ def within_tol(x, y, atol, rtol): with errstate(invalid='ignore'): -- cgit v1.2.1 From 579034a0c925ee9db5157141d73209beca037aeb Mon Sep 17 00:00:00 2001 From: Geoffrey Irving Date: Thu, 15 Feb 2018 11:56:56 -0800 Subject: ENH: make flatnonzero use np.ravel(a) instead of a.ravel() It now works for lists and other numpy-convertible input. Fixes #10598. --- numpy/core/numeric.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 123bff2ec..5c8951474 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -829,12 +829,12 @@ def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. - This is equivalent to a.ravel().nonzero()[0]. + This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ---------- - a : ndarray - Input array. + a : array_like + Input data. Returns ------- @@ -862,7 +862,7 @@ def flatnonzero(a): array([-2, -1, 1, 2]) """ - return a.ravel().nonzero()[0] + return np.nonzero(np.ravel(a))[0] _mode_from_name_dict = {'v': 0, -- cgit v1.2.1 From 96f346d2ac81f12081cacb6524bc779626132a68 Mon Sep 17 00:00:00 2001 From: Andrey Portnoy Date: Wed, 28 Feb 2018 05:25:13 -0800 Subject: STY: Minor stylistic cleanup of numeric.py No changes to the logic, only minor edits guided by flake8. --- numpy/core/numeric.py | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 5c8951474..d2d59d9b2 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -69,7 +69,7 @@ __all__ = [ 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like', 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS', - 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError' ] + 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError'] if sys.version_info[0] < 3: __all__.extend(['getbuffer', 'newbuffer']) @@ -365,6 +365,7 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): multiarray.copyto(res, fill_value, casting='unsafe') return res + def count_nonzero(a, axis=None): """ Counts the number of non-zero values in the array ``a``. @@ -686,12 +687,12 @@ def require(a, dtype=None, requirements=None): 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'} + 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: @@ -1123,7 +1124,7 @@ def outer(a, b, out=None): """ a = asarray(a) b = asarray(b) - return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out) + return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out) def tensordot(a, b, axes=2): @@ -1790,6 +1791,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): return moveaxis(cp, -1, axisc) + little_endian = (sys.byteorder == 'little') @@ -2313,12 +2315,12 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Unlike the built-in `math.isclose`, the above equation is not symmetric - in `a` and `b` -- it assumes `b` is the reference value -- so that + in `a` and `b` -- it assumes `b` is the reference value -- so that `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values - are significantly smaller than one, it can result in false positives. + are significantly smaller than one, it can result in false positives. `atol` should be carefully selected for the use case at hand. A zero value for `atol` will result in `False` if either `a` or `b` is zero. @@ -2471,12 +2473,12 @@ 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 = {"ignore": ERR_IGNORE, + "warn": ERR_WARN, + "raise": ERR_RAISE, + "call": ERR_CALL, + "print": ERR_PRINT, + "log": ERR_LOG} _errdict_rev = {} for key in _errdict.keys(): @@ -2543,7 +2545,8 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} >>> np.seterr(**old_settings) # reset to default - {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} >>> np.int16(32000) * np.int16(3) 30464 @@ -2690,11 +2693,11 @@ def seterrcall(func): 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":: + 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] @@ -2811,6 +2814,8 @@ def geterrcall(): class _unspecified(object): pass + + _Unspecified = _unspecified() @@ -2918,6 +2923,7 @@ def extend_all(module): if a not in adict: __all__.append(a) + from .umath import * from .numerictypes import * from . import fromnumeric -- cgit v1.2.1 From 5a238789894a1f21961217eaaae3e18bcf6ea7c7 Mon Sep 17 00:00:00 2001 From: Nelle Varoquaux Date: Wed, 28 Feb 2018 16:38:55 -0800 Subject: DOC zeros, empty, and ones now have consistent docstrings closes #10611 --- numpy/core/numeric.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index d2d59d9b2..1f249ae6c 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -160,9 +160,10 @@ def ones(shape, dtype=None, order='C'): dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. - order : {'C', 'F'}, optional - Whether to store multidimensional data in C- or Fortran-contiguous - (row- or column-wise) order in memory. + order : {'C', 'F'}, optional, default: C + Whether to store multi-dimensional data in row-major + (C-style) or column-major (Fortran-style) order in + memory. Returns ------- -- cgit v1.2.1 From 53b358ce7eddf78ac2bc22045fbe25e91e663b9a Mon Sep 17 00:00:00 2001 From: Frederick Lefebvre Date: Wed, 14 Mar 2018 03:33:05 +0000 Subject: TST: Import abstract classes from collections.abc Abstract collection classes accessed from the collections module have been deprecated since Python 3.3. They should be accessed through collections.abc. When run with Python 3.7, the deprecation warning cause multiple tests to fail. --- 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 1f249ae6c..d2348f364 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,6 +1,11 @@ from __future__ import division, absolute_import, print_function -import collections +try: + # Accessing collections abstact classes from collections + # has been deprecated since Python 3.3 + import collections.abc as collections_abc +except ImportError: + import collections as collections_abc import itertools import operator import sys @@ -2758,8 +2763,8 @@ def seterrcall(func): {'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'} """ - if func is not None and not isinstance(func, collections.Callable): - if not hasattr(func, 'write') or not isinstance(func.write, collections.Callable): + 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() -- cgit v1.2.1 From 53a558ca2e6f400830210d30c9e1f5ccaa3268eb Mon Sep 17 00:00:00 2001 From: ChloeColeongco Date: Thu, 22 Mar 2018 12:25:39 -0600 Subject: Fixed author name in reference to book ('van' vs 'Van') --- 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 d2348f364..aa5059180 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1089,7 +1089,7 @@ def outer(a, b, out=None): References ---------- - .. [1] : G. H. Golub and C. F. van Loan, *Matrix Computations*, 3rd + .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8. -- cgit v1.2.1 From 108d01a0a4eea38ed5b8e88de34ee2d0324fec65 Mon Sep 17 00:00:00 2001 From: "luz.paz" Date: Fri, 30 Mar 2018 09:33:39 -0400 Subject: DOC: Fix minor typos Found via `codespell -q 3 -I ../numpy-whitelist.txt` --- 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 aa5059180..d154206c5 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,7 +1,7 @@ from __future__ import division, absolute_import, print_function try: - # Accessing collections abstact classes from collections + # Accessing collections abstract classes from collections # has been deprecated since Python 3.3 import collections.abc as collections_abc except ImportError: -- cgit v1.2.1 From f2f17210a5e5824a9977d63957c09bbe5d64eda2 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Mon, 9 Apr 2018 12:14:24 -0700 Subject: Cross Link full/full_like in a few see-also. While teaching numpy I was asked the best way to create an array of nan, and `np.full` seem not be cross linked from many places; In particular in the documentation of `zeros` and `ones` seam like obvious candidates to add them. Reorder all the see-also to be - empty_like - ones_like - zero_like - full_like - empty - ones - zeros - full --- numpy/core/numeric.py | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index d154206c5..a5ee5f815 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -123,11 +123,13 @@ def zeros_like(a, dtype=None, order='K', subok=True): See Also -------- - ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. - zeros : Return a new array setting values to zero. - ones : Return a new array setting values to one. + ones_like : Return an array of ones with shape and type of input. + full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. + ones : Return a new array setting values to one. + zeros : Return a new array setting values to zero. + full : Return a new array of given shape filled with value. Examples -------- @@ -177,7 +179,14 @@ def ones(shape, dtype=None, order='C'): See Also -------- - zeros, ones_like + empty_like : Return an empty array with shape and type of input. + ones_like : Return an array of ones with shape and type of input. + zeros_like : Return an array of zeros with shape and type of input. + full_like : Return a new array with shape of input filled with value. + empty : Return a new uninitialized array. + zeros : Return a new array setting values to zero. + full : Return a new array of given shape filled with value. + Examples -------- @@ -234,11 +243,13 @@ def ones_like(a, dtype=None, order='K', subok=True): See Also -------- - zeros_like : Return an array of zeros with shape and type of input. empty_like : Return an empty array with shape and type of input. - zeros : Return a new array setting values to zero. - ones : Return a new array setting values to one. + zeros_like : Return an array of zeros with shape and type of input. + full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. + ones : Return a new array setting values to one. + zeros : Return a new array setting values to zero. + full : Return a new array of given shape filled with value. Examples -------- @@ -287,13 +298,13 @@ def full(shape, fill_value, dtype=None, order='C'): See Also -------- - zeros_like : Return an array of zeros with shape and type of input. - ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. - full_like : Fill an array with shape and type of input. - zeros : Return a new array setting values to zero. - ones : Return a new array setting values to one. + ones_like : Return an array of ones with shape and type of input. + zeros_like : Return an array of zeros with shape and type of input. + full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. + ones : Return a new array setting values to one. + zeros : Return a new array setting values to zero. Examples -------- @@ -342,13 +353,13 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): See Also -------- - zeros_like : Return an array of zeros with shape and type of input. - ones_like : Return an array of ones with shape and type of input. empty_like : Return an empty array with shape and type of input. - zeros : Return a new array setting values to zero. - ones : Return a new array setting values to one. + ones_like : Return an array of ones with shape and type of input. + zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. - full : Fill a new array. + ones : Return a new array setting values to one. + zeros : Return a new array setting values to zero. + full : Return a new array of given shape filled with value. Examples -------- -- cgit v1.2.1 From 35753b1f28106d5b3fe48f31130e2dde7a02aa0c Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Mon, 9 Apr 2018 13:43:38 -0700 Subject: 'remove indirect relationships' --- numpy/core/numeric.py | 15 --------------- 1 file changed, 15 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index a5ee5f815..77aaf6dec 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -126,10 +126,7 @@ def zeros_like(a, dtype=None, order='K', subok=True): empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. full_like : Return a new array with shape of input filled with value. - empty : Return a new uninitialized array. - ones : Return a new array setting values to one. zeros : Return a new array setting values to zero. - full : Return a new array of given shape filled with value. Examples -------- @@ -179,10 +176,7 @@ def ones(shape, dtype=None, order='C'): See Also -------- - empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. - zeros_like : Return an array of zeros with shape and type of input. - full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value. @@ -246,10 +240,7 @@ def ones_like(a, dtype=None, order='K', subok=True): empty_like : Return an empty array with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full_like : Return a new array with shape of input filled with value. - empty : Return a new uninitialized array. ones : Return a new array setting values to one. - zeros : Return a new array setting values to zero. - full : Return a new array of given shape filled with value. Examples -------- @@ -298,9 +289,6 @@ def full(shape, fill_value, dtype=None, order='C'): See Also -------- - empty_like : Return an empty array with shape and type of input. - ones_like : Return an array of ones with shape and type of input. - zeros_like : Return an array of zeros with shape and type of input. full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. ones : Return a new array setting values to one. @@ -356,9 +344,6 @@ def full_like(a, fill_value, dtype=None, order='K', subok=True): empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. - empty : Return a new uninitialized array. - ones : Return a new array setting values to one. - zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value. Examples -- cgit v1.2.1 From 1eef2af85df832b55c856935a820889cdee83581 Mon Sep 17 00:00:00 2001 From: mattip Date: Wed, 11 Apr 2018 14:23:07 +0300 Subject: formatting fixes --- 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 d154206c5..028dfc745 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2533,7 +2533,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Notes ----- - The floating-point exceptions are defined in the IEEE 754 standard [1]: + 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. -- cgit v1.2.1 From d7e0c7e34b293ab32a46960c65d063446115d4e8 Mon Sep 17 00:00:00 2001 From: Marten van Kerkwijk Date: Sun, 29 Apr 2018 15:24:01 -0400 Subject: MAINT: move matrix tests in core, polynomial to matrixlib. --- numpy/core/numeric.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1108d4667..cd783d242 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -489,9 +489,9 @@ def asarray(a, dtype=None, order=None): Contrary to `asanyarray`, ndarray subclasses are not passed through: - >>> issubclass(np.matrix, np.ndarray) + >>> issubclass(np.recarray, np.ndarray) True - >>> a = np.matrix([[1, 2]]) + >>> 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 @@ -545,7 +545,7 @@ def asanyarray(a, dtype=None, order=None): Instances of `ndarray` subclasses are passed through as-is: - >>> a = np.matrix([1, 2]) + >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) >>> np.asanyarray(a) is a True @@ -2280,7 +2280,7 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. - + .. warning:: The default `atol` is not appropriate for comparing numbers that are much smaller than one (see Notes). -- cgit v1.2.1 From 6aa659951a63d7c491f1a06aea0605ea30ec699f Mon Sep 17 00:00:00 2001 From: zuko3d Date: Fri, 18 May 2018 19:54:01 +0300 Subject: BUG: Fix typo in variable name (#11116) Typo fix in variable name in core/numeric/binary_repr/warn_if_insufficient. This only worked before because it used binwidth from the outer namespace. --- 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 cd783d242..7ade3d224 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2035,7 +2035,7 @@ def binary_repr(num, width=None): '11101' """ - def warn_if_insufficient(width, binwdith): + def warn_if_insufficient(width, binwidth): if width is not None and width < binwidth: warnings.warn( "Insufficient bit width provided. This behavior " -- cgit v1.2.1 From a8556c1007dbf7eb329caaa3dbffc9cd708359ec Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Wed, 13 Jun 2018 01:27:56 -0700 Subject: MAINT: Use a set instead of a dictionary --- numpy/core/numeric.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 7ade3d224..4ff12dbbd 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2914,15 +2914,13 @@ True_ = bool_(True) def extend_all(module): - adict = {} - for a in __all__: - adict[a] = 1 + existing = set(__all__) try: mall = getattr(module, '__all__') except AttributeError: mall = [k for k in module.__dict__.keys() if not k.startswith('_')] for a in mall: - if a not in adict: + if a not in existing: __all__.append(a) -- cgit v1.2.1 From 83828f52b287fefb3d8753a21bd3441997a4d687 Mon Sep 17 00:00:00 2001 From: Mike Toews Date: Sat, 16 Jun 2018 18:18:19 +1200 Subject: HTTP -> HTTPS, and other linkrot fixes --- numpy/core/numeric.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 4ff12dbbd..106f0ccfe 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1010,7 +1010,8 @@ def convolve(a, v, mode='full'): References ---------- - .. [1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution. + .. [1] Wikipedia, "Convolution", + https://en.wikipedia.org/wiki/Convolution Examples -------- @@ -2015,7 +2016,7 @@ def binary_repr(num, width=None): References ---------- .. [1] Wikipedia, "Two's complement", - http://en.wikipedia.org/wiki/Two's_complement + https://en.wikipedia.org/wiki/Two's_complement Examples -------- @@ -2538,7 +2539,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): - Invalid operation: result is not an expressible number, typically indicates that a NaN was produced. - .. [1] http://en.wikipedia.org/wiki/IEEE_754 + .. [1] https://en.wikipedia.org/wiki/IEEE_754 Examples -------- -- cgit v1.2.1 From e9bf4aefc982341c106a05e1db60054bc1c5957c Mon Sep 17 00:00:00 2001 From: silenc3r Date: Thu, 28 Jun 2018 20:03:50 +0100 Subject: Fix documentation for fromfunction ```np.fromfunction(lambda i, j: 1, (3, 3), dtype=int)``` returns ```1```. --- 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 106f0ccfe..b49a7f551 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1897,7 +1897,7 @@ def fromfunction(function, shape, **kwargs): The result of the call to `function` is passed back directly. Therefore the shape of `fromfunction` is completely determined by `function`. If `function` returns a scalar value, the shape of - `fromfunction` would match the `shape` parameter. + `fromfunction` would not match the `shape` parameter. See Also -------- -- cgit v1.2.1 From 5c42cc31fa1ac6bfaed50d7069d7bb8e8fd8bb53 Mon Sep 17 00:00:00 2001 From: Marten van Kerkwijk Date: Fri, 6 Jul 2018 11:10:22 -0400 Subject: MAINT: Speed up normalize_axis_tuple by about 30% MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is used in `np.moveaxis`, which is relatively slow. Timings change as follows: ``` import numpy as np from numpy.core.numeric import normalize_axis_tuple %timeit normalize_axis_tuple([0, 1, 2], 4, 'parrot') a = np.zeros((10,20,30)) %timeit np.moveaxis(a, [0,1,2], [2,1,0]) 100000 loops, best of 3: 5.56 µs per loop -> 4.17 µs ``` --- numpy/core/numeric.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index b49a7f551..a9fa3efe0 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1509,11 +1509,14 @@ def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): -------- normalize_axis_index : normalizing a single scalar axis """ - try: - axis = [operator.index(axis)] - except TypeError: - axis = tuple(axis) - axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis) + # Speed-up most common cases. + if not isinstance(axis, (list, tuple)): + try: + axis = [operator.index(axis)] + except TypeError: + pass + # Going via an iterator directly is slower than via list comprehension. + axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis]) if not allow_duplicate and len(set(axis)) != len(axis): if argname: raise ValueError('repeated axis in `{}` argument'.format(argname)) -- cgit v1.2.1 From 4bed228adba88f9c5b85eaad308582db79a95b7b Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Sun, 8 Jul 2018 17:38:33 +0100 Subject: MAINT: Restore previous behavior on subclasses --- 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 a9fa3efe0..e5570791a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1509,8 +1509,8 @@ def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False): -------- normalize_axis_index : normalizing a single scalar axis """ - # Speed-up most common cases. - if not isinstance(axis, (list, tuple)): + # Optimization to speed-up the most common cases. + if type(axis) not in (tuple, list): try: axis = [operator.index(axis)] except TypeError: -- cgit v1.2.1 From 03e08148eb303c7799a18db78b8087f78e5cc2fc Mon Sep 17 00:00:00 2001 From: mattip Date: Thu, 2 Aug 2018 18:23:54 -0700 Subject: MAINT: remove code that codecov pointed out is superflous --- 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 e5570791a..655548bb0 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2919,10 +2919,7 @@ True_ = bool_(True) def extend_all(module): existing = set(__all__) - try: - mall = getattr(module, '__all__') - except AttributeError: - mall = [k for k in module.__dict__.keys() if not k.startswith('_')] + mall = getattr(module, '__all__') for a in mall: if a not in existing: __all__.append(a) -- cgit v1.2.1 From bcdd3e7e11b7bce4ed77f9f45fffa584c0f8438a Mon Sep 17 00:00:00 2001 From: "Michael Hirsch, Ph.D" Date: Tue, 28 Aug 2018 23:27:25 -0400 Subject: DOC, MAINT: Fixes for errstate() and README.md documentation. (#11814) * DOC: errstate() and AppVeyor badge link Removes outdated references to Python 2.5, which hasn't been supported for several releases. Corrected README.rst AppVeyor badge link. * revert appveyor badge link to charris --- numpy/core/numeric.py | 5 ----- 1 file changed, 5 deletions(-) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index e5570791a..6c9baef0a 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2850,16 +2850,11 @@ class errstate(object): Notes ----- - The ``with`` statement was introduced in Python 2.5, and can only be used - there by importing it: ``from __future__ import with_statement``. In - earlier Python versions the ``with`` statement is not available. - For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. Examples -------- - >>> from __future__ import with_statement # use 'with' in Python 2.5 >>> olderr = np.seterr(all='ignore') # Set error handling to known state. >>> np.arange(3) / 0. -- cgit v1.2.1 From 547c74767d00e69a1385a588b6ed00b67bf87993 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 4 Sep 2018 23:09:13 -0700 Subject: DOC: Recommend the use of `np.ndim` over `np.isscalar`, and explain the differences --- numpy/core/numeric.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1b4818b76..2e46057ac 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1942,10 +1942,46 @@ def isscalar(num): val : bool True if `num` is a scalar type, False if it is not. + See Also + -------- + ndim : Get the number of dimensions of an array + + Notes + ----- + In almost all cases ``np.ndim(x) == 0`` should be used instead of this + function, as that will also return true for 0d arrays. This is how + numpy overloads functions in the style of the ``dx`` arguments to `gradient` + and the ``bins`` argument to `histogram`. Some key differences: + + +--------------------------------------+---------------+-------------------+ + | x |``isscalar(x)``|``np.ndim(x) == 0``| + +======================================+===============+===================+ + | PEP 3141 numeric objects (including | ``True`` | ``True`` | + | builtins) | | | + +--------------------------------------+---------------+-------------------+ + | builtin string and buffer objects | ``True`` | ``True`` | + +--------------------------------------+---------------+-------------------+ + | other builtin objects, like | ``False`` | ``True`` | + | `pathlib.Path`, `Exception`, | | | + | the result of `re.compile` | | | + +--------------------------------------+---------------+-------------------+ + | third-party objects like | ``False`` | ``True`` | + | `matplotlib.figure.Figure` | | | + +--------------------------------------+---------------+-------------------+ + | zero-dimensional numpy arrays | ``False`` | ``True`` | + +--------------------------------------+---------------+-------------------+ + | other numpy arrays | ``False`` | ``False`` | + +--------------------------------------+---------------+-------------------+ + | `list`, `tuple`, and other sequence | ``False`` | ``False`` | + | objects | | | + +--------------------------------------+---------------+-------------------+ + Examples -------- >>> np.isscalar(3.1) True + >>> np.isscalar(np.array(3.1)) + False >>> np.isscalar([3.1]) False >>> np.isscalar(False) -- cgit v1.2.1 From 5e3412dfc139b733b136c2c3b508eb7bf7b8ec10 Mon Sep 17 00:00:00 2001 From: mattip Date: Sat, 8 Sep 2018 20:24:49 +0300 Subject: MAINT: remove redundant imports --- 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 1b4818b76..c93eab03b 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -18,7 +18,7 @@ from .multiarray import ( _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE, WRAP, arange, array, broadcast, can_cast, compare_chararrays, - concatenate, copyto, count_nonzero, dot, dtype, empty, + concatenate, copyto, dot, dtype, empty, empty_like, flatiter, frombuffer, fromfile, fromiter, fromstring, inner, int_asbuffer, lexsort, matmul, may_share_memory, min_scalar_type, ndarray, nditer, nested_iters, promote_types, -- cgit v1.2.1 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