From f31f12afa6fcbc852dfc57b34dd701d7b4145203 Mon Sep 17 00:00:00 2001 From: Neal C Date: Tue, 14 Jul 2020 00:44:56 -0700 Subject: DOC: Add explanation of 'K' and 'A' layout options to 'asarray*' functions (#16811) * DOC: update parameter choices for asarray, asarray_contiguous, asarray_chkfinite converters Co-authored-by: sun --- numpy/lib/function_base.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 42ea8c7a7..6ea9cc4de 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -431,10 +431,13 @@ def asarray_chkfinite(a, dtype=None, order=None): of lists and ndarrays. Success requires no NaNs or Infs. 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'. + order : {'C', 'F', 'A', 'K'}, optional + Memory layout. 'A' and 'K' depend on the order of input array a. + 'C' row-major (C-style), + 'F' column-major (Fortran-style) memory representation. + 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise + 'K' (keep) preserve input order + Defaults to 'C'. Returns ------- -- cgit v1.2.1 From 8066b45451eff24228bb5af96aad2fe0bd548383 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 14 May 2020 18:47:59 -0700 Subject: edge first try ENH: added edge keyword argument to digitize added test --- numpy/lib/function_base.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 6ea9cc4de..c7f3dc033 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4733,12 +4733,12 @@ def append(arr, values, axis=None): return concatenate((arr, values), axis=axis) -def _digitize_dispatcher(x, bins, right=None): +def _digitize_dispatcher(x, bins, right=None, edge=None): return (x, bins) @array_function_dispatch(_digitize_dispatcher) -def digitize(x, bins, right=False): +def digitize(x, bins, right=False, edge=False): """ Return the indices of the bins to which each value in input array belongs. @@ -4767,6 +4767,10 @@ def digitize(x, bins, right=False): does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. + edge : bool, optional + Whether to include the last right edge if right == False or the first + left edge if right == True. If egde==True, the entire interval is + included that would otherwise not be for the first or last edge case. Returns ------- @@ -4839,6 +4843,18 @@ def digitize(x, bins, right=False): if mono == 0: raise ValueError("bins must be monotonically increasing or decreasing") + if edge: + # if cannot make round trip, cannot use eps + if np.issubdtype(bins.dtype, _nx.int64): + if (bins != bins.astype(_nx.float64).astype(_nx.int64)).any(): + raise ValueError("bins have too large values to use" + "'edges=True'") + bins = bins.astype(_nx.float64) + if right: + bins[0] -= np.finfo(_nx.float64).eps * 2 * mono + else: + bins[-1] += np.finfo(_nx.float64).eps * 2 * mono + # this is backwards because the arguments below are swapped side = 'left' if right else 'right' if mono == -1: -- cgit v1.2.1 From 5db1c6a48c9bf626ad171caab6085eec5b7408ea Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 15 May 2020 00:00:48 -0700 Subject: changed from large number error to different solution --- numpy/lib/function_base.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c7f3dc033..c266078cf 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4845,15 +4845,17 @@ def digitize(x, bins, right=False, edge=False): if edge: # if cannot make round trip, cannot use eps - if np.issubdtype(bins.dtype, _nx.int64): - if (bins != bins.astype(_nx.float64).astype(_nx.int64)).any(): - raise ValueError("bins have too large values to use" - "'edges=True'") - bins = bins.astype(_nx.float64) - if right: - bins[0] -= np.finfo(_nx.float64).eps * 2 * mono + if np.issubdtype(bins.dtype, _nx.integer): + if right: + bins[0] -= 1 + else: + bins[-1] += 1 else: - bins[-1] += np.finfo(_nx.float64).eps * 2 * mono + bins = bins.astype(_nx.float64) + if right: + bins[0] -= np.finfo(_nx.float64).eps * 2 * mono + else: + bins[-1] += np.finfo(_nx.float64).eps * 2 * mono # this is backwards because the arguments below are swapped side = 'left' if right else 'right' -- cgit v1.2.1 From 8c4ce9936ec6989fdf2b2374489f023681e329a3 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 15 May 2020 00:11:02 -0700 Subject: forgot to include monotonicity --- numpy/lib/function_base.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c266078cf..f629a8fdb 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4847,9 +4847,9 @@ def digitize(x, bins, right=False, edge=False): # if cannot make round trip, cannot use eps if np.issubdtype(bins.dtype, _nx.integer): if right: - bins[0] -= 1 + bins[0] -= mono else: - bins[-1] += 1 + bins[-1] += mono else: bins = bins.astype(_nx.float64) if right: -- cgit v1.2.1 From 5840165bd7db8628d0d5b318544943a28d799068 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 15 May 2020 09:56:38 -0700 Subject: simplified --- numpy/lib/function_base.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index f629a8fdb..3199c6169 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4768,9 +4768,9 @@ def digitize(x, bins, right=False, edge=False): case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. edge : bool, optional - Whether to include the last right edge if right == False or the first - left edge if right == True. If egde==True, the entire interval is - included that would otherwise not be for the first or last edge case. + Whether to include the last right edge if right==False or the first + left edge if right==True so that the whole interval from the least + to the greatest value of bins is covered. Returns ------- @@ -4786,7 +4786,7 @@ def digitize(x, bins, right=False, edge=False): See Also -------- - bincount, histogram, unique, searchsorted + bincount, histogram, unique, nextafter, searchsorted Notes ----- @@ -4844,18 +4844,15 @@ def digitize(x, bins, right=False, edge=False): raise ValueError("bins must be monotonically increasing or decreasing") if edge: - # if cannot make round trip, cannot use eps + # move first bin eps if right edge not included else move last bin + idx = 0 if right else -1 + # move bin down if going up and using right or going down and using + # left else move bin up + delta = -mono if right else mono if np.issubdtype(bins.dtype, _nx.integer): - if right: - bins[0] -= mono - else: - bins[-1] += mono + bins[idx] += delta else: - bins = bins.astype(_nx.float64) - if right: - bins[0] -= np.finfo(_nx.float64).eps * 2 * mono - else: - bins[-1] += np.finfo(_nx.float64).eps * 2 * mono + bins[idx] = np.nextafter(bins[idx], bins[idx] + delta) # this is backwards because the arguments below are swapped side = 'left' if right else 'right' -- cgit v1.2.1 From f292b95f153b37e6d6141848d2e806275b175836 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 15 May 2020 10:43:31 -0700 Subject: fixed simplify --- numpy/lib/function_base.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 3199c6169..e2f5cdd6f 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4844,11 +4844,16 @@ def digitize(x, bins, right=False, edge=False): raise ValueError("bins must be monotonically increasing or decreasing") if edge: - # move first bin eps if right edge not included else move last bin - idx = 0 if right else -1 - # move bin down if going up and using right or going down and using - # left else move bin up - delta = -mono if right else mono + # ========= ============= ============================ ===== ===== + # `right` order of bins returned index `i` satisfies delta index + # ========= ============= ============================ ===== ===== + # ``False`` increasing ``bins[i-1] <= x < bins[i]`` 1 -1 + # ``True`` increasing ``bins[i-1] < x <= bins[i]`` -1 0 + # ``False`` decreasing ``bins[i-1] > x >= bins[i]`` 1 0 + # ``True`` decreasing ``bins[i-1] >= x > bins[i]`` -1 -1 + # ========= ============= ============================ ===== ===== + delta = -1 if right else 1 + idx = 0 if delta != mono else -1 if np.issubdtype(bins.dtype, _nx.integer): bins[idx] += delta else: -- cgit v1.2.1 From d215c1f16c74a756c1b374a96a1abd0cac11b5d3 Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 15 May 2020 13:55:47 -0700 Subject: change != to == --- numpy/lib/function_base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index e2f5cdd6f..41caa805e 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4853,7 +4853,7 @@ def digitize(x, bins, right=False, edge=False): # ``True`` decreasing ``bins[i-1] >= x > bins[i]`` -1 -1 # ========= ============= ============================ ===== ===== delta = -1 if right else 1 - idx = 0 if delta != mono else -1 + idx = -1 if delta == mono else 0 if np.issubdtype(bins.dtype, _nx.integer): bins[idx] += delta else: -- cgit v1.2.1 From 4c4c058d125ae0a62979942ba155dfa372264071 Mon Sep 17 00:00:00 2001 From: mattip Date: Thu, 23 Jul 2020 13:00:25 +0300 Subject: Revert "Merge pull request #16248 from alexrockhill/edge" --- numpy/lib/function_base.py | 26 +++----------------------- 1 file changed, 3 insertions(+), 23 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 41caa805e..6ea9cc4de 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4733,12 +4733,12 @@ def append(arr, values, axis=None): return concatenate((arr, values), axis=axis) -def _digitize_dispatcher(x, bins, right=None, edge=None): +def _digitize_dispatcher(x, bins, right=None): return (x, bins) @array_function_dispatch(_digitize_dispatcher) -def digitize(x, bins, right=False, edge=False): +def digitize(x, bins, right=False): """ Return the indices of the bins to which each value in input array belongs. @@ -4767,10 +4767,6 @@ def digitize(x, bins, right=False, edge=False): does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. - edge : bool, optional - Whether to include the last right edge if right==False or the first - left edge if right==True so that the whole interval from the least - to the greatest value of bins is covered. Returns ------- @@ -4786,7 +4782,7 @@ def digitize(x, bins, right=False, edge=False): See Also -------- - bincount, histogram, unique, nextafter, searchsorted + bincount, histogram, unique, searchsorted Notes ----- @@ -4843,22 +4839,6 @@ def digitize(x, bins, right=False, edge=False): if mono == 0: raise ValueError("bins must be monotonically increasing or decreasing") - if edge: - # ========= ============= ============================ ===== ===== - # `right` order of bins returned index `i` satisfies delta index - # ========= ============= ============================ ===== ===== - # ``False`` increasing ``bins[i-1] <= x < bins[i]`` 1 -1 - # ``True`` increasing ``bins[i-1] < x <= bins[i]`` -1 0 - # ``False`` decreasing ``bins[i-1] > x >= bins[i]`` 1 0 - # ``True`` decreasing ``bins[i-1] >= x > bins[i]`` -1 -1 - # ========= ============= ============================ ===== ===== - delta = -1 if right else 1 - idx = -1 if delta == mono else 0 - if np.issubdtype(bins.dtype, _nx.integer): - bins[idx] += delta - else: - bins[idx] = np.nextafter(bins[idx], bins[idx] + delta) - # this is backwards because the arguments below are swapped side = 'left' if right else 'right' if mono == -1: -- cgit v1.2.1 From 593ef5fc5a02fbcd6eeb70a59684b3b21c9cc643 Mon Sep 17 00:00:00 2001 From: Bas van Beek <43369155+BvB93@users.noreply.github.com> Date: Tue, 4 Aug 2020 06:00:37 +0200 Subject: ENH: Speed up trim_zeros (#16911) * Added a benchmark for `trim_zeros()` * Improve the performance of `np.trim_zeros()` * Increase the variety of the tests Fall back to the old `np.trim_zeros()` implementation if an exception is encountered. Emit a `DeprecationWarning` in such case. * DEP,REL: Added a deprecation release note --- numpy/lib/function_base.py | 67 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 8 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 6ea9cc4de..cd8862c94 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -433,7 +433,7 @@ def asarray_chkfinite(a, dtype=None, order=None): By default, the data-type is inferred from the input data. order : {'C', 'F', 'A', 'K'}, optional Memory layout. 'A' and 'K' depend on the order of input array a. - 'C' row-major (C-style), + 'C' row-major (C-style), 'F' column-major (Fortran-style) memory representation. 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise 'K' (keep) preserve input order @@ -1624,6 +1624,57 @@ def trim_zeros(filt, trim='fb'): >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] + """ + try: + return _trim_zeros_new(filt, trim) + except Exception as ex: + # Numpy 1.20.0, 2020-07-31 + warning = DeprecationWarning( + "in the future trim_zeros will require a 1-D array as input " + "that is compatible with ndarray.astype(bool)" + ) + warning.__cause__ = ex + warnings.warn(warning, stacklevel=3) + + # Fall back to the old implementation if an exception is encountered + # Note that the same exception may or may not be raised here as well + return _trim_zeros_old(filt, trim) + + +def _trim_zeros_new(filt, trim='fb'): + """Newer optimized implementation of ``trim_zeros()``.""" + arr = np.asanyarray(filt).astype(bool, copy=False) + + if arr.ndim != 1: + raise ValueError('trim_zeros requires an array of exactly one dimension') + elif not len(arr): + return filt + + trim_upper = trim.upper() + first = last = None + + if 'F' in trim_upper: + first = arr.argmax() + # If `arr[first] is False` then so are all other elements + if not arr[first]: + return filt[:0] + + if 'B' in trim_upper: + last = len(arr) - arr[::-1].argmax() + # If `arr[last - 1] is False` then so are all other elements + if not arr[last - 1]: + return filt[:0] + + return filt[first:last] + + +def _trim_zeros_old(filt, trim='fb'): + """ + Older unoptimized implementation of ``trim_zeros()``. + + Used as fallback in case an exception is encountered + in ``_trim_zeros_new()``. + """ first = 0 trim = trim.upper() @@ -2546,11 +2597,11 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. - + Examples - -------- + -------- In this example we generate two random arrays, ``xarr`` and ``yarr``, and - compute the row-wise and column-wise Pearson correlation coefficients, + compute the row-wise and column-wise Pearson correlation coefficients, ``R``. Since ``rowvar`` is true by default, we first find the row-wise Pearson correlation coefficients between the variables of ``xarr``. @@ -2566,11 +2617,11 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): array([[ 1. , 0.99256089, -0.68080986], [ 0.99256089, 1. , -0.76492172], [-0.68080986, -0.76492172, 1. ]]) - - If we add another set of variables and observations ``yarr``, we can + + If we add another set of variables and observations ``yarr``, we can compute the row-wise Pearson correlation coefficients between the variables in ``xarr`` and ``yarr``. - + >>> yarr = rng.random((3, 3)) >>> yarr array([[0.45038594, 0.37079802, 0.92676499], @@ -2592,7 +2643,7 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): 1. ]]) Finally if we use the option ``rowvar=False``, the columns are now - being treated as the variables and we will find the column-wise Pearson + being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in ``xarr`` and ``yarr``. >>> R3 = np.corrcoef(xarr, yarr, rowvar=False) -- cgit v1.2.1 From 7127cdfb8553030ba317455c9f31fe4d7ed74e81 Mon Sep 17 00:00:00 2001 From: Bas van Beek Date: Tue, 11 Aug 2020 15:53:55 +0200 Subject: ENH: Use elementwise comparisons with 0 rather than boolean casting --- numpy/lib/function_base.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index cd8862c94..96e1c6de9 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1631,7 +1631,7 @@ def trim_zeros(filt, trim='fb'): # Numpy 1.20.0, 2020-07-31 warning = DeprecationWarning( "in the future trim_zeros will require a 1-D array as input " - "that is compatible with ndarray.astype(bool)" + "that supports elementwise comparisons with zero" ) warning.__cause__ = ex warnings.warn(warning, stacklevel=3) @@ -1643,7 +1643,11 @@ def trim_zeros(filt, trim='fb'): def _trim_zeros_new(filt, trim='fb'): """Newer optimized implementation of ``trim_zeros()``.""" - arr = np.asanyarray(filt).astype(bool, copy=False) + arr_any = np.asanyarray(filt) + with warnings.catch_warnings(): + # not all dtypes support elementwise comparisons with `0` (e.g. str) + warnings.simplefilter('error', FutureWarning) + arr = arr_any != 0 if arr_any.dtype != bool else arr_any if arr.ndim != 1: raise ValueError('trim_zeros requires an array of exactly one dimension') -- cgit v1.2.1 From e62d5d15f3b8df247dcb133eaaceb71f5f60d8c0 Mon Sep 17 00:00:00 2001 From: Bas van Beek Date: Tue, 11 Aug 2020 16:17:50 +0200 Subject: MAINT: Catching warnings is expensive; remove it --- numpy/lib/function_base.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 96e1c6de9..e9fe936e9 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1644,12 +1644,13 @@ def trim_zeros(filt, trim='fb'): def _trim_zeros_new(filt, trim='fb'): """Newer optimized implementation of ``trim_zeros()``.""" arr_any = np.asanyarray(filt) - with warnings.catch_warnings(): - # not all dtypes support elementwise comparisons with `0` (e.g. str) - warnings.simplefilter('error', FutureWarning) - arr = arr_any != 0 if arr_any.dtype != bool else arr_any + arr = arr_any != 0 if arr_any.dtype != bool else arr_any - if arr.ndim != 1: + if arr is False: + # not all dtypes support elementwise comparisons with `0` (e.g. str); + # they will return `False` instead + raise TypeError('elementwise comparison failed; unsupported data type') + elif arr.ndim != 1: raise ValueError('trim_zeros requires an array of exactly one dimension') elif not len(arr): return filt -- cgit v1.2.1 From a2b9c2d5b6637b040917c0a2ef393dae83f09ee3 Mon Sep 17 00:00:00 2001 From: peterbell10 Date: Wed, 12 Aug 2020 07:36:07 +0100 Subject: API, BUG: Raise error on complex input to i0 (#17062) * BUG, API: Raise error on complex input to np.i0 --- numpy/lib/function_base.py | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index cd8862c94..b530f0aa1 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -3193,25 +3193,18 @@ def i0(x): """ Modified Bessel function of the first kind, order 0. - Usually denoted :math:`I_0`. This function does broadcast, but will *not* - "up-cast" int dtype arguments unless accompanied by at least one float or - complex dtype argument (see Raises below). + Usually denoted :math:`I_0`. Parameters ---------- - x : array_like, dtype float or complex + x : array_like of float Argument of the Bessel function. Returns ------- - out : ndarray, shape = x.shape, dtype = x.dtype + out : ndarray, shape = x.shape, dtype = float The modified Bessel function evaluated at each of the elements of `x`. - Raises - ------ - TypeError: array cannot be safely cast to required type - If argument consists exclusively of int dtypes. - See Also -------- scipy.special.i0, scipy.special.iv, scipy.special.ive @@ -3241,12 +3234,16 @@ def i0(x): Examples -------- >>> np.i0(0.) - array(1.0) # may vary - >>> np.i0([0., 1. + 2j]) - array([ 1.00000000+0.j , 0.18785373+0.64616944j]) # may vary + array(1.0) + >>> np.i0([0, 1, 2, 3]) + array([1. , 1.26606588, 2.2795853 , 4.88079259]) """ x = np.asanyarray(x) + if x.dtype.kind == 'c': + raise TypeError("i0 not supported for complex values") + if x.dtype.kind != 'f': + x = x.astype(float) x = np.abs(x) return piecewise(x, [x <= 8.0], [_i0_1, _i0_2]) -- cgit v1.2.1 From f977f575d6263cac4703d809f57fe895415993ae Mon Sep 17 00:00:00 2001 From: Bas van Beek Date: Thu, 13 Aug 2020 15:15:56 +0200 Subject: MAINT: Issue the DeprecationWarning after creating the to-be returned array --- numpy/lib/function_base.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index e9fe936e9..8e25074ab 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1634,11 +1634,12 @@ def trim_zeros(filt, trim='fb'): "that supports elementwise comparisons with zero" ) warning.__cause__ = ex - warnings.warn(warning, stacklevel=3) - # Fall back to the old implementation if an exception is encountered - # Note that the same exception may or may not be raised here as well - return _trim_zeros_old(filt, trim) + # Fall back to the old implementation if an exception is encountered + # Note that the same exception may or may not be raised here as well + ret = _trim_zeros_old(filt, trim) + warnings.warn(warning, stacklevel=3) + return ret def _trim_zeros_new(filt, trim='fb'): -- cgit v1.2.1 From 4eae213d4bbe1b509ceff897db8f65be9c480d14 Mon Sep 17 00:00:00 2001 From: Kevin Sheppard Date: Thu, 20 Aug 2020 11:30:50 +0100 Subject: DOC: Fix spacing in vectorize doc Fix spacing that produced incorrect rendering --- numpy/lib/function_base.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 556227c0d..0db00a0f2 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1991,8 +1991,8 @@ class vectorize: .. versionadded:: 1.7.0 cache : bool, optional - If `True`, then cache the first function call that determines the number - of outputs if `otypes` is not provided. + If `True`, then cache the first function call that determines the number + of outputs if `otypes` is not provided. .. versionadded:: 1.7.0 -- cgit v1.2.1 From 051198414ba1e2c3e56919013d4d4372c34aa994 Mon Sep 17 00:00:00 2001 From: mattip Date: Thu, 27 Aug 2020 19:35:52 +0300 Subject: BUG: revert trim_zeros changes from gh-16911 --- numpy/lib/function_base.py | 56 ---------------------------------------------- 1 file changed, 56 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 0db00a0f2..710091de2 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1625,63 +1625,7 @@ def trim_zeros(filt, trim='fb'): [1, 2] """ - try: - return _trim_zeros_new(filt, trim) - except Exception as ex: - # Numpy 1.20.0, 2020-07-31 - warning = DeprecationWarning( - "in the future trim_zeros will require a 1-D array as input " - "that supports elementwise comparisons with zero" - ) - warning.__cause__ = ex - - # Fall back to the old implementation if an exception is encountered - # Note that the same exception may or may not be raised here as well - ret = _trim_zeros_old(filt, trim) - warnings.warn(warning, stacklevel=3) - return ret - - -def _trim_zeros_new(filt, trim='fb'): - """Newer optimized implementation of ``trim_zeros()``.""" - arr_any = np.asanyarray(filt) - arr = arr_any != 0 if arr_any.dtype != bool else arr_any - - if arr is False: - # not all dtypes support elementwise comparisons with `0` (e.g. str); - # they will return `False` instead - raise TypeError('elementwise comparison failed; unsupported data type') - elif arr.ndim != 1: - raise ValueError('trim_zeros requires an array of exactly one dimension') - elif not len(arr): - return filt - - trim_upper = trim.upper() - first = last = None - - if 'F' in trim_upper: - first = arr.argmax() - # If `arr[first] is False` then so are all other elements - if not arr[first]: - return filt[:0] - if 'B' in trim_upper: - last = len(arr) - arr[::-1].argmax() - # If `arr[last - 1] is False` then so are all other elements - if not arr[last - 1]: - return filt[:0] - - return filt[first:last] - - -def _trim_zeros_old(filt, trim='fb'): - """ - Older unoptimized implementation of ``trim_zeros()``. - - Used as fallback in case an exception is encountered - in ``_trim_zeros_new()``. - - """ first = 0 trim = trim.upper() if 'F' in trim: -- cgit v1.2.1 From 36ad0e43127240377692b9ca669db06c7fb153f7 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Mon, 31 Aug 2020 11:14:40 +0100 Subject: ENH: Make the window functions exactly symmetric This relies on the fact that `cos` is exactly symmetric around zero, but not around the floating-point approximation of `pi`. Closes gh-17169. --- numpy/lib/function_base.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 710091de2..f1ec38c5c 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -2733,8 +2733,8 @@ def blackman(M): return array([]) if M == 1: return ones(1, float) - n = arange(0, M) - return 0.42 - 0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) + n = arange(1-M, M, 2) + return 0.42 + 0.5*cos(pi*n/(M-1)) + 0.08*cos(2.0*pi*n/(M-1)) @set_module('numpy') @@ -2842,8 +2842,8 @@ def bartlett(M): return array([]) if M == 1: return ones(1, float) - n = arange(0, M) - return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0 - 2.0*n/(M-1)) + n = arange(1-M, M, 2) + return where(less_equal(n, 0), 1 + n/(M-1), 1 - n/(M-1)) @set_module('numpy') @@ -2946,8 +2946,8 @@ def hanning(M): return array([]) if M == 1: return ones(1, float) - n = arange(0, M) - return 0.5 - 0.5*cos(2.0*pi*n/(M-1)) + n = arange(1-M, M, 2) + return 0.5 + 0.5*cos(pi*n/(M-1)) @set_module('numpy') @@ -3046,8 +3046,8 @@ def hamming(M): return array([]) if M == 1: return ones(1, float) - n = arange(0, M) - return 0.54 - 0.46*cos(2.0*pi*n/(M-1)) + n = arange(1-M, M, 2) + return 0.54 + 0.46*cos(pi*n/(M-1)) ## Code from cephes for i0 -- cgit v1.2.1 From 8599fe0abc88f584ee45b54654833cdccefc3cd0 Mon Sep 17 00:00:00 2001 From: Albert Villanova del Moral <8515462+albertvillanova@users.noreply.github.com> Date: Fri, 4 Sep 2020 20:23:42 +0200 Subject: Fix docstring cross-referencing --- numpy/lib/function_base.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index f1ec38c5c..bd0f4c11b 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4229,9 +4229,9 @@ def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): See Also -------- - index_tricks.mgrid : Construct a multi-dimensional "meshgrid" + mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. - index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" + ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -- cgit v1.2.1 From fef19578d79dffd9310cc8d155c631bcfd1bcd9e Mon Sep 17 00:00:00 2001 From: Ross Barnowski Date: Wed, 9 Sep 2020 15:00:48 -0700 Subject: DOC: reformat meshgrid see also links --- numpy/lib/function_base.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index bd0f4c11b..c43b2fb53 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -4229,10 +4229,9 @@ def meshgrid(*xi, copy=True, sparse=False, indexing='xy'): See Also -------- - mgrid : Construct a multi-dimensional "meshgrid" - using indexing notation. - ogrid : Construct an open multi-dimensional "meshgrid" - using indexing notation. + mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. + ogrid : Construct an open multi-dimensional "meshgrid" using indexing + notation. Examples -------- -- cgit v1.2.1 From 60a1e10c4593736b188b38e7d7c51aefb213af6a Mon Sep 17 00:00:00 2001 From: Bradley Dice Date: Thu, 17 Sep 2020 03:06:41 -0500 Subject: DOC: Fix syntax errors in docstrings for versionchanged, versionadded (#17338) * DOC: Fix typos in versionchanged. --- numpy/lib/function_base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c43b2fb53..c7ddbdb8d 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1450,7 +1450,7 @@ def angle(z, deg=False): The counterclockwise angle from the positive real axis on the complex plane in the range ``(-pi, pi]``, with dtype as numpy.float64. - ..versionchanged:: 1.16.0 + .. versionchanged:: 1.16.0 This function works on subclasses of ndarray like `ma.array`. See Also -- cgit v1.2.1 From 156cd054e007b05d4ac4829e10a369d19dd2b0b1 Mon Sep 17 00:00:00 2001 From: Lisa Schwetlick Date: Fri, 9 Oct 2020 21:35:47 +0200 Subject: ENH: add dtype option to cov and corrcoef (#17456) Adds a keyword-only dtype parameter to correlate and coerrcoef to allow user to specify the dtype of the output. Co-authored-by: Eric Wieser Co-authored-by: Ross Barnowski --- numpy/lib/function_base.py | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index c7ddbdb8d..984f3086e 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -2268,13 +2268,13 @@ class vectorize: def _cov_dispatcher(m, y=None, rowvar=None, bias=None, ddof=None, - fweights=None, aweights=None): + fweights=None, aweights=None, *, dtype=None): return (m, y, fweights, aweights) @array_function_dispatch(_cov_dispatcher) def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, - aweights=None): + aweights=None, *, dtype=None): """ Estimate a covariance matrix, given data and weights. @@ -2325,6 +2325,11 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, weights can be used to assign probabilities to observation vectors. .. versionadded:: 1.10 + dtype : data-type, optional + Data-type of the result. By default, the return data-type will have + at least `numpy.float64` precision. + + .. versionadded:: 1.20 Returns ------- @@ -2400,13 +2405,16 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, if m.ndim > 2: raise ValueError("m has more than 2 dimensions") - if y is None: - dtype = np.result_type(m, np.float64) - else: + if y is not None: y = np.asarray(y) if y.ndim > 2: raise ValueError("y has more than 2 dimensions") - dtype = np.result_type(m, y, np.float64) + + if dtype is None: + if y is None: + dtype = np.result_type(m, np.float64) + else: + dtype = np.result_type(m, y, np.float64) X = array(m, ndmin=2, dtype=dtype) if not rowvar and X.shape[0] != 1: @@ -2486,12 +2494,14 @@ def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, return c.squeeze() -def _corrcoef_dispatcher(x, y=None, rowvar=None, bias=None, ddof=None): +def _corrcoef_dispatcher(x, y=None, rowvar=None, bias=None, ddof=None, *, + dtype=None): return (x, y) @array_function_dispatch(_corrcoef_dispatcher) -def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): +def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue, *, + dtype=None): """ Return Pearson product-moment correlation coefficients. @@ -2525,6 +2535,11 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): Has no effect, do not use. .. deprecated:: 1.10.0 + dtype : data-type, optional + Data-type of the result. By default, the return data-type will have + at least `numpy.float64` precision. + + .. versionadded:: 1.20 Returns ------- @@ -2616,7 +2631,7 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue): # 2015-03-15, 1.10 warnings.warn('bias and ddof have no effect and are deprecated', DeprecationWarning, stacklevel=3) - c = cov(x, y, rowvar) + c = cov(x, y, rowvar, dtype=dtype) try: d = diag(c) except ValueError: -- cgit v1.2.1 From fd821c8dc5e39879e684467e4326083822e7a796 Mon Sep 17 00:00:00 2001 From: David Stansby Date: Fri, 27 Nov 2020 20:41:50 +0000 Subject: Make it clearer that np.interp input must be monotonically increasing --- numpy/lib/function_base.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'numpy/lib/function_base.py') diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 984f3086e..696fe617b 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1290,7 +1290,7 @@ def _interp_dispatcher(x, xp, fp, left=None, right=None, period=None): @array_function_dispatch(_interp_dispatcher) def interp(x, xp, fp, left=None, right=None, period=None): """ - One-dimensional linear interpolation. + One-dimensional linear interpolation for monotonically increasing sample points. Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (`xp`, `fp`), evaluated at `x`. @@ -1337,8 +1337,8 @@ def interp(x, xp, fp, left=None, right=None, period=None): -------- scipy.interpolate - Notes - ----- + Warnings + -------- The x-coordinate sequence is expected to be increasing, but this is not explicitly enforced. However, if the sequence `xp` is non-increasing, interpolation results are meaningless. -- cgit v1.2.1