Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/core/numeric.py: 29%
487 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-03 06:39 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-03 06:39 +0000
1import functools
2import itertools
3import operator
4import sys
5import warnings
6import numbers
7import builtins
9import numpy as np
10from . import multiarray
11from .multiarray import (
12 fastCopyAndTranspose, ALLOW_THREADS,
13 BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE,
14 WRAP, arange, array, asarray, asanyarray, ascontiguousarray,
15 asfortranarray, broadcast, can_cast, compare_chararrays,
16 concatenate, copyto, dot, dtype, empty,
17 empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter,
18 fromstring, inner, lexsort, matmul, may_share_memory,
19 min_scalar_type, ndarray, nditer, nested_iters, promote_types,
20 putmask, result_type, set_numeric_ops, shares_memory, vdot, where,
21 zeros, normalize_axis_index, _get_promotion_state, _set_promotion_state,
22 _using_numpy2_behavior)
24from . import overrides
25from . import umath
26from . import shape_base
27from .overrides import set_array_function_like_doc, set_module
28from .umath import (multiply, invert, sin, PINF, NAN)
29from . import numerictypes
30from .numerictypes import longlong, intc, int_, float_, complex_, bool_
31from ..exceptions import ComplexWarning, TooHardError, AxisError
32from ._ufunc_config import errstate, _no_nep50_warning
34bitwise_not = invert
35ufunc = type(sin)
36newaxis = None
38array_function_dispatch = functools.partial(
39 overrides.array_function_dispatch, module='numpy')
42__all__ = [
43 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
44 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
45 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
46 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
47 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
48 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
49 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
50 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
51 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
52 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
53 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
54 'identity', 'allclose', 'compare_chararrays', 'putmask',
55 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN',
56 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS',
57 'BUFSIZE', 'ALLOW_THREADS', 'full', 'full_like',
58 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS',
59 'MAY_SHARE_EXACT', '_get_promotion_state', '_set_promotion_state',
60 '_using_numpy2_behavior']
63def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
64 return (a,)
67@array_function_dispatch(_zeros_like_dispatcher)
68def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
69 """
70 Return an array of zeros with the same shape and type as a given array.
72 Parameters
73 ----------
74 a : array_like
75 The shape and data-type of `a` define these same attributes of
76 the returned array.
77 dtype : data-type, optional
78 Overrides the data type of the result.
80 .. versionadded:: 1.6.0
81 order : {'C', 'F', 'A', or 'K'}, optional
82 Overrides the memory layout of the result. 'C' means C-order,
83 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
84 'C' otherwise. 'K' means match the layout of `a` as closely
85 as possible.
87 .. versionadded:: 1.6.0
88 subok : bool, optional.
89 If True, then the newly created array will use the sub-class
90 type of `a`, otherwise it will be a base-class array. Defaults
91 to True.
92 shape : int or sequence of ints, optional.
93 Overrides the shape of the result. If order='K' and the number of
94 dimensions is unchanged, will try to keep order, otherwise,
95 order='C' is implied.
97 .. versionadded:: 1.17.0
99 Returns
100 -------
101 out : ndarray
102 Array of zeros with the same shape and type as `a`.
104 See Also
105 --------
106 empty_like : Return an empty array with shape and type of input.
107 ones_like : Return an array of ones with shape and type of input.
108 full_like : Return a new array with shape of input filled with value.
109 zeros : Return a new array setting values to zero.
111 Examples
112 --------
113 >>> x = np.arange(6)
114 >>> x = x.reshape((2, 3))
115 >>> x
116 array([[0, 1, 2],
117 [3, 4, 5]])
118 >>> np.zeros_like(x)
119 array([[0, 0, 0],
120 [0, 0, 0]])
122 >>> y = np.arange(3, dtype=float)
123 >>> y
124 array([0., 1., 2.])
125 >>> np.zeros_like(y)
126 array([0., 0., 0.])
128 """
129 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
130 # needed instead of a 0 to get same result as zeros for string dtypes
131 z = zeros(1, dtype=res.dtype)
132 multiarray.copyto(res, z, casting='unsafe')
133 return res
136@set_array_function_like_doc
137@set_module('numpy')
138def ones(shape, dtype=None, order='C', *, like=None):
139 """
140 Return a new array of given shape and type, filled with ones.
142 Parameters
143 ----------
144 shape : int or sequence of ints
145 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
146 dtype : data-type, optional
147 The desired data-type for the array, e.g., `numpy.int8`. Default is
148 `numpy.float64`.
149 order : {'C', 'F'}, optional, default: C
150 Whether to store multi-dimensional data in row-major
151 (C-style) or column-major (Fortran-style) order in
152 memory.
153 ${ARRAY_FUNCTION_LIKE}
155 .. versionadded:: 1.20.0
157 Returns
158 -------
159 out : ndarray
160 Array of ones with the given shape, dtype, and order.
162 See Also
163 --------
164 ones_like : Return an array of ones with shape and type of input.
165 empty : Return a new uninitialized array.
166 zeros : Return a new array setting values to zero.
167 full : Return a new array of given shape filled with value.
170 Examples
171 --------
172 >>> np.ones(5)
173 array([1., 1., 1., 1., 1.])
175 >>> np.ones((5,), dtype=int)
176 array([1, 1, 1, 1, 1])
178 >>> np.ones((2, 1))
179 array([[1.],
180 [1.]])
182 >>> s = (2,2)
183 >>> np.ones(s)
184 array([[1., 1.],
185 [1., 1.]])
187 """
188 if like is not None:
189 return _ones_with_like(like, shape, dtype=dtype, order=order)
191 a = empty(shape, dtype, order)
192 multiarray.copyto(a, 1, casting='unsafe')
193 return a
196_ones_with_like = array_function_dispatch()(ones)
199def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
200 return (a,)
203@array_function_dispatch(_ones_like_dispatcher)
204def ones_like(a, dtype=None, order='K', subok=True, shape=None):
205 """
206 Return an array of ones with the same shape and type as a given array.
208 Parameters
209 ----------
210 a : array_like
211 The shape and data-type of `a` define these same attributes of
212 the returned array.
213 dtype : data-type, optional
214 Overrides the data type of the result.
216 .. versionadded:: 1.6.0
217 order : {'C', 'F', 'A', or 'K'}, optional
218 Overrides the memory layout of the result. 'C' means C-order,
219 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
220 'C' otherwise. 'K' means match the layout of `a` as closely
221 as possible.
223 .. versionadded:: 1.6.0
224 subok : bool, optional.
225 If True, then the newly created array will use the sub-class
226 type of `a`, otherwise it will be a base-class array. Defaults
227 to True.
228 shape : int or sequence of ints, optional.
229 Overrides the shape of the result. If order='K' and the number of
230 dimensions is unchanged, will try to keep order, otherwise,
231 order='C' is implied.
233 .. versionadded:: 1.17.0
235 Returns
236 -------
237 out : ndarray
238 Array of ones with the same shape and type as `a`.
240 See Also
241 --------
242 empty_like : Return an empty array with shape and type of input.
243 zeros_like : Return an array of zeros with shape and type of input.
244 full_like : Return a new array with shape of input filled with value.
245 ones : Return a new array setting values to one.
247 Examples
248 --------
249 >>> x = np.arange(6)
250 >>> x = x.reshape((2, 3))
251 >>> x
252 array([[0, 1, 2],
253 [3, 4, 5]])
254 >>> np.ones_like(x)
255 array([[1, 1, 1],
256 [1, 1, 1]])
258 >>> y = np.arange(3, dtype=float)
259 >>> y
260 array([0., 1., 2.])
261 >>> np.ones_like(y)
262 array([1., 1., 1.])
264 """
265 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
266 multiarray.copyto(res, 1, casting='unsafe')
267 return res
270def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, like=None):
271 return(like,)
274@set_array_function_like_doc
275@set_module('numpy')
276def full(shape, fill_value, dtype=None, order='C', *, like=None):
277 """
278 Return a new array of given shape and type, filled with `fill_value`.
280 Parameters
281 ----------
282 shape : int or sequence of ints
283 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
284 fill_value : scalar or array_like
285 Fill value.
286 dtype : data-type, optional
287 The desired data-type for the array The default, None, means
288 ``np.array(fill_value).dtype``.
289 order : {'C', 'F'}, optional
290 Whether to store multidimensional data in C- or Fortran-contiguous
291 (row- or column-wise) order in memory.
292 ${ARRAY_FUNCTION_LIKE}
294 .. versionadded:: 1.20.0
296 Returns
297 -------
298 out : ndarray
299 Array of `fill_value` with the given shape, dtype, and order.
301 See Also
302 --------
303 full_like : Return a new array with shape of input filled with value.
304 empty : Return a new uninitialized array.
305 ones : Return a new array setting values to one.
306 zeros : Return a new array setting values to zero.
308 Examples
309 --------
310 >>> np.full((2, 2), np.inf)
311 array([[inf, inf],
312 [inf, inf]])
313 >>> np.full((2, 2), 10)
314 array([[10, 10],
315 [10, 10]])
317 >>> np.full((2, 2), [1, 2])
318 array([[1, 2],
319 [1, 2]])
321 """
322 if like is not None:
323 return _full_with_like(
324 like, shape, fill_value, dtype=dtype, order=order)
326 if dtype is None:
327 fill_value = asarray(fill_value)
328 dtype = fill_value.dtype
329 a = empty(shape, dtype, order)
330 multiarray.copyto(a, fill_value, casting='unsafe')
331 return a
334_full_with_like = array_function_dispatch()(full)
337def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None):
338 return (a,)
341@array_function_dispatch(_full_like_dispatcher)
342def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
343 """
344 Return a full array with the same shape and type as a given array.
346 Parameters
347 ----------
348 a : array_like
349 The shape and data-type of `a` define these same attributes of
350 the returned array.
351 fill_value : array_like
352 Fill value.
353 dtype : data-type, optional
354 Overrides the data type of the result.
355 order : {'C', 'F', 'A', or 'K'}, optional
356 Overrides the memory layout of the result. 'C' means C-order,
357 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
358 'C' otherwise. 'K' means match the layout of `a` as closely
359 as possible.
360 subok : bool, optional.
361 If True, then the newly created array will use the sub-class
362 type of `a`, otherwise it will be a base-class array. Defaults
363 to True.
364 shape : int or sequence of ints, optional.
365 Overrides the shape of the result. If order='K' and the number of
366 dimensions is unchanged, will try to keep order, otherwise,
367 order='C' is implied.
369 .. versionadded:: 1.17.0
371 Returns
372 -------
373 out : ndarray
374 Array of `fill_value` with the same shape and type as `a`.
376 See Also
377 --------
378 empty_like : Return an empty array with shape and type of input.
379 ones_like : Return an array of ones with shape and type of input.
380 zeros_like : Return an array of zeros with shape and type of input.
381 full : Return a new array of given shape filled with value.
383 Examples
384 --------
385 >>> x = np.arange(6, dtype=int)
386 >>> np.full_like(x, 1)
387 array([1, 1, 1, 1, 1, 1])
388 >>> np.full_like(x, 0.1)
389 array([0, 0, 0, 0, 0, 0])
390 >>> np.full_like(x, 0.1, dtype=np.double)
391 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
392 >>> np.full_like(x, np.nan, dtype=np.double)
393 array([nan, nan, nan, nan, nan, nan])
395 >>> y = np.arange(6, dtype=np.double)
396 >>> np.full_like(y, 0.1)
397 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
399 >>> y = np.zeros([2, 2, 3], dtype=int)
400 >>> np.full_like(y, [0, 0, 255])
401 array([[[ 0, 0, 255],
402 [ 0, 0, 255]],
403 [[ 0, 0, 255],
404 [ 0, 0, 255]]])
405 """
406 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
407 multiarray.copyto(res, fill_value, casting='unsafe')
408 return res
411def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
412 return (a,)
415@array_function_dispatch(_count_nonzero_dispatcher)
416def count_nonzero(a, axis=None, *, keepdims=False):
417 """
418 Counts the number of non-zero values in the array ``a``.
420 The word "non-zero" is in reference to the Python 2.x
421 built-in method ``__nonzero__()`` (renamed ``__bool__()``
422 in Python 3.x) of Python objects that tests an object's
423 "truthfulness". For example, any number is considered
424 truthful if it is nonzero, whereas any string is considered
425 truthful if it is not the empty string. Thus, this function
426 (recursively) counts how many elements in ``a`` (and in
427 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
428 method evaluated to ``True``.
430 Parameters
431 ----------
432 a : array_like
433 The array for which to count non-zeros.
434 axis : int or tuple, optional
435 Axis or tuple of axes along which to count non-zeros.
436 Default is None, meaning that non-zeros will be counted
437 along a flattened version of ``a``.
439 .. versionadded:: 1.12.0
441 keepdims : bool, optional
442 If this is set to True, the axes that are counted are left
443 in the result as dimensions with size one. With this option,
444 the result will broadcast correctly against the input array.
446 .. versionadded:: 1.19.0
448 Returns
449 -------
450 count : int or array of int
451 Number of non-zero values in the array along a given axis.
452 Otherwise, the total number of non-zero values in the array
453 is returned.
455 See Also
456 --------
457 nonzero : Return the coordinates of all the non-zero values.
459 Examples
460 --------
461 >>> np.count_nonzero(np.eye(4))
462 4
463 >>> a = np.array([[0, 1, 7, 0],
464 ... [3, 0, 2, 19]])
465 >>> np.count_nonzero(a)
466 5
467 >>> np.count_nonzero(a, axis=0)
468 array([1, 1, 2, 1])
469 >>> np.count_nonzero(a, axis=1)
470 array([2, 3])
471 >>> np.count_nonzero(a, axis=1, keepdims=True)
472 array([[2],
473 [3]])
474 """
475 if axis is None and not keepdims:
476 return multiarray.count_nonzero(a)
478 a = asanyarray(a)
480 # TODO: this works around .astype(bool) not working properly (gh-9847)
481 if np.issubdtype(a.dtype, np.character):
482 a_bool = a != a.dtype.type()
483 else:
484 a_bool = a.astype(np.bool_, copy=False)
486 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
489@set_module('numpy')
490def isfortran(a):
491 """
492 Check if the array is Fortran contiguous but *not* C contiguous.
494 This function is obsolete and, because of changes due to relaxed stride
495 checking, its return value for the same array may differ for versions
496 of NumPy >= 1.10.0 and previous versions. If you only want to check if an
497 array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
499 Parameters
500 ----------
501 a : ndarray
502 Input array.
504 Returns
505 -------
506 isfortran : bool
507 Returns True if the array is Fortran contiguous but *not* C contiguous.
510 Examples
511 --------
513 np.array allows to specify whether the array is written in C-contiguous
514 order (last index varies the fastest), or FORTRAN-contiguous order in
515 memory (first index varies the fastest).
517 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
518 >>> a
519 array([[1, 2, 3],
520 [4, 5, 6]])
521 >>> np.isfortran(a)
522 False
524 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
525 >>> b
526 array([[1, 2, 3],
527 [4, 5, 6]])
528 >>> np.isfortran(b)
529 True
532 The transpose of a C-ordered array is a FORTRAN-ordered array.
534 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
535 >>> a
536 array([[1, 2, 3],
537 [4, 5, 6]])
538 >>> np.isfortran(a)
539 False
540 >>> b = a.T
541 >>> b
542 array([[1, 4],
543 [2, 5],
544 [3, 6]])
545 >>> np.isfortran(b)
546 True
548 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
550 >>> np.isfortran(np.array([1, 2], order='F'))
551 False
553 """
554 return a.flags.fnc
557def _argwhere_dispatcher(a):
558 return (a,)
561@array_function_dispatch(_argwhere_dispatcher)
562def argwhere(a):
563 """
564 Find the indices of array elements that are non-zero, grouped by element.
566 Parameters
567 ----------
568 a : array_like
569 Input data.
571 Returns
572 -------
573 index_array : (N, a.ndim) ndarray
574 Indices of elements that are non-zero. Indices are grouped by element.
575 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
576 non-zero items.
578 See Also
579 --------
580 where, nonzero
582 Notes
583 -----
584 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
585 but produces a result of the correct shape for a 0D array.
587 The output of ``argwhere`` is not suitable for indexing arrays.
588 For this purpose use ``nonzero(a)`` instead.
590 Examples
591 --------
592 >>> x = np.arange(6).reshape(2,3)
593 >>> x
594 array([[0, 1, 2],
595 [3, 4, 5]])
596 >>> np.argwhere(x>1)
597 array([[0, 2],
598 [1, 0],
599 [1, 1],
600 [1, 2]])
602 """
603 # nonzero does not behave well on 0d, so promote to 1d
604 if np.ndim(a) == 0:
605 a = shape_base.atleast_1d(a)
606 # then remove the added dimension
607 return argwhere(a)[:,:0]
608 return transpose(nonzero(a))
611def _flatnonzero_dispatcher(a):
612 return (a,)
615@array_function_dispatch(_flatnonzero_dispatcher)
616def flatnonzero(a):
617 """
618 Return indices that are non-zero in the flattened version of a.
620 This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
622 Parameters
623 ----------
624 a : array_like
625 Input data.
627 Returns
628 -------
629 res : ndarray
630 Output array, containing the indices of the elements of ``a.ravel()``
631 that are non-zero.
633 See Also
634 --------
635 nonzero : Return the indices of the non-zero elements of the input array.
636 ravel : Return a 1-D array containing the elements of the input array.
638 Examples
639 --------
640 >>> x = np.arange(-2, 3)
641 >>> x
642 array([-2, -1, 0, 1, 2])
643 >>> np.flatnonzero(x)
644 array([0, 1, 3, 4])
646 Use the indices of the non-zero elements as an index array to extract
647 these elements:
649 >>> x.ravel()[np.flatnonzero(x)]
650 array([-2, -1, 1, 2])
652 """
653 return np.nonzero(np.ravel(a))[0]
656def _correlate_dispatcher(a, v, mode=None):
657 return (a, v)
660@array_function_dispatch(_correlate_dispatcher)
661def correlate(a, v, mode='valid'):
662 r"""
663 Cross-correlation of two 1-dimensional sequences.
665 This function computes the correlation as generally defined in signal
666 processing texts:
668 .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
670 with a and v sequences being zero-padded where necessary and
671 :math:`\overline x` denoting complex conjugation.
673 Parameters
674 ----------
675 a, v : array_like
676 Input sequences.
677 mode : {'valid', 'same', 'full'}, optional
678 Refer to the `convolve` docstring. Note that the default
679 is 'valid', unlike `convolve`, which uses 'full'.
680 old_behavior : bool
681 `old_behavior` was removed in NumPy 1.10. If you need the old
682 behavior, use `multiarray.correlate`.
684 Returns
685 -------
686 out : ndarray
687 Discrete cross-correlation of `a` and `v`.
689 See Also
690 --------
691 convolve : Discrete, linear convolution of two one-dimensional sequences.
692 multiarray.correlate : Old, no conjugate, version of correlate.
693 scipy.signal.correlate : uses FFT which has superior performance on large arrays.
695 Notes
696 -----
697 The definition of correlation above is not unique and sometimes correlation
698 may be defined differently. Another common definition is:
700 .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
702 which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
704 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does
705 not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might
706 be preferable.
709 Examples
710 --------
711 >>> np.correlate([1, 2, 3], [0, 1, 0.5])
712 array([3.5])
713 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
714 array([2. , 3.5, 3. ])
715 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
716 array([0.5, 2. , 3.5, 3. , 0. ])
718 Using complex sequences:
720 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
721 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
723 Note that you get the time reversed, complex conjugated result
724 (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
725 places:
727 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
728 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
730 """
731 return multiarray.correlate2(a, v, mode)
734def _convolve_dispatcher(a, v, mode=None):
735 return (a, v)
738@array_function_dispatch(_convolve_dispatcher)
739def convolve(a, v, mode='full'):
740 """
741 Returns the discrete, linear convolution of two one-dimensional sequences.
743 The convolution operator is often seen in signal processing, where it
744 models the effect of a linear time-invariant system on a signal [1]_. In
745 probability theory, the sum of two independent random variables is
746 distributed according to the convolution of their individual
747 distributions.
749 If `v` is longer than `a`, the arrays are swapped before computation.
751 Parameters
752 ----------
753 a : (N,) array_like
754 First one-dimensional input array.
755 v : (M,) array_like
756 Second one-dimensional input array.
757 mode : {'full', 'valid', 'same'}, optional
758 'full':
759 By default, mode is 'full'. This returns the convolution
760 at each point of overlap, with an output shape of (N+M-1,). At
761 the end-points of the convolution, the signals do not overlap
762 completely, and boundary effects may be seen.
764 'same':
765 Mode 'same' returns output of length ``max(M, N)``. Boundary
766 effects are still visible.
768 'valid':
769 Mode 'valid' returns output of length
770 ``max(M, N) - min(M, N) + 1``. The convolution product is only given
771 for points where the signals overlap completely. Values outside
772 the signal boundary have no effect.
774 Returns
775 -------
776 out : ndarray
777 Discrete, linear convolution of `a` and `v`.
779 See Also
780 --------
781 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
782 Transform.
783 scipy.linalg.toeplitz : Used to construct the convolution operator.
784 polymul : Polynomial multiplication. Same output as convolve, but also
785 accepts poly1d objects as input.
787 Notes
788 -----
789 The discrete convolution operation is defined as
791 .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
793 It can be shown that a convolution :math:`x(t) * y(t)` in time/space
794 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
795 domain, after appropriate padding (padding is necessary to prevent
796 circular convolution). Since multiplication is more efficient (faster)
797 than convolution, the function `scipy.signal.fftconvolve` exploits the
798 FFT to calculate the convolution of large data-sets.
800 References
801 ----------
802 .. [1] Wikipedia, "Convolution",
803 https://en.wikipedia.org/wiki/Convolution
805 Examples
806 --------
807 Note how the convolution operator flips the second array
808 before "sliding" the two across one another:
810 >>> np.convolve([1, 2, 3], [0, 1, 0.5])
811 array([0. , 1. , 2.5, 4. , 1.5])
813 Only return the middle values of the convolution.
814 Contains boundary effects, where zeros are taken
815 into account:
817 >>> np.convolve([1,2,3],[0,1,0.5], 'same')
818 array([1. , 2.5, 4. ])
820 The two arrays are of the same length, so there
821 is only one position where they completely overlap:
823 >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
824 array([2.5])
826 """
827 a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
828 if (len(v) > len(a)):
829 a, v = v, a
830 if len(a) == 0:
831 raise ValueError('a cannot be empty')
832 if len(v) == 0:
833 raise ValueError('v cannot be empty')
834 return multiarray.correlate(a, v[::-1], mode)
837def _outer_dispatcher(a, b, out=None):
838 return (a, b, out)
841@array_function_dispatch(_outer_dispatcher)
842def outer(a, b, out=None):
843 """
844 Compute the outer product of two vectors.
846 Given two vectors `a` and `b` of length ``M`` and ``N``, repsectively,
847 the outer product [1]_ is::
849 [[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
850 [a_1*b_0 .
851 [ ... .
852 [a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
854 Parameters
855 ----------
856 a : (M,) array_like
857 First input vector. Input is flattened if
858 not already 1-dimensional.
859 b : (N,) array_like
860 Second input vector. Input is flattened if
861 not already 1-dimensional.
862 out : (M, N) ndarray, optional
863 A location where the result is stored
865 .. versionadded:: 1.9.0
867 Returns
868 -------
869 out : (M, N) ndarray
870 ``out[i, j] = a[i] * b[j]``
872 See also
873 --------
874 inner
875 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
876 ufunc.outer : A generalization to dimensions other than 1D and other
877 operations. ``np.multiply.outer(a.ravel(), b.ravel())``
878 is the equivalent.
879 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
880 is the equivalent.
882 References
883 ----------
884 .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
885 ed., Baltimore, MD, Johns Hopkins University Press, 1996,
886 pg. 8.
888 Examples
889 --------
890 Make a (*very* coarse) grid for computing a Mandelbrot set:
892 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
893 >>> rl
894 array([[-2., -1., 0., 1., 2.],
895 [-2., -1., 0., 1., 2.],
896 [-2., -1., 0., 1., 2.],
897 [-2., -1., 0., 1., 2.],
898 [-2., -1., 0., 1., 2.]])
899 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
900 >>> im
901 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
902 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
903 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
904 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
905 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
906 >>> grid = rl + im
907 >>> grid
908 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
909 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
910 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
911 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
912 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
914 An example using a "vector" of letters:
916 >>> x = np.array(['a', 'b', 'c'], dtype=object)
917 >>> np.outer(x, [1, 2, 3])
918 array([['a', 'aa', 'aaa'],
919 ['b', 'bb', 'bbb'],
920 ['c', 'cc', 'ccc']], dtype=object)
922 """
923 a = asarray(a)
924 b = asarray(b)
925 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
928def _tensordot_dispatcher(a, b, axes=None):
929 return (a, b)
932@array_function_dispatch(_tensordot_dispatcher)
933def tensordot(a, b, axes=2):
934 """
935 Compute tensor dot product along specified axes.
937 Given two tensors, `a` and `b`, and an array_like object containing
938 two array_like objects, ``(a_axes, b_axes)``, sum the products of
939 `a`'s and `b`'s elements (components) over the axes specified by
940 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
941 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
942 of `a` and the first ``N`` dimensions of `b` are summed over.
944 Parameters
945 ----------
946 a, b : array_like
947 Tensors to "dot".
949 axes : int or (2,) array_like
950 * integer_like
951 If an int N, sum over the last N axes of `a` and the first N axes
952 of `b` in order. The sizes of the corresponding axes must match.
953 * (2,) array_like
954 Or, a list of axes to be summed over, first sequence applying to `a`,
955 second to `b`. Both elements array_like must be of the same length.
957 Returns
958 -------
959 output : ndarray
960 The tensor dot product of the input.
962 See Also
963 --------
964 dot, einsum
966 Notes
967 -----
968 Three common use cases are:
969 * ``axes = 0`` : tensor product :math:`a\\otimes b`
970 * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
971 * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
973 When `axes` is integer_like, the sequence for evaluation will be: first
974 the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
975 Nth axis in `b` last.
977 When there is more than one axis to sum over - and they are not the last
978 (first) axes of `a` (`b`) - the argument `axes` should consist of
979 two sequences of the same length, with the first axis to sum over given
980 first in both sequences, the second axis second, and so forth.
982 The shape of the result consists of the non-contracted axes of the
983 first tensor, followed by the non-contracted axes of the second.
985 Examples
986 --------
987 A "traditional" example:
989 >>> a = np.arange(60.).reshape(3,4,5)
990 >>> b = np.arange(24.).reshape(4,3,2)
991 >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
992 >>> c.shape
993 (5, 2)
994 >>> c
995 array([[4400., 4730.],
996 [4532., 4874.],
997 [4664., 5018.],
998 [4796., 5162.],
999 [4928., 5306.]])
1000 >>> # A slower but equivalent way of computing the same...
1001 >>> d = np.zeros((5,2))
1002 >>> for i in range(5):
1003 ... for j in range(2):
1004 ... for k in range(3):
1005 ... for n in range(4):
1006 ... d[i,j] += a[k,n,i] * b[n,k,j]
1007 >>> c == d
1008 array([[ True, True],
1009 [ True, True],
1010 [ True, True],
1011 [ True, True],
1012 [ True, True]])
1014 An extended example taking advantage of the overloading of + and \\*:
1016 >>> a = np.array(range(1, 9))
1017 >>> a.shape = (2, 2, 2)
1018 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1019 >>> A.shape = (2, 2)
1020 >>> a; A
1021 array([[[1, 2],
1022 [3, 4]],
1023 [[5, 6],
1024 [7, 8]]])
1025 array([['a', 'b'],
1026 ['c', 'd']], dtype=object)
1028 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1029 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1031 >>> np.tensordot(a, A, 1)
1032 array([[['acc', 'bdd'],
1033 ['aaacccc', 'bbbdddd']],
1034 [['aaaaacccccc', 'bbbbbdddddd'],
1035 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1037 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1038 array([[[[['a', 'b'],
1039 ['c', 'd']],
1040 ...
1042 >>> np.tensordot(a, A, (0, 1))
1043 array([[['abbbbb', 'cddddd'],
1044 ['aabbbbbb', 'ccdddddd']],
1045 [['aaabbbbbbb', 'cccddddddd'],
1046 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1048 >>> np.tensordot(a, A, (2, 1))
1049 array([[['abb', 'cdd'],
1050 ['aaabbbb', 'cccdddd']],
1051 [['aaaaabbbbbb', 'cccccdddddd'],
1052 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1054 >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1055 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1057 >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1058 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1060 """
1061 try:
1062 iter(axes)
1063 except Exception:
1064 axes_a = list(range(-axes, 0))
1065 axes_b = list(range(0, axes))
1066 else:
1067 axes_a, axes_b = axes
1068 try:
1069 na = len(axes_a)
1070 axes_a = list(axes_a)
1071 except TypeError:
1072 axes_a = [axes_a]
1073 na = 1
1074 try:
1075 nb = len(axes_b)
1076 axes_b = list(axes_b)
1077 except TypeError:
1078 axes_b = [axes_b]
1079 nb = 1
1081 a, b = asarray(a), asarray(b)
1082 as_ = a.shape
1083 nda = a.ndim
1084 bs = b.shape
1085 ndb = b.ndim
1086 equal = True
1087 if na != nb:
1088 equal = False
1089 else:
1090 for k in range(na):
1091 if as_[axes_a[k]] != bs[axes_b[k]]:
1092 equal = False
1093 break
1094 if axes_a[k] < 0:
1095 axes_a[k] += nda
1096 if axes_b[k] < 0:
1097 axes_b[k] += ndb
1098 if not equal:
1099 raise ValueError("shape-mismatch for sum")
1101 # Move the axes to sum over to the end of "a"
1102 # and to the front of "b"
1103 notin = [k for k in range(nda) if k not in axes_a]
1104 newaxes_a = notin + axes_a
1105 N2 = 1
1106 for axis in axes_a:
1107 N2 *= as_[axis]
1108 newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
1109 olda = [as_[axis] for axis in notin]
1111 notin = [k for k in range(ndb) if k not in axes_b]
1112 newaxes_b = axes_b + notin
1113 N2 = 1
1114 for axis in axes_b:
1115 N2 *= bs[axis]
1116 newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
1117 oldb = [bs[axis] for axis in notin]
1119 at = a.transpose(newaxes_a).reshape(newshape_a)
1120 bt = b.transpose(newaxes_b).reshape(newshape_b)
1121 res = dot(at, bt)
1122 return res.reshape(olda + oldb)
1125def _roll_dispatcher(a, shift, axis=None):
1126 return (a,)
1129@array_function_dispatch(_roll_dispatcher)
1130def roll(a, shift, axis=None):
1131 """
1132 Roll array elements along a given axis.
1134 Elements that roll beyond the last position are re-introduced at
1135 the first.
1137 Parameters
1138 ----------
1139 a : array_like
1140 Input array.
1141 shift : int or tuple of ints
1142 The number of places by which elements are shifted. If a tuple,
1143 then `axis` must be a tuple of the same size, and each of the
1144 given axes is shifted by the corresponding number. If an int
1145 while `axis` is a tuple of ints, then the same value is used for
1146 all given axes.
1147 axis : int or tuple of ints, optional
1148 Axis or axes along which elements are shifted. By default, the
1149 array is flattened before shifting, after which the original
1150 shape is restored.
1152 Returns
1153 -------
1154 res : ndarray
1155 Output array, with the same shape as `a`.
1157 See Also
1158 --------
1159 rollaxis : Roll the specified axis backwards, until it lies in a
1160 given position.
1162 Notes
1163 -----
1164 .. versionadded:: 1.12.0
1166 Supports rolling over multiple dimensions simultaneously.
1168 Examples
1169 --------
1170 >>> x = np.arange(10)
1171 >>> np.roll(x, 2)
1172 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
1173 >>> np.roll(x, -2)
1174 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
1176 >>> x2 = np.reshape(x, (2, 5))
1177 >>> x2
1178 array([[0, 1, 2, 3, 4],
1179 [5, 6, 7, 8, 9]])
1180 >>> np.roll(x2, 1)
1181 array([[9, 0, 1, 2, 3],
1182 [4, 5, 6, 7, 8]])
1183 >>> np.roll(x2, -1)
1184 array([[1, 2, 3, 4, 5],
1185 [6, 7, 8, 9, 0]])
1186 >>> np.roll(x2, 1, axis=0)
1187 array([[5, 6, 7, 8, 9],
1188 [0, 1, 2, 3, 4]])
1189 >>> np.roll(x2, -1, axis=0)
1190 array([[5, 6, 7, 8, 9],
1191 [0, 1, 2, 3, 4]])
1192 >>> np.roll(x2, 1, axis=1)
1193 array([[4, 0, 1, 2, 3],
1194 [9, 5, 6, 7, 8]])
1195 >>> np.roll(x2, -1, axis=1)
1196 array([[1, 2, 3, 4, 0],
1197 [6, 7, 8, 9, 5]])
1198 >>> np.roll(x2, (1, 1), axis=(1, 0))
1199 array([[9, 5, 6, 7, 8],
1200 [4, 0, 1, 2, 3]])
1201 >>> np.roll(x2, (2, 1), axis=(1, 0))
1202 array([[8, 9, 5, 6, 7],
1203 [3, 4, 0, 1, 2]])
1205 """
1206 a = asanyarray(a)
1207 if axis is None:
1208 return roll(a.ravel(), shift, 0).reshape(a.shape)
1210 else:
1211 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1212 broadcasted = broadcast(shift, axis)
1213 if broadcasted.ndim > 1:
1214 raise ValueError(
1215 "'shift' and 'axis' should be scalars or 1D sequences")
1216 shifts = {ax: 0 for ax in range(a.ndim)}
1217 for sh, ax in broadcasted:
1218 shifts[ax] += sh
1220 rolls = [((slice(None), slice(None)),)] * a.ndim
1221 for ax, offset in shifts.items():
1222 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
1223 if offset:
1224 # (original, result), (original, result)
1225 rolls[ax] = ((slice(None, -offset), slice(offset, None)),
1226 (slice(-offset, None), slice(None, offset)))
1228 result = empty_like(a)
1229 for indices in itertools.product(*rolls):
1230 arr_index, res_index = zip(*indices)
1231 result[res_index] = a[arr_index]
1233 return result
1236def _rollaxis_dispatcher(a, axis, start=None):
1237 return (a,)
1240@array_function_dispatch(_rollaxis_dispatcher)
1241def rollaxis(a, axis, start=0):
1242 """
1243 Roll the specified axis backwards, until it lies in a given position.
1245 This function continues to be supported for backward compatibility, but you
1246 should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1247 1.11.
1249 Parameters
1250 ----------
1251 a : ndarray
1252 Input array.
1253 axis : int
1254 The axis to be rolled. The positions of the other axes do not
1255 change relative to one another.
1256 start : int, optional
1257 When ``start <= axis``, the axis is rolled back until it lies in
1258 this position. When ``start > axis``, the axis is rolled until it
1259 lies before this position. The default, 0, results in a "complete"
1260 roll. The following table describes how negative values of ``start``
1261 are interpreted:
1263 .. table::
1264 :align: left
1266 +-------------------+----------------------+
1267 | ``start`` | Normalized ``start`` |
1268 +===================+======================+
1269 | ``-(arr.ndim+1)`` | raise ``AxisError`` |
1270 +-------------------+----------------------+
1271 | ``-arr.ndim`` | 0 |
1272 +-------------------+----------------------+
1273 | |vdots| | |vdots| |
1274 +-------------------+----------------------+
1275 | ``-1`` | ``arr.ndim-1`` |
1276 +-------------------+----------------------+
1277 | ``0`` | ``0`` |
1278 +-------------------+----------------------+
1279 | |vdots| | |vdots| |
1280 +-------------------+----------------------+
1281 | ``arr.ndim`` | ``arr.ndim`` |
1282 +-------------------+----------------------+
1283 | ``arr.ndim + 1`` | raise ``AxisError`` |
1284 +-------------------+----------------------+
1286 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
1288 Returns
1289 -------
1290 res : ndarray
1291 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
1292 NumPy versions a view of `a` is returned only if the order of the
1293 axes is changed, otherwise the input array is returned.
1295 See Also
1296 --------
1297 moveaxis : Move array axes to new positions.
1298 roll : Roll the elements of an array by a number of positions along a
1299 given axis.
1301 Examples
1302 --------
1303 >>> a = np.ones((3,4,5,6))
1304 >>> np.rollaxis(a, 3, 1).shape
1305 (3, 6, 4, 5)
1306 >>> np.rollaxis(a, 2).shape
1307 (5, 3, 4, 6)
1308 >>> np.rollaxis(a, 1, 4).shape
1309 (3, 5, 6, 4)
1311 """
1312 n = a.ndim
1313 axis = normalize_axis_index(axis, n)
1314 if start < 0:
1315 start += n
1316 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1317 if not (0 <= start < n + 1):
1318 raise AxisError(msg % ('start', -n, 'start', n + 1, start))
1319 if axis < start:
1320 # it's been removed
1321 start -= 1
1322 if axis == start:
1323 return a[...]
1324 axes = list(range(0, n))
1325 axes.remove(axis)
1326 axes.insert(start, axis)
1327 return a.transpose(axes)
1330def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
1331 """
1332 Normalizes an axis argument into a tuple of non-negative integer axes.
1334 This handles shorthands such as ``1`` and converts them to ``(1,)``,
1335 as well as performing the handling of negative indices covered by
1336 `normalize_axis_index`.
1338 By default, this forbids axes from being specified multiple times.
1340 Used internally by multi-axis-checking logic.
1342 .. versionadded:: 1.13.0
1344 Parameters
1345 ----------
1346 axis : int, iterable of int
1347 The un-normalized index or indices of the axis.
1348 ndim : int
1349 The number of dimensions of the array that `axis` should be normalized
1350 against.
1351 argname : str, optional
1352 A prefix to put before the error message, typically the name of the
1353 argument.
1354 allow_duplicate : bool, optional
1355 If False, the default, disallow an axis from being specified twice.
1357 Returns
1358 -------
1359 normalized_axes : tuple of int
1360 The normalized axis index, such that `0 <= normalized_axis < ndim`
1362 Raises
1363 ------
1364 AxisError
1365 If any axis provided is out of range
1366 ValueError
1367 If an axis is repeated
1369 See also
1370 --------
1371 normalize_axis_index : normalizing a single scalar axis
1372 """
1373 # Optimization to speed-up the most common cases.
1374 if type(axis) not in (tuple, list):
1375 try:
1376 axis = [operator.index(axis)]
1377 except TypeError:
1378 pass
1379 # Going via an iterator directly is slower than via list comprehension.
1380 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
1381 if not allow_duplicate and len(set(axis)) != len(axis):
1382 if argname:
1383 raise ValueError('repeated axis in `{}` argument'.format(argname))
1384 else:
1385 raise ValueError('repeated axis')
1386 return axis
1389def _moveaxis_dispatcher(a, source, destination):
1390 return (a,)
1393@array_function_dispatch(_moveaxis_dispatcher)
1394def moveaxis(a, source, destination):
1395 """
1396 Move axes of an array to new positions.
1398 Other axes remain in their original order.
1400 .. versionadded:: 1.11.0
1402 Parameters
1403 ----------
1404 a : np.ndarray
1405 The array whose axes should be reordered.
1406 source : int or sequence of int
1407 Original positions of the axes to move. These must be unique.
1408 destination : int or sequence of int
1409 Destination positions for each of the original axes. These must also be
1410 unique.
1412 Returns
1413 -------
1414 result : np.ndarray
1415 Array with moved axes. This array is a view of the input array.
1417 See Also
1418 --------
1419 transpose : Permute the dimensions of an array.
1420 swapaxes : Interchange two axes of an array.
1422 Examples
1423 --------
1424 >>> x = np.zeros((3, 4, 5))
1425 >>> np.moveaxis(x, 0, -1).shape
1426 (4, 5, 3)
1427 >>> np.moveaxis(x, -1, 0).shape
1428 (5, 3, 4)
1430 These all achieve the same result:
1432 >>> np.transpose(x).shape
1433 (5, 4, 3)
1434 >>> np.swapaxes(x, 0, -1).shape
1435 (5, 4, 3)
1436 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
1437 (5, 4, 3)
1438 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
1439 (5, 4, 3)
1441 """
1442 try:
1443 # allow duck-array types if they define transpose
1444 transpose = a.transpose
1445 except AttributeError:
1446 a = asarray(a)
1447 transpose = a.transpose
1449 source = normalize_axis_tuple(source, a.ndim, 'source')
1450 destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1451 if len(source) != len(destination):
1452 raise ValueError('`source` and `destination` arguments must have '
1453 'the same number of elements')
1455 order = [n for n in range(a.ndim) if n not in source]
1457 for dest, src in sorted(zip(destination, source)):
1458 order.insert(dest, src)
1460 result = transpose(order)
1461 return result
1464def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
1465 return (a, b)
1468@array_function_dispatch(_cross_dispatcher)
1469def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
1470 """
1471 Return the cross product of two (arrays of) vectors.
1473 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
1474 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
1475 are defined by the last axis of `a` and `b` by default, and these axes
1476 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
1477 2, the third component of the input vector is assumed to be zero and the
1478 cross product calculated accordingly. In cases where both input vectors
1479 have dimension 2, the z-component of the cross product is returned.
1481 Parameters
1482 ----------
1483 a : array_like
1484 Components of the first vector(s).
1485 b : array_like
1486 Components of the second vector(s).
1487 axisa : int, optional
1488 Axis of `a` that defines the vector(s). By default, the last axis.
1489 axisb : int, optional
1490 Axis of `b` that defines the vector(s). By default, the last axis.
1491 axisc : int, optional
1492 Axis of `c` containing the cross product vector(s). Ignored if
1493 both input vectors have dimension 2, as the return is scalar.
1494 By default, the last axis.
1495 axis : int, optional
1496 If defined, the axis of `a`, `b` and `c` that defines the vector(s)
1497 and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
1499 Returns
1500 -------
1501 c : ndarray
1502 Vector cross product(s).
1504 Raises
1505 ------
1506 ValueError
1507 When the dimension of the vector(s) in `a` and/or `b` does not
1508 equal 2 or 3.
1510 See Also
1511 --------
1512 inner : Inner product
1513 outer : Outer product.
1514 ix_ : Construct index arrays.
1516 Notes
1517 -----
1518 .. versionadded:: 1.9.0
1520 Supports full broadcasting of the inputs.
1522 Examples
1523 --------
1524 Vector cross-product.
1526 >>> x = [1, 2, 3]
1527 >>> y = [4, 5, 6]
1528 >>> np.cross(x, y)
1529 array([-3, 6, -3])
1531 One vector with dimension 2.
1533 >>> x = [1, 2]
1534 >>> y = [4, 5, 6]
1535 >>> np.cross(x, y)
1536 array([12, -6, -3])
1538 Equivalently:
1540 >>> x = [1, 2, 0]
1541 >>> y = [4, 5, 6]
1542 >>> np.cross(x, y)
1543 array([12, -6, -3])
1545 Both vectors with dimension 2.
1547 >>> x = [1,2]
1548 >>> y = [4,5]
1549 >>> np.cross(x, y)
1550 array(-3)
1552 Multiple vector cross-products. Note that the direction of the cross
1553 product vector is defined by the *right-hand rule*.
1555 >>> x = np.array([[1,2,3], [4,5,6]])
1556 >>> y = np.array([[4,5,6], [1,2,3]])
1557 >>> np.cross(x, y)
1558 array([[-3, 6, -3],
1559 [ 3, -6, 3]])
1561 The orientation of `c` can be changed using the `axisc` keyword.
1563 >>> np.cross(x, y, axisc=0)
1564 array([[-3, 3],
1565 [ 6, -6],
1566 [-3, 3]])
1568 Change the vector definition of `x` and `y` using `axisa` and `axisb`.
1570 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
1571 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
1572 >>> np.cross(x, y)
1573 array([[ -6, 12, -6],
1574 [ 0, 0, 0],
1575 [ 6, -12, 6]])
1576 >>> np.cross(x, y, axisa=0, axisb=0)
1577 array([[-24, 48, -24],
1578 [-30, 60, -30],
1579 [-36, 72, -36]])
1581 """
1582 if axis is not None:
1583 axisa, axisb, axisc = (axis,) * 3
1584 a = asarray(a)
1585 b = asarray(b)
1586 # Check axisa and axisb are within bounds
1587 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
1588 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
1590 # Move working axis to the end of the shape
1591 a = moveaxis(a, axisa, -1)
1592 b = moveaxis(b, axisb, -1)
1593 msg = ("incompatible dimensions for cross product\n"
1594 "(dimension must be 2 or 3)")
1595 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1596 raise ValueError(msg)
1598 # Create the output array
1599 shape = broadcast(a[..., 0], b[..., 0]).shape
1600 if a.shape[-1] == 3 or b.shape[-1] == 3:
1601 shape += (3,)
1602 # Check axisc is within bounds
1603 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
1604 dtype = promote_types(a.dtype, b.dtype)
1605 cp = empty(shape, dtype)
1607 # recast arrays as dtype
1608 a = a.astype(dtype)
1609 b = b.astype(dtype)
1611 # create local aliases for readability
1612 a0 = a[..., 0]
1613 a1 = a[..., 1]
1614 if a.shape[-1] == 3:
1615 a2 = a[..., 2]
1616 b0 = b[..., 0]
1617 b1 = b[..., 1]
1618 if b.shape[-1] == 3:
1619 b2 = b[..., 2]
1620 if cp.ndim != 0 and cp.shape[-1] == 3:
1621 cp0 = cp[..., 0]
1622 cp1 = cp[..., 1]
1623 cp2 = cp[..., 2]
1625 if a.shape[-1] == 2:
1626 if b.shape[-1] == 2:
1627 # a0 * b1 - a1 * b0
1628 multiply(a0, b1, out=cp)
1629 cp -= a1 * b0
1630 return cp
1631 else:
1632 assert b.shape[-1] == 3
1633 # cp0 = a1 * b2 - 0 (a2 = 0)
1634 # cp1 = 0 - a0 * b2 (a2 = 0)
1635 # cp2 = a0 * b1 - a1 * b0
1636 multiply(a1, b2, out=cp0)
1637 multiply(a0, b2, out=cp1)
1638 negative(cp1, out=cp1)
1639 multiply(a0, b1, out=cp2)
1640 cp2 -= a1 * b0
1641 else:
1642 assert a.shape[-1] == 3
1643 if b.shape[-1] == 3:
1644 # cp0 = a1 * b2 - a2 * b1
1645 # cp1 = a2 * b0 - a0 * b2
1646 # cp2 = a0 * b1 - a1 * b0
1647 multiply(a1, b2, out=cp0)
1648 tmp = array(a2 * b1)
1649 cp0 -= tmp
1650 multiply(a2, b0, out=cp1)
1651 multiply(a0, b2, out=tmp)
1652 cp1 -= tmp
1653 multiply(a0, b1, out=cp2)
1654 multiply(a1, b0, out=tmp)
1655 cp2 -= tmp
1656 else:
1657 assert b.shape[-1] == 2
1658 # cp0 = 0 - a2 * b1 (b2 = 0)
1659 # cp1 = a2 * b0 - 0 (b2 = 0)
1660 # cp2 = a0 * b1 - a1 * b0
1661 multiply(a2, b1, out=cp0)
1662 negative(cp0, out=cp0)
1663 multiply(a2, b0, out=cp1)
1664 multiply(a0, b1, out=cp2)
1665 cp2 -= a1 * b0
1667 return moveaxis(cp, -1, axisc)
1670little_endian = (sys.byteorder == 'little')
1673@set_module('numpy')
1674def indices(dimensions, dtype=int, sparse=False):
1675 """
1676 Return an array representing the indices of a grid.
1678 Compute an array where the subarrays contain index values 0, 1, ...
1679 varying only along the corresponding axis.
1681 Parameters
1682 ----------
1683 dimensions : sequence of ints
1684 The shape of the grid.
1685 dtype : dtype, optional
1686 Data type of the result.
1687 sparse : boolean, optional
1688 Return a sparse representation of the grid instead of a dense
1689 representation. Default is False.
1691 .. versionadded:: 1.17
1693 Returns
1694 -------
1695 grid : one ndarray or tuple of ndarrays
1696 If sparse is False:
1697 Returns one array of grid indices,
1698 ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1699 If sparse is True:
1700 Returns a tuple of arrays, with
1701 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1702 dimensions[i] in the ith place
1704 See Also
1705 --------
1706 mgrid, ogrid, meshgrid
1708 Notes
1709 -----
1710 The output shape in the dense case is obtained by prepending the number
1711 of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
1712 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
1713 ``(N, r0, ..., rN-1)``.
1715 The subarrays ``grid[k]`` contains the N-D array of indices along the
1716 ``k-th`` axis. Explicitly::
1718 grid[k, i0, i1, ..., iN-1] = ik
1720 Examples
1721 --------
1722 >>> grid = np.indices((2, 3))
1723 >>> grid.shape
1724 (2, 2, 3)
1725 >>> grid[0] # row indices
1726 array([[0, 0, 0],
1727 [1, 1, 1]])
1728 >>> grid[1] # column indices
1729 array([[0, 1, 2],
1730 [0, 1, 2]])
1732 The indices can be used as an index into an array.
1734 >>> x = np.arange(20).reshape(5, 4)
1735 >>> row, col = np.indices((2, 3))
1736 >>> x[row, col]
1737 array([[0, 1, 2],
1738 [4, 5, 6]])
1740 Note that it would be more straightforward in the above example to
1741 extract the required elements directly with ``x[:2, :3]``.
1743 If sparse is set to true, the grid will be returned in a sparse
1744 representation.
1746 >>> i, j = np.indices((2, 3), sparse=True)
1747 >>> i.shape
1748 (2, 1)
1749 >>> j.shape
1750 (1, 3)
1751 >>> i # row indices
1752 array([[0],
1753 [1]])
1754 >>> j # column indices
1755 array([[0, 1, 2]])
1757 """
1758 dimensions = tuple(dimensions)
1759 N = len(dimensions)
1760 shape = (1,)*N
1761 if sparse:
1762 res = tuple()
1763 else:
1764 res = empty((N,)+dimensions, dtype=dtype)
1765 for i, dim in enumerate(dimensions):
1766 idx = arange(dim, dtype=dtype).reshape(
1767 shape[:i] + (dim,) + shape[i+1:]
1768 )
1769 if sparse:
1770 res = res + (idx,)
1771 else:
1772 res[i] = idx
1773 return res
1776@set_array_function_like_doc
1777@set_module('numpy')
1778def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
1779 """
1780 Construct an array by executing a function over each coordinate.
1782 The resulting array therefore has a value ``fn(x, y, z)`` at
1783 coordinate ``(x, y, z)``.
1785 Parameters
1786 ----------
1787 function : callable
1788 The function is called with N parameters, where N is the rank of
1789 `shape`. Each parameter represents the coordinates of the array
1790 varying along a specific axis. For example, if `shape`
1791 were ``(2, 2)``, then the parameters would be
1792 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
1793 shape : (N,) tuple of ints
1794 Shape of the output array, which also determines the shape of
1795 the coordinate arrays passed to `function`.
1796 dtype : data-type, optional
1797 Data-type of the coordinate arrays passed to `function`.
1798 By default, `dtype` is float.
1799 ${ARRAY_FUNCTION_LIKE}
1801 .. versionadded:: 1.20.0
1803 Returns
1804 -------
1805 fromfunction : any
1806 The result of the call to `function` is passed back directly.
1807 Therefore the shape of `fromfunction` is completely determined by
1808 `function`. If `function` returns a scalar value, the shape of
1809 `fromfunction` would not match the `shape` parameter.
1811 See Also
1812 --------
1813 indices, meshgrid
1815 Notes
1816 -----
1817 Keywords other than `dtype` and `like` are passed to `function`.
1819 Examples
1820 --------
1821 >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
1822 array([[0., 0.],
1823 [1., 1.]])
1825 >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
1826 array([[0., 1.],
1827 [0., 1.]])
1829 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
1830 array([[ True, False, False],
1831 [False, True, False],
1832 [False, False, True]])
1834 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
1835 array([[0, 1, 2],
1836 [1, 2, 3],
1837 [2, 3, 4]])
1839 """
1840 if like is not None:
1841 return _fromfunction_with_like(
1842 like, function, shape, dtype=dtype, **kwargs)
1844 args = indices(shape, dtype=dtype)
1845 return function(*args, **kwargs)
1848_fromfunction_with_like = array_function_dispatch()(fromfunction)
1851def _frombuffer(buf, dtype, shape, order):
1852 return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
1855@set_module('numpy')
1856def isscalar(element):
1857 """
1858 Returns True if the type of `element` is a scalar type.
1860 Parameters
1861 ----------
1862 element : any
1863 Input argument, can be of any type and shape.
1865 Returns
1866 -------
1867 val : bool
1868 True if `element` is a scalar type, False if it is not.
1870 See Also
1871 --------
1872 ndim : Get the number of dimensions of an array
1874 Notes
1875 -----
1876 If you need a stricter way to identify a *numerical* scalar, use
1877 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
1878 non-numerical elements such as strings.
1880 In most cases ``np.ndim(x) == 0`` should be used instead of this function,
1881 as that will also return true for 0d arrays. This is how numpy overloads
1882 functions in the style of the ``dx`` arguments to `gradient` and the ``bins``
1883 argument to `histogram`. Some key differences:
1885 +--------------------------------------+---------------+-------------------+
1886 | x |``isscalar(x)``|``np.ndim(x) == 0``|
1887 +======================================+===============+===================+
1888 | PEP 3141 numeric objects (including | ``True`` | ``True`` |
1889 | builtins) | | |
1890 +--------------------------------------+---------------+-------------------+
1891 | builtin string and buffer objects | ``True`` | ``True`` |
1892 +--------------------------------------+---------------+-------------------+
1893 | other builtin objects, like | ``False`` | ``True`` |
1894 | `pathlib.Path`, `Exception`, | | |
1895 | the result of `re.compile` | | |
1896 +--------------------------------------+---------------+-------------------+
1897 | third-party objects like | ``False`` | ``True`` |
1898 | `matplotlib.figure.Figure` | | |
1899 +--------------------------------------+---------------+-------------------+
1900 | zero-dimensional numpy arrays | ``False`` | ``True`` |
1901 +--------------------------------------+---------------+-------------------+
1902 | other numpy arrays | ``False`` | ``False`` |
1903 +--------------------------------------+---------------+-------------------+
1904 | `list`, `tuple`, and other sequence | ``False`` | ``False`` |
1905 | objects | | |
1906 +--------------------------------------+---------------+-------------------+
1908 Examples
1909 --------
1910 >>> np.isscalar(3.1)
1911 True
1912 >>> np.isscalar(np.array(3.1))
1913 False
1914 >>> np.isscalar([3.1])
1915 False
1916 >>> np.isscalar(False)
1917 True
1918 >>> np.isscalar('numpy')
1919 True
1921 NumPy supports PEP 3141 numbers:
1923 >>> from fractions import Fraction
1924 >>> np.isscalar(Fraction(5, 17))
1925 True
1926 >>> from numbers import Number
1927 >>> np.isscalar(Number())
1928 True
1930 """
1931 return (isinstance(element, generic)
1932 or type(element) in ScalarType
1933 or isinstance(element, numbers.Number))
1936@set_module('numpy')
1937def binary_repr(num, width=None):
1938 """
1939 Return the binary representation of the input number as a string.
1941 For negative numbers, if width is not given, a minus sign is added to the
1942 front. If width is given, the two's complement of the number is
1943 returned, with respect to that width.
1945 In a two's-complement system negative numbers are represented by the two's
1946 complement of the absolute value. This is the most common method of
1947 representing signed integers on computers [1]_. A N-bit two's-complement
1948 system can represent every integer in the range
1949 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
1951 Parameters
1952 ----------
1953 num : int
1954 Only an integer decimal number can be used.
1955 width : int, optional
1956 The length of the returned string if `num` is positive, or the length
1957 of the two's complement if `num` is negative, provided that `width` is
1958 at least a sufficient number of bits for `num` to be represented in the
1959 designated form.
1961 If the `width` value is insufficient, it will be ignored, and `num` will
1962 be returned in binary (`num` > 0) or two's complement (`num` < 0) form
1963 with its width equal to the minimum number of bits needed to represent
1964 the number in the designated form. This behavior is deprecated and will
1965 later raise an error.
1967 .. deprecated:: 1.12.0
1969 Returns
1970 -------
1971 bin : str
1972 Binary representation of `num` or two's complement of `num`.
1974 See Also
1975 --------
1976 base_repr: Return a string representation of a number in the given base
1977 system.
1978 bin: Python's built-in binary representation generator of an integer.
1980 Notes
1981 -----
1982 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
1983 faster.
1985 References
1986 ----------
1987 .. [1] Wikipedia, "Two's complement",
1988 https://en.wikipedia.org/wiki/Two's_complement
1990 Examples
1991 --------
1992 >>> np.binary_repr(3)
1993 '11'
1994 >>> np.binary_repr(-3)
1995 '-11'
1996 >>> np.binary_repr(3, width=4)
1997 '0011'
1999 The two's complement is returned when the input number is negative and
2000 width is specified:
2002 >>> np.binary_repr(-3, width=3)
2003 '101'
2004 >>> np.binary_repr(-3, width=5)
2005 '11101'
2007 """
2008 def warn_if_insufficient(width, binwidth):
2009 if width is not None and width < binwidth:
2010 warnings.warn(
2011 "Insufficient bit width provided. This behavior "
2012 "will raise an error in the future.", DeprecationWarning,
2013 stacklevel=3)
2015 # Ensure that num is a Python integer to avoid overflow or unwanted
2016 # casts to floating point.
2017 num = operator.index(num)
2019 if num == 0:
2020 return '0' * (width or 1)
2022 elif num > 0:
2023 binary = bin(num)[2:]
2024 binwidth = len(binary)
2025 outwidth = (binwidth if width is None
2026 else builtins.max(binwidth, width))
2027 warn_if_insufficient(width, binwidth)
2028 return binary.zfill(outwidth)
2030 else:
2031 if width is None:
2032 return '-' + bin(-num)[2:]
2034 else:
2035 poswidth = len(bin(-num)[2:])
2037 # See gh-8679: remove extra digit
2038 # for numbers at boundaries.
2039 if 2**(poswidth - 1) == -num:
2040 poswidth -= 1
2042 twocomp = 2**(poswidth + 1) + num
2043 binary = bin(twocomp)[2:]
2044 binwidth = len(binary)
2046 outwidth = builtins.max(binwidth, width)
2047 warn_if_insufficient(width, binwidth)
2048 return '1' * (outwidth - binwidth) + binary
2051@set_module('numpy')
2052def base_repr(number, base=2, padding=0):
2053 """
2054 Return a string representation of a number in the given base system.
2056 Parameters
2057 ----------
2058 number : int
2059 The value to convert. Positive and negative values are handled.
2060 base : int, optional
2061 Convert `number` to the `base` number system. The valid range is 2-36,
2062 the default value is 2.
2063 padding : int, optional
2064 Number of zeros padded on the left. Default is 0 (no padding).
2066 Returns
2067 -------
2068 out : str
2069 String representation of `number` in `base` system.
2071 See Also
2072 --------
2073 binary_repr : Faster version of `base_repr` for base 2.
2075 Examples
2076 --------
2077 >>> np.base_repr(5)
2078 '101'
2079 >>> np.base_repr(6, 5)
2080 '11'
2081 >>> np.base_repr(7, base=5, padding=3)
2082 '00012'
2084 >>> np.base_repr(10, base=16)
2085 'A'
2086 >>> np.base_repr(32, base=16)
2087 '20'
2089 """
2090 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2091 if base > len(digits):
2092 raise ValueError("Bases greater than 36 not handled in base_repr.")
2093 elif base < 2:
2094 raise ValueError("Bases less than 2 not handled in base_repr.")
2096 num = abs(number)
2097 res = []
2098 while num:
2099 res.append(digits[num % base])
2100 num //= base
2101 if padding:
2102 res.append('0' * padding)
2103 if number < 0:
2104 res.append('-')
2105 return ''.join(reversed(res or '0'))
2108# These are all essentially abbreviations
2109# These might wind up in a special abbreviations module
2112def _maketup(descr, val):
2113 dt = dtype(descr)
2114 # Place val in all scalar tuples:
2115 fields = dt.fields
2116 if fields is None:
2117 return val
2118 else:
2119 res = [_maketup(fields[name][0], val) for name in dt.names]
2120 return tuple(res)
2123@set_array_function_like_doc
2124@set_module('numpy')
2125def identity(n, dtype=None, *, like=None):
2126 """
2127 Return the identity array.
2129 The identity array is a square array with ones on
2130 the main diagonal.
2132 Parameters
2133 ----------
2134 n : int
2135 Number of rows (and columns) in `n` x `n` output.
2136 dtype : data-type, optional
2137 Data-type of the output. Defaults to ``float``.
2138 ${ARRAY_FUNCTION_LIKE}
2140 .. versionadded:: 1.20.0
2142 Returns
2143 -------
2144 out : ndarray
2145 `n` x `n` array with its main diagonal set to one,
2146 and all other elements 0.
2148 Examples
2149 --------
2150 >>> np.identity(3)
2151 array([[1., 0., 0.],
2152 [0., 1., 0.],
2153 [0., 0., 1.]])
2155 """
2156 if like is not None:
2157 return _identity_with_like(like, n, dtype=dtype)
2159 from numpy import eye
2160 return eye(n, dtype=dtype, like=like)
2163_identity_with_like = array_function_dispatch()(identity)
2166def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2167 return (a, b)
2170@array_function_dispatch(_allclose_dispatcher)
2171def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2172 """
2173 Returns True if two arrays are element-wise equal within a tolerance.
2175 The tolerance values are positive, typically very small numbers. The
2176 relative difference (`rtol` * abs(`b`)) and the absolute difference
2177 `atol` are added together to compare against the absolute difference
2178 between `a` and `b`.
2180 NaNs are treated as equal if they are in the same place and if
2181 ``equal_nan=True``. Infs are treated as equal if they are in the same
2182 place and of the same sign in both arrays.
2184 Parameters
2185 ----------
2186 a, b : array_like
2187 Input arrays to compare.
2188 rtol : float
2189 The relative tolerance parameter (see Notes).
2190 atol : float
2191 The absolute tolerance parameter (see Notes).
2192 equal_nan : bool
2193 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2194 considered equal to NaN's in `b` in the output array.
2196 .. versionadded:: 1.10.0
2198 Returns
2199 -------
2200 allclose : bool
2201 Returns True if the two arrays are equal within the given
2202 tolerance; False otherwise.
2204 See Also
2205 --------
2206 isclose, all, any, equal
2208 Notes
2209 -----
2210 If the following equation is element-wise True, then allclose returns
2211 True.
2213 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2215 The above equation is not symmetric in `a` and `b`, so that
2216 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
2217 some rare cases.
2219 The comparison of `a` and `b` uses standard broadcasting, which
2220 means that `a` and `b` need not have the same shape in order for
2221 ``allclose(a, b)`` to evaluate to True. The same is true for
2222 `equal` but not `array_equal`.
2224 `allclose` is not defined for non-numeric data types.
2225 `bool` is considered a numeric data-type for this purpose.
2227 Examples
2228 --------
2229 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
2230 False
2231 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
2232 True
2233 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
2234 False
2235 >>> np.allclose([1.0, np.nan], [1.0, np.nan])
2236 False
2237 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2238 True
2240 """
2241 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2242 return bool(res)
2245def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2246 return (a, b)
2249@array_function_dispatch(_isclose_dispatcher)
2250def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2251 """
2252 Returns a boolean array where two arrays are element-wise equal within a
2253 tolerance.
2255 The tolerance values are positive, typically very small numbers. The
2256 relative difference (`rtol` * abs(`b`)) and the absolute difference
2257 `atol` are added together to compare against the absolute difference
2258 between `a` and `b`.
2260 .. warning:: The default `atol` is not appropriate for comparing numbers
2261 that are much smaller than one (see Notes).
2263 Parameters
2264 ----------
2265 a, b : array_like
2266 Input arrays to compare.
2267 rtol : float
2268 The relative tolerance parameter (see Notes).
2269 atol : float
2270 The absolute tolerance parameter (see Notes).
2271 equal_nan : bool
2272 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2273 considered equal to NaN's in `b` in the output array.
2275 Returns
2276 -------
2277 y : array_like
2278 Returns a boolean array of where `a` and `b` are equal within the
2279 given tolerance. If both `a` and `b` are scalars, returns a single
2280 boolean value.
2282 See Also
2283 --------
2284 allclose
2285 math.isclose
2287 Notes
2288 -----
2289 .. versionadded:: 1.7.0
2291 For finite values, isclose uses the following equation to test whether
2292 two floating point values are equivalent.
2294 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2296 Unlike the built-in `math.isclose`, the above equation is not symmetric
2297 in `a` and `b` -- it assumes `b` is the reference value -- so that
2298 `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
2299 the default value of atol is not zero, and is used to determine what
2300 small values should be considered close to zero. The default value is
2301 appropriate for expected values of order unity: if the expected values
2302 are significantly smaller than one, it can result in false positives.
2303 `atol` should be carefully selected for the use case at hand. A zero value
2304 for `atol` will result in `False` if either `a` or `b` is zero.
2306 `isclose` is not defined for non-numeric data types.
2307 `bool` is considered a numeric data-type for this purpose.
2309 Examples
2310 --------
2311 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
2312 array([ True, False])
2313 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
2314 array([ True, True])
2315 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
2316 array([False, True])
2317 >>> np.isclose([1.0, np.nan], [1.0, np.nan])
2318 array([ True, False])
2319 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2320 array([ True, True])
2321 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
2322 array([ True, False])
2323 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
2324 array([False, False])
2325 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
2326 array([ True, True])
2327 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
2328 array([False, True])
2329 """
2330 def within_tol(x, y, atol, rtol):
2331 with errstate(invalid='ignore'), _no_nep50_warning():
2332 return less_equal(abs(x-y), atol + rtol * abs(y))
2334 x = asanyarray(a)
2335 y = asanyarray(b)
2337 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
2338 # This will cause casting of x later. Also, make sure to allow subclasses
2339 # (e.g., for numpy.ma).
2340 # NOTE: We explicitly allow timedelta, which used to work. This could
2341 # possibly be deprecated. See also gh-18286.
2342 # timedelta works if `atol` is an integer or also a timedelta.
2343 # Although, the default tolerances are unlikely to be useful
2344 if y.dtype.kind != "m":
2345 dt = multiarray.result_type(y, 1.)
2346 y = asanyarray(y, dtype=dt)
2348 xfin = isfinite(x)
2349 yfin = isfinite(y)
2350 if all(xfin) and all(yfin):
2351 return within_tol(x, y, atol, rtol)
2352 else:
2353 finite = xfin & yfin
2354 cond = zeros_like(finite, subok=True)
2355 # Because we're using boolean indexing, x & y must be the same shape.
2356 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
2357 # lib.stride_tricks, though, so we can't import it here.
2358 x = x * ones_like(cond)
2359 y = y * ones_like(cond)
2360 # Avoid subtraction with infinite/nan values...
2361 cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
2362 # Check for equality of infinite values...
2363 cond[~finite] = (x[~finite] == y[~finite])
2364 if equal_nan:
2365 # Make NaN == NaN
2366 both_nan = isnan(x) & isnan(y)
2368 # Needed to treat masked arrays correctly. = True would not work.
2369 cond[both_nan] = both_nan[both_nan]
2371 return cond[()] # Flatten 0d arrays to scalars
2374def _array_equal_dispatcher(a1, a2, equal_nan=None):
2375 return (a1, a2)
2378@array_function_dispatch(_array_equal_dispatcher)
2379def array_equal(a1, a2, equal_nan=False):
2380 """
2381 True if two arrays have the same shape and elements, False otherwise.
2383 Parameters
2384 ----------
2385 a1, a2 : array_like
2386 Input arrays.
2387 equal_nan : bool
2388 Whether to compare NaN's as equal. If the dtype of a1 and a2 is
2389 complex, values will be considered equal if either the real or the
2390 imaginary component of a given value is ``nan``.
2392 .. versionadded:: 1.19.0
2394 Returns
2395 -------
2396 b : bool
2397 Returns True if the arrays are equal.
2399 See Also
2400 --------
2401 allclose: Returns True if two arrays are element-wise equal within a
2402 tolerance.
2403 array_equiv: Returns True if input arrays are shape consistent and all
2404 elements equal.
2406 Examples
2407 --------
2408 >>> np.array_equal([1, 2], [1, 2])
2409 True
2410 >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
2411 True
2412 >>> np.array_equal([1, 2], [1, 2, 3])
2413 False
2414 >>> np.array_equal([1, 2], [1, 4])
2415 False
2416 >>> a = np.array([1, np.nan])
2417 >>> np.array_equal(a, a)
2418 False
2419 >>> np.array_equal(a, a, equal_nan=True)
2420 True
2422 When ``equal_nan`` is True, complex values with nan components are
2423 considered equal if either the real *or* the imaginary components are nan.
2425 >>> a = np.array([1 + 1j])
2426 >>> b = a.copy()
2427 >>> a.real = np.nan
2428 >>> b.imag = np.nan
2429 >>> np.array_equal(a, b, equal_nan=True)
2430 True
2431 """
2432 try:
2433 a1, a2 = asarray(a1), asarray(a2)
2434 except Exception:
2435 return False
2436 if a1.shape != a2.shape:
2437 return False
2438 if not equal_nan:
2439 return bool(asarray(a1 == a2).all())
2440 # Handling NaN values if equal_nan is True
2441 a1nan, a2nan = isnan(a1), isnan(a2)
2442 # NaN's occur at different locations
2443 if not (a1nan == a2nan).all():
2444 return False
2445 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
2446 return bool(asarray(a1[~a1nan] == a2[~a1nan]).all())
2449def _array_equiv_dispatcher(a1, a2):
2450 return (a1, a2)
2453@array_function_dispatch(_array_equiv_dispatcher)
2454def array_equiv(a1, a2):
2455 """
2456 Returns True if input arrays are shape consistent and all elements equal.
2458 Shape consistent means they are either the same shape, or one input array
2459 can be broadcasted to create the same shape as the other one.
2461 Parameters
2462 ----------
2463 a1, a2 : array_like
2464 Input arrays.
2466 Returns
2467 -------
2468 out : bool
2469 True if equivalent, False otherwise.
2471 Examples
2472 --------
2473 >>> np.array_equiv([1, 2], [1, 2])
2474 True
2475 >>> np.array_equiv([1, 2], [1, 3])
2476 False
2478 Showing the shape equivalence:
2480 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
2481 True
2482 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
2483 False
2485 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
2486 False
2488 """
2489 try:
2490 a1, a2 = asarray(a1), asarray(a2)
2491 except Exception:
2492 return False
2493 try:
2494 multiarray.broadcast(a1, a2)
2495 except Exception:
2496 return False
2498 return bool(asarray(a1 == a2).all())
2501Inf = inf = infty = Infinity = PINF
2502nan = NaN = NAN
2503False_ = bool_(False)
2504True_ = bool_(True)
2507def extend_all(module):
2508 existing = set(__all__)
2509 mall = getattr(module, '__all__')
2510 for a in mall:
2511 if a not in existing:
2512 __all__.append(a)
2515from .umath import *
2516from .numerictypes import *
2517from . import fromnumeric
2518from .fromnumeric import *
2519from . import arrayprint
2520from .arrayprint import *
2521from . import _asarray
2522from ._asarray import *
2523from . import _ufunc_config
2524from ._ufunc_config import *
2525extend_all(fromnumeric)
2526extend_all(umath)
2527extend_all(numerictypes)
2528extend_all(arrayprint)
2529extend_all(_asarray)
2530extend_all(_ufunc_config)