Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/numpy/core/numeric.py: 29%
492 statements
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:27 +0000
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:27 +0000
1import functools
2import itertools
3import operator
4import sys
5import warnings
6import numbers
8import numpy as np
9from . import multiarray
10from .multiarray import (
11 fastCopyAndTranspose, ALLOW_THREADS,
12 BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE,
13 WRAP, arange, array, asarray, asanyarray, ascontiguousarray,
14 asfortranarray, broadcast, can_cast, compare_chararrays,
15 concatenate, copyto, dot, dtype, empty,
16 empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter,
17 fromstring, inner, lexsort, matmul, may_share_memory,
18 min_scalar_type, ndarray, nditer, nested_iters, promote_types,
19 putmask, result_type, set_numeric_ops, shares_memory, vdot, where,
20 zeros, normalize_axis_index, _get_promotion_state, _set_promotion_state)
22from . import overrides
23from . import umath
24from . import shape_base
25from .overrides import set_array_function_like_doc, set_module
26from .umath import (multiply, invert, sin, PINF, NAN)
27from . import numerictypes
28from .numerictypes import longlong, intc, int_, float_, complex_, bool_
29from ..exceptions import ComplexWarning, TooHardError, AxisError
30from ._ufunc_config import errstate, _no_nep50_warning
32bitwise_not = invert
33ufunc = type(sin)
34newaxis = None
36array_function_dispatch = functools.partial(
37 overrides.array_function_dispatch, module='numpy')
40__all__ = [
41 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
42 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
43 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
44 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
45 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
46 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
47 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
48 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
49 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
50 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
51 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
52 'identity', 'allclose', 'compare_chararrays', 'putmask',
53 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN',
54 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS',
55 'BUFSIZE', 'ALLOW_THREADS', 'full', 'full_like',
56 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS',
57 'MAY_SHARE_EXACT', '_get_promotion_state', '_set_promotion_state']
60def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
61 return (a,)
64@array_function_dispatch(_zeros_like_dispatcher)
65def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
66 """
67 Return an array of zeros with the same shape and type as a given array.
69 Parameters
70 ----------
71 a : array_like
72 The shape and data-type of `a` define these same attributes of
73 the returned array.
74 dtype : data-type, optional
75 Overrides the data type of the result.
77 .. versionadded:: 1.6.0
78 order : {'C', 'F', 'A', or 'K'}, optional
79 Overrides the memory layout of the result. 'C' means C-order,
80 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
81 'C' otherwise. 'K' means match the layout of `a` as closely
82 as possible.
84 .. versionadded:: 1.6.0
85 subok : bool, optional.
86 If True, then the newly created array will use the sub-class
87 type of `a`, otherwise it will be a base-class array. Defaults
88 to True.
89 shape : int or sequence of ints, optional.
90 Overrides the shape of the result. If order='K' and the number of
91 dimensions is unchanged, will try to keep order, otherwise,
92 order='C' is implied.
94 .. versionadded:: 1.17.0
96 Returns
97 -------
98 out : ndarray
99 Array of zeros with the same shape and type as `a`.
101 See Also
102 --------
103 empty_like : Return an empty array with shape and type of input.
104 ones_like : Return an array of ones with shape and type of input.
105 full_like : Return a new array with shape of input filled with value.
106 zeros : Return a new array setting values to zero.
108 Examples
109 --------
110 >>> x = np.arange(6)
111 >>> x = x.reshape((2, 3))
112 >>> x
113 array([[0, 1, 2],
114 [3, 4, 5]])
115 >>> np.zeros_like(x)
116 array([[0, 0, 0],
117 [0, 0, 0]])
119 >>> y = np.arange(3, dtype=float)
120 >>> y
121 array([0., 1., 2.])
122 >>> np.zeros_like(y)
123 array([0., 0., 0.])
125 """
126 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
127 # needed instead of a 0 to get same result as zeros for string dtypes
128 z = zeros(1, dtype=res.dtype)
129 multiarray.copyto(res, z, casting='unsafe')
130 return res
133def _ones_dispatcher(shape, dtype=None, order=None, *, like=None):
134 return(like,)
137@set_array_function_like_doc
138@set_module('numpy')
139def ones(shape, dtype=None, order='C', *, like=None):
140 """
141 Return a new array of given shape and type, filled with ones.
143 Parameters
144 ----------
145 shape : int or sequence of ints
146 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
147 dtype : data-type, optional
148 The desired data-type for the array, e.g., `numpy.int8`. Default is
149 `numpy.float64`.
150 order : {'C', 'F'}, optional, default: C
151 Whether to store multi-dimensional data in row-major
152 (C-style) or column-major (Fortran-style) order in
153 memory.
154 ${ARRAY_FUNCTION_LIKE}
156 .. versionadded:: 1.20.0
158 Returns
159 -------
160 out : ndarray
161 Array of ones with the given shape, dtype, and order.
163 See Also
164 --------
165 ones_like : Return an array of ones with shape and type of input.
166 empty : Return a new uninitialized array.
167 zeros : Return a new array setting values to zero.
168 full : Return a new array of given shape filled with value.
171 Examples
172 --------
173 >>> np.ones(5)
174 array([1., 1., 1., 1., 1.])
176 >>> np.ones((5,), dtype=int)
177 array([1, 1, 1, 1, 1])
179 >>> np.ones((2, 1))
180 array([[1.],
181 [1.]])
183 >>> s = (2,2)
184 >>> np.ones(s)
185 array([[1., 1.],
186 [1., 1.]])
188 """
189 if like is not None:
190 return _ones_with_like(shape, dtype=dtype, order=order, like=like)
192 a = empty(shape, dtype, order)
193 multiarray.copyto(a, 1, casting='unsafe')
194 return a
197_ones_with_like = array_function_dispatch(
198 _ones_dispatcher
199)(ones)
202def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
203 return (a,)
206@array_function_dispatch(_ones_like_dispatcher)
207def ones_like(a, dtype=None, order='K', subok=True, shape=None):
208 """
209 Return an array of ones with the same shape and type as a given array.
211 Parameters
212 ----------
213 a : array_like
214 The shape and data-type of `a` define these same attributes of
215 the returned array.
216 dtype : data-type, optional
217 Overrides the data type of the result.
219 .. versionadded:: 1.6.0
220 order : {'C', 'F', 'A', or 'K'}, optional
221 Overrides the memory layout of the result. 'C' means C-order,
222 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
223 'C' otherwise. 'K' means match the layout of `a` as closely
224 as possible.
226 .. versionadded:: 1.6.0
227 subok : bool, optional.
228 If True, then the newly created array will use the sub-class
229 type of `a`, otherwise it will be a base-class array. Defaults
230 to True.
231 shape : int or sequence of ints, optional.
232 Overrides the shape of the result. If order='K' and the number of
233 dimensions is unchanged, will try to keep order, otherwise,
234 order='C' is implied.
236 .. versionadded:: 1.17.0
238 Returns
239 -------
240 out : ndarray
241 Array of ones with the same shape and type as `a`.
243 See Also
244 --------
245 empty_like : Return an empty array with shape and type of input.
246 zeros_like : Return an array of zeros with shape and type of input.
247 full_like : Return a new array with shape of input filled with value.
248 ones : Return a new array setting values to one.
250 Examples
251 --------
252 >>> x = np.arange(6)
253 >>> x = x.reshape((2, 3))
254 >>> x
255 array([[0, 1, 2],
256 [3, 4, 5]])
257 >>> np.ones_like(x)
258 array([[1, 1, 1],
259 [1, 1, 1]])
261 >>> y = np.arange(3, dtype=float)
262 >>> y
263 array([0., 1., 2.])
264 >>> np.ones_like(y)
265 array([1., 1., 1.])
267 """
268 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
269 multiarray.copyto(res, 1, casting='unsafe')
270 return res
273def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, like=None):
274 return(like,)
277@set_array_function_like_doc
278@set_module('numpy')
279def full(shape, fill_value, dtype=None, order='C', *, like=None):
280 """
281 Return a new array of given shape and type, filled with `fill_value`.
283 Parameters
284 ----------
285 shape : int or sequence of ints
286 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
287 fill_value : scalar or array_like
288 Fill value.
289 dtype : data-type, optional
290 The desired data-type for the array The default, None, means
291 ``np.array(fill_value).dtype``.
292 order : {'C', 'F'}, optional
293 Whether to store multidimensional data in C- or Fortran-contiguous
294 (row- or column-wise) order in memory.
295 ${ARRAY_FUNCTION_LIKE}
297 .. versionadded:: 1.20.0
299 Returns
300 -------
301 out : ndarray
302 Array of `fill_value` with the given shape, dtype, and order.
304 See Also
305 --------
306 full_like : Return a new array with shape of input filled with value.
307 empty : Return a new uninitialized array.
308 ones : Return a new array setting values to one.
309 zeros : Return a new array setting values to zero.
311 Examples
312 --------
313 >>> np.full((2, 2), np.inf)
314 array([[inf, inf],
315 [inf, inf]])
316 >>> np.full((2, 2), 10)
317 array([[10, 10],
318 [10, 10]])
320 >>> np.full((2, 2), [1, 2])
321 array([[1, 2],
322 [1, 2]])
324 """
325 if like is not None:
326 return _full_with_like(shape, fill_value, dtype=dtype, order=order, like=like)
328 if dtype is None:
329 fill_value = asarray(fill_value)
330 dtype = fill_value.dtype
331 a = empty(shape, dtype, order)
332 multiarray.copyto(a, fill_value, casting='unsafe')
333 return a
336_full_with_like = array_function_dispatch(
337 _full_dispatcher
338)(full)
341def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None):
342 return (a,)
345@array_function_dispatch(_full_like_dispatcher)
346def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
347 """
348 Return a full array with the same shape and type as a given array.
350 Parameters
351 ----------
352 a : array_like
353 The shape and data-type of `a` define these same attributes of
354 the returned array.
355 fill_value : array_like
356 Fill value.
357 dtype : data-type, optional
358 Overrides the data type of the result.
359 order : {'C', 'F', 'A', or 'K'}, optional
360 Overrides the memory layout of the result. 'C' means C-order,
361 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
362 'C' otherwise. 'K' means match the layout of `a` as closely
363 as possible.
364 subok : bool, optional.
365 If True, then the newly created array will use the sub-class
366 type of `a`, otherwise it will be a base-class array. Defaults
367 to True.
368 shape : int or sequence of ints, optional.
369 Overrides the shape of the result. If order='K' and the number of
370 dimensions is unchanged, will try to keep order, otherwise,
371 order='C' is implied.
373 .. versionadded:: 1.17.0
375 Returns
376 -------
377 out : ndarray
378 Array of `fill_value` with the same shape and type as `a`.
380 See Also
381 --------
382 empty_like : Return an empty array with shape and type of input.
383 ones_like : Return an array of ones with shape and type of input.
384 zeros_like : Return an array of zeros with shape and type of input.
385 full : Return a new array of given shape filled with value.
387 Examples
388 --------
389 >>> x = np.arange(6, dtype=int)
390 >>> np.full_like(x, 1)
391 array([1, 1, 1, 1, 1, 1])
392 >>> np.full_like(x, 0.1)
393 array([0, 0, 0, 0, 0, 0])
394 >>> np.full_like(x, 0.1, dtype=np.double)
395 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
396 >>> np.full_like(x, np.nan, dtype=np.double)
397 array([nan, nan, nan, nan, nan, nan])
399 >>> y = np.arange(6, dtype=np.double)
400 >>> np.full_like(y, 0.1)
401 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
403 >>> y = np.zeros([2, 2, 3], dtype=int)
404 >>> np.full_like(y, [0, 0, 255])
405 array([[[ 0, 0, 255],
406 [ 0, 0, 255]],
407 [[ 0, 0, 255],
408 [ 0, 0, 255]]])
409 """
410 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
411 multiarray.copyto(res, fill_value, casting='unsafe')
412 return res
415def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
416 return (a,)
419@array_function_dispatch(_count_nonzero_dispatcher)
420def count_nonzero(a, axis=None, *, keepdims=False):
421 """
422 Counts the number of non-zero values in the array ``a``.
424 The word "non-zero" is in reference to the Python 2.x
425 built-in method ``__nonzero__()`` (renamed ``__bool__()``
426 in Python 3.x) of Python objects that tests an object's
427 "truthfulness". For example, any number is considered
428 truthful if it is nonzero, whereas any string is considered
429 truthful if it is not the empty string. Thus, this function
430 (recursively) counts how many elements in ``a`` (and in
431 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
432 method evaluated to ``True``.
434 Parameters
435 ----------
436 a : array_like
437 The array for which to count non-zeros.
438 axis : int or tuple, optional
439 Axis or tuple of axes along which to count non-zeros.
440 Default is None, meaning that non-zeros will be counted
441 along a flattened version of ``a``.
443 .. versionadded:: 1.12.0
445 keepdims : bool, optional
446 If this is set to True, the axes that are counted are left
447 in the result as dimensions with size one. With this option,
448 the result will broadcast correctly against the input array.
450 .. versionadded:: 1.19.0
452 Returns
453 -------
454 count : int or array of int
455 Number of non-zero values in the array along a given axis.
456 Otherwise, the total number of non-zero values in the array
457 is returned.
459 See Also
460 --------
461 nonzero : Return the coordinates of all the non-zero values.
463 Examples
464 --------
465 >>> np.count_nonzero(np.eye(4))
466 4
467 >>> a = np.array([[0, 1, 7, 0],
468 ... [3, 0, 2, 19]])
469 >>> np.count_nonzero(a)
470 5
471 >>> np.count_nonzero(a, axis=0)
472 array([1, 1, 2, 1])
473 >>> np.count_nonzero(a, axis=1)
474 array([2, 3])
475 >>> np.count_nonzero(a, axis=1, keepdims=True)
476 array([[2],
477 [3]])
478 """
479 if axis is None and not keepdims:
480 return multiarray.count_nonzero(a)
482 a = asanyarray(a)
484 # TODO: this works around .astype(bool) not working properly (gh-9847)
485 if np.issubdtype(a.dtype, np.character):
486 a_bool = a != a.dtype.type()
487 else:
488 a_bool = a.astype(np.bool_, copy=False)
490 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
493@set_module('numpy')
494def isfortran(a):
495 """
496 Check if the array is Fortran contiguous but *not* C contiguous.
498 This function is obsolete and, because of changes due to relaxed stride
499 checking, its return value for the same array may differ for versions
500 of NumPy >= 1.10.0 and previous versions. If you only want to check if an
501 array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
503 Parameters
504 ----------
505 a : ndarray
506 Input array.
508 Returns
509 -------
510 isfortran : bool
511 Returns True if the array is Fortran contiguous but *not* C contiguous.
514 Examples
515 --------
517 np.array allows to specify whether the array is written in C-contiguous
518 order (last index varies the fastest), or FORTRAN-contiguous order in
519 memory (first index varies the fastest).
521 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
522 >>> a
523 array([[1, 2, 3],
524 [4, 5, 6]])
525 >>> np.isfortran(a)
526 False
528 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
529 >>> b
530 array([[1, 2, 3],
531 [4, 5, 6]])
532 >>> np.isfortran(b)
533 True
536 The transpose of a C-ordered array is a FORTRAN-ordered array.
538 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
539 >>> a
540 array([[1, 2, 3],
541 [4, 5, 6]])
542 >>> np.isfortran(a)
543 False
544 >>> b = a.T
545 >>> b
546 array([[1, 4],
547 [2, 5],
548 [3, 6]])
549 >>> np.isfortran(b)
550 True
552 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
554 >>> np.isfortran(np.array([1, 2], order='F'))
555 False
557 """
558 return a.flags.fnc
561def _argwhere_dispatcher(a):
562 return (a,)
565@array_function_dispatch(_argwhere_dispatcher)
566def argwhere(a):
567 """
568 Find the indices of array elements that are non-zero, grouped by element.
570 Parameters
571 ----------
572 a : array_like
573 Input data.
575 Returns
576 -------
577 index_array : (N, a.ndim) ndarray
578 Indices of elements that are non-zero. Indices are grouped by element.
579 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
580 non-zero items.
582 See Also
583 --------
584 where, nonzero
586 Notes
587 -----
588 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
589 but produces a result of the correct shape for a 0D array.
591 The output of ``argwhere`` is not suitable for indexing arrays.
592 For this purpose use ``nonzero(a)`` instead.
594 Examples
595 --------
596 >>> x = np.arange(6).reshape(2,3)
597 >>> x
598 array([[0, 1, 2],
599 [3, 4, 5]])
600 >>> np.argwhere(x>1)
601 array([[0, 2],
602 [1, 0],
603 [1, 1],
604 [1, 2]])
606 """
607 # nonzero does not behave well on 0d, so promote to 1d
608 if np.ndim(a) == 0:
609 a = shape_base.atleast_1d(a)
610 # then remove the added dimension
611 return argwhere(a)[:,:0]
612 return transpose(nonzero(a))
615def _flatnonzero_dispatcher(a):
616 return (a,)
619@array_function_dispatch(_flatnonzero_dispatcher)
620def flatnonzero(a):
621 """
622 Return indices that are non-zero in the flattened version of a.
624 This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
626 Parameters
627 ----------
628 a : array_like
629 Input data.
631 Returns
632 -------
633 res : ndarray
634 Output array, containing the indices of the elements of ``a.ravel()``
635 that are non-zero.
637 See Also
638 --------
639 nonzero : Return the indices of the non-zero elements of the input array.
640 ravel : Return a 1-D array containing the elements of the input array.
642 Examples
643 --------
644 >>> x = np.arange(-2, 3)
645 >>> x
646 array([-2, -1, 0, 1, 2])
647 >>> np.flatnonzero(x)
648 array([0, 1, 3, 4])
650 Use the indices of the non-zero elements as an index array to extract
651 these elements:
653 >>> x.ravel()[np.flatnonzero(x)]
654 array([-2, -1, 1, 2])
656 """
657 return np.nonzero(np.ravel(a))[0]
660def _correlate_dispatcher(a, v, mode=None):
661 return (a, v)
664@array_function_dispatch(_correlate_dispatcher)
665def correlate(a, v, mode='valid'):
666 r"""
667 Cross-correlation of two 1-dimensional sequences.
669 This function computes the correlation as generally defined in signal
670 processing texts:
672 .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
674 with a and v sequences being zero-padded where necessary and
675 :math:`\overline x` denoting complex conjugation.
677 Parameters
678 ----------
679 a, v : array_like
680 Input sequences.
681 mode : {'valid', 'same', 'full'}, optional
682 Refer to the `convolve` docstring. Note that the default
683 is 'valid', unlike `convolve`, which uses 'full'.
684 old_behavior : bool
685 `old_behavior` was removed in NumPy 1.10. If you need the old
686 behavior, use `multiarray.correlate`.
688 Returns
689 -------
690 out : ndarray
691 Discrete cross-correlation of `a` and `v`.
693 See Also
694 --------
695 convolve : Discrete, linear convolution of two one-dimensional sequences.
696 multiarray.correlate : Old, no conjugate, version of correlate.
697 scipy.signal.correlate : uses FFT which has superior performance on large arrays.
699 Notes
700 -----
701 The definition of correlation above is not unique and sometimes correlation
702 may be defined differently. Another common definition is:
704 .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
706 which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
708 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does
709 not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might
710 be preferable.
713 Examples
714 --------
715 >>> np.correlate([1, 2, 3], [0, 1, 0.5])
716 array([3.5])
717 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
718 array([2. , 3.5, 3. ])
719 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
720 array([0.5, 2. , 3.5, 3. , 0. ])
722 Using complex sequences:
724 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
725 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
727 Note that you get the time reversed, complex conjugated result
728 (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
729 places:
731 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
732 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
734 """
735 return multiarray.correlate2(a, v, mode)
738def _convolve_dispatcher(a, v, mode=None):
739 return (a, v)
742@array_function_dispatch(_convolve_dispatcher)
743def convolve(a, v, mode='full'):
744 """
745 Returns the discrete, linear convolution of two one-dimensional sequences.
747 The convolution operator is often seen in signal processing, where it
748 models the effect of a linear time-invariant system on a signal [1]_. In
749 probability theory, the sum of two independent random variables is
750 distributed according to the convolution of their individual
751 distributions.
753 If `v` is longer than `a`, the arrays are swapped before computation.
755 Parameters
756 ----------
757 a : (N,) array_like
758 First one-dimensional input array.
759 v : (M,) array_like
760 Second one-dimensional input array.
761 mode : {'full', 'valid', 'same'}, optional
762 'full':
763 By default, mode is 'full'. This returns the convolution
764 at each point of overlap, with an output shape of (N+M-1,). At
765 the end-points of the convolution, the signals do not overlap
766 completely, and boundary effects may be seen.
768 'same':
769 Mode 'same' returns output of length ``max(M, N)``. Boundary
770 effects are still visible.
772 'valid':
773 Mode 'valid' returns output of length
774 ``max(M, N) - min(M, N) + 1``. The convolution product is only given
775 for points where the signals overlap completely. Values outside
776 the signal boundary have no effect.
778 Returns
779 -------
780 out : ndarray
781 Discrete, linear convolution of `a` and `v`.
783 See Also
784 --------
785 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
786 Transform.
787 scipy.linalg.toeplitz : Used to construct the convolution operator.
788 polymul : Polynomial multiplication. Same output as convolve, but also
789 accepts poly1d objects as input.
791 Notes
792 -----
793 The discrete convolution operation is defined as
795 .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
797 It can be shown that a convolution :math:`x(t) * y(t)` in time/space
798 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
799 domain, after appropriate padding (padding is necessary to prevent
800 circular convolution). Since multiplication is more efficient (faster)
801 than convolution, the function `scipy.signal.fftconvolve` exploits the
802 FFT to calculate the convolution of large data-sets.
804 References
805 ----------
806 .. [1] Wikipedia, "Convolution",
807 https://en.wikipedia.org/wiki/Convolution
809 Examples
810 --------
811 Note how the convolution operator flips the second array
812 before "sliding" the two across one another:
814 >>> np.convolve([1, 2, 3], [0, 1, 0.5])
815 array([0. , 1. , 2.5, 4. , 1.5])
817 Only return the middle values of the convolution.
818 Contains boundary effects, where zeros are taken
819 into account:
821 >>> np.convolve([1,2,3],[0,1,0.5], 'same')
822 array([1. , 2.5, 4. ])
824 The two arrays are of the same length, so there
825 is only one position where they completely overlap:
827 >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
828 array([2.5])
830 """
831 a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
832 if (len(v) > len(a)):
833 a, v = v, a
834 if len(a) == 0:
835 raise ValueError('a cannot be empty')
836 if len(v) == 0:
837 raise ValueError('v cannot be empty')
838 return multiarray.correlate(a, v[::-1], mode)
841def _outer_dispatcher(a, b, out=None):
842 return (a, b, out)
845@array_function_dispatch(_outer_dispatcher)
846def outer(a, b, out=None):
847 """
848 Compute the outer product of two vectors.
850 Given two vectors, ``a = [a0, a1, ..., aM]`` and
851 ``b = [b0, b1, ..., bN]``,
852 the outer product [1]_ is::
854 [[a0*b0 a0*b1 ... a0*bN ]
855 [a1*b0 .
856 [ ... .
857 [aM*b0 aM*bN ]]
859 Parameters
860 ----------
861 a : (M,) array_like
862 First input vector. Input is flattened if
863 not already 1-dimensional.
864 b : (N,) array_like
865 Second input vector. Input is flattened if
866 not already 1-dimensional.
867 out : (M, N) ndarray, optional
868 A location where the result is stored
870 .. versionadded:: 1.9.0
872 Returns
873 -------
874 out : (M, N) ndarray
875 ``out[i, j] = a[i] * b[j]``
877 See also
878 --------
879 inner
880 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
881 ufunc.outer : A generalization to dimensions other than 1D and other
882 operations. ``np.multiply.outer(a.ravel(), b.ravel())``
883 is the equivalent.
884 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
885 is the equivalent.
887 References
888 ----------
889 .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
890 ed., Baltimore, MD, Johns Hopkins University Press, 1996,
891 pg. 8.
893 Examples
894 --------
895 Make a (*very* coarse) grid for computing a Mandelbrot set:
897 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
898 >>> rl
899 array([[-2., -1., 0., 1., 2.],
900 [-2., -1., 0., 1., 2.],
901 [-2., -1., 0., 1., 2.],
902 [-2., -1., 0., 1., 2.],
903 [-2., -1., 0., 1., 2.]])
904 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
905 >>> im
906 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
907 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
908 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
909 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
910 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
911 >>> grid = rl + im
912 >>> grid
913 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
914 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
915 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
916 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
917 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
919 An example using a "vector" of letters:
921 >>> x = np.array(['a', 'b', 'c'], dtype=object)
922 >>> np.outer(x, [1, 2, 3])
923 array([['a', 'aa', 'aaa'],
924 ['b', 'bb', 'bbb'],
925 ['c', 'cc', 'ccc']], dtype=object)
927 """
928 a = asarray(a)
929 b = asarray(b)
930 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
933def _tensordot_dispatcher(a, b, axes=None):
934 return (a, b)
937@array_function_dispatch(_tensordot_dispatcher)
938def tensordot(a, b, axes=2):
939 """
940 Compute tensor dot product along specified axes.
942 Given two tensors, `a` and `b`, and an array_like object containing
943 two array_like objects, ``(a_axes, b_axes)``, sum the products of
944 `a`'s and `b`'s elements (components) over the axes specified by
945 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
946 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
947 of `a` and the first ``N`` dimensions of `b` are summed over.
949 Parameters
950 ----------
951 a, b : array_like
952 Tensors to "dot".
954 axes : int or (2,) array_like
955 * integer_like
956 If an int N, sum over the last N axes of `a` and the first N axes
957 of `b` in order. The sizes of the corresponding axes must match.
958 * (2,) array_like
959 Or, a list of axes to be summed over, first sequence applying to `a`,
960 second to `b`. Both elements array_like must be of the same length.
962 Returns
963 -------
964 output : ndarray
965 The tensor dot product of the input.
967 See Also
968 --------
969 dot, einsum
971 Notes
972 -----
973 Three common use cases are:
974 * ``axes = 0`` : tensor product :math:`a\\otimes b`
975 * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
976 * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
978 When `axes` is integer_like, the sequence for evaluation will be: first
979 the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
980 Nth axis in `b` last.
982 When there is more than one axis to sum over - and they are not the last
983 (first) axes of `a` (`b`) - the argument `axes` should consist of
984 two sequences of the same length, with the first axis to sum over given
985 first in both sequences, the second axis second, and so forth.
987 The shape of the result consists of the non-contracted axes of the
988 first tensor, followed by the non-contracted axes of the second.
990 Examples
991 --------
992 A "traditional" example:
994 >>> a = np.arange(60.).reshape(3,4,5)
995 >>> b = np.arange(24.).reshape(4,3,2)
996 >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
997 >>> c.shape
998 (5, 2)
999 >>> c
1000 array([[4400., 4730.],
1001 [4532., 4874.],
1002 [4664., 5018.],
1003 [4796., 5162.],
1004 [4928., 5306.]])
1005 >>> # A slower but equivalent way of computing the same...
1006 >>> d = np.zeros((5,2))
1007 >>> for i in range(5):
1008 ... for j in range(2):
1009 ... for k in range(3):
1010 ... for n in range(4):
1011 ... d[i,j] += a[k,n,i] * b[n,k,j]
1012 >>> c == d
1013 array([[ True, True],
1014 [ True, True],
1015 [ True, True],
1016 [ True, True],
1017 [ True, True]])
1019 An extended example taking advantage of the overloading of + and \\*:
1021 >>> a = np.array(range(1, 9))
1022 >>> a.shape = (2, 2, 2)
1023 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1024 >>> A.shape = (2, 2)
1025 >>> a; A
1026 array([[[1, 2],
1027 [3, 4]],
1028 [[5, 6],
1029 [7, 8]]])
1030 array([['a', 'b'],
1031 ['c', 'd']], dtype=object)
1033 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1034 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1036 >>> np.tensordot(a, A, 1)
1037 array([[['acc', 'bdd'],
1038 ['aaacccc', 'bbbdddd']],
1039 [['aaaaacccccc', 'bbbbbdddddd'],
1040 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1042 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1043 array([[[[['a', 'b'],
1044 ['c', 'd']],
1045 ...
1047 >>> np.tensordot(a, A, (0, 1))
1048 array([[['abbbbb', 'cddddd'],
1049 ['aabbbbbb', 'ccdddddd']],
1050 [['aaabbbbbbb', 'cccddddddd'],
1051 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1053 >>> np.tensordot(a, A, (2, 1))
1054 array([[['abb', 'cdd'],
1055 ['aaabbbb', 'cccdddd']],
1056 [['aaaaabbbbbb', 'cccccdddddd'],
1057 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1059 >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1060 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1062 >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1063 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1065 """
1066 try:
1067 iter(axes)
1068 except Exception:
1069 axes_a = list(range(-axes, 0))
1070 axes_b = list(range(0, axes))
1071 else:
1072 axes_a, axes_b = axes
1073 try:
1074 na = len(axes_a)
1075 axes_a = list(axes_a)
1076 except TypeError:
1077 axes_a = [axes_a]
1078 na = 1
1079 try:
1080 nb = len(axes_b)
1081 axes_b = list(axes_b)
1082 except TypeError:
1083 axes_b = [axes_b]
1084 nb = 1
1086 a, b = asarray(a), asarray(b)
1087 as_ = a.shape
1088 nda = a.ndim
1089 bs = b.shape
1090 ndb = b.ndim
1091 equal = True
1092 if na != nb:
1093 equal = False
1094 else:
1095 for k in range(na):
1096 if as_[axes_a[k]] != bs[axes_b[k]]:
1097 equal = False
1098 break
1099 if axes_a[k] < 0:
1100 axes_a[k] += nda
1101 if axes_b[k] < 0:
1102 axes_b[k] += ndb
1103 if not equal:
1104 raise ValueError("shape-mismatch for sum")
1106 # Move the axes to sum over to the end of "a"
1107 # and to the front of "b"
1108 notin = [k for k in range(nda) if k not in axes_a]
1109 newaxes_a = notin + axes_a
1110 N2 = 1
1111 for axis in axes_a:
1112 N2 *= as_[axis]
1113 newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
1114 olda = [as_[axis] for axis in notin]
1116 notin = [k for k in range(ndb) if k not in axes_b]
1117 newaxes_b = axes_b + notin
1118 N2 = 1
1119 for axis in axes_b:
1120 N2 *= bs[axis]
1121 newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
1122 oldb = [bs[axis] for axis in notin]
1124 at = a.transpose(newaxes_a).reshape(newshape_a)
1125 bt = b.transpose(newaxes_b).reshape(newshape_b)
1126 res = dot(at, bt)
1127 return res.reshape(olda + oldb)
1130def _roll_dispatcher(a, shift, axis=None):
1131 return (a,)
1134@array_function_dispatch(_roll_dispatcher)
1135def roll(a, shift, axis=None):
1136 """
1137 Roll array elements along a given axis.
1139 Elements that roll beyond the last position are re-introduced at
1140 the first.
1142 Parameters
1143 ----------
1144 a : array_like
1145 Input array.
1146 shift : int or tuple of ints
1147 The number of places by which elements are shifted. If a tuple,
1148 then `axis` must be a tuple of the same size, and each of the
1149 given axes is shifted by the corresponding number. If an int
1150 while `axis` is a tuple of ints, then the same value is used for
1151 all given axes.
1152 axis : int or tuple of ints, optional
1153 Axis or axes along which elements are shifted. By default, the
1154 array is flattened before shifting, after which the original
1155 shape is restored.
1157 Returns
1158 -------
1159 res : ndarray
1160 Output array, with the same shape as `a`.
1162 See Also
1163 --------
1164 rollaxis : Roll the specified axis backwards, until it lies in a
1165 given position.
1167 Notes
1168 -----
1169 .. versionadded:: 1.12.0
1171 Supports rolling over multiple dimensions simultaneously.
1173 Examples
1174 --------
1175 >>> x = np.arange(10)
1176 >>> np.roll(x, 2)
1177 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
1178 >>> np.roll(x, -2)
1179 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
1181 >>> x2 = np.reshape(x, (2, 5))
1182 >>> x2
1183 array([[0, 1, 2, 3, 4],
1184 [5, 6, 7, 8, 9]])
1185 >>> np.roll(x2, 1)
1186 array([[9, 0, 1, 2, 3],
1187 [4, 5, 6, 7, 8]])
1188 >>> np.roll(x2, -1)
1189 array([[1, 2, 3, 4, 5],
1190 [6, 7, 8, 9, 0]])
1191 >>> np.roll(x2, 1, axis=0)
1192 array([[5, 6, 7, 8, 9],
1193 [0, 1, 2, 3, 4]])
1194 >>> np.roll(x2, -1, axis=0)
1195 array([[5, 6, 7, 8, 9],
1196 [0, 1, 2, 3, 4]])
1197 >>> np.roll(x2, 1, axis=1)
1198 array([[4, 0, 1, 2, 3],
1199 [9, 5, 6, 7, 8]])
1200 >>> np.roll(x2, -1, axis=1)
1201 array([[1, 2, 3, 4, 0],
1202 [6, 7, 8, 9, 5]])
1203 >>> np.roll(x2, (1, 1), axis=(1, 0))
1204 array([[9, 5, 6, 7, 8],
1205 [4, 0, 1, 2, 3]])
1206 >>> np.roll(x2, (2, 1), axis=(1, 0))
1207 array([[8, 9, 5, 6, 7],
1208 [3, 4, 0, 1, 2]])
1210 """
1211 a = asanyarray(a)
1212 if axis is None:
1213 return roll(a.ravel(), shift, 0).reshape(a.shape)
1215 else:
1216 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1217 broadcasted = broadcast(shift, axis)
1218 if broadcasted.ndim > 1:
1219 raise ValueError(
1220 "'shift' and 'axis' should be scalars or 1D sequences")
1221 shifts = {ax: 0 for ax in range(a.ndim)}
1222 for sh, ax in broadcasted:
1223 shifts[ax] += sh
1225 rolls = [((slice(None), slice(None)),)] * a.ndim
1226 for ax, offset in shifts.items():
1227 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
1228 if offset:
1229 # (original, result), (original, result)
1230 rolls[ax] = ((slice(None, -offset), slice(offset, None)),
1231 (slice(-offset, None), slice(None, offset)))
1233 result = empty_like(a)
1234 for indices in itertools.product(*rolls):
1235 arr_index, res_index = zip(*indices)
1236 result[res_index] = a[arr_index]
1238 return result
1241def _rollaxis_dispatcher(a, axis, start=None):
1242 return (a,)
1245@array_function_dispatch(_rollaxis_dispatcher)
1246def rollaxis(a, axis, start=0):
1247 """
1248 Roll the specified axis backwards, until it lies in a given position.
1250 This function continues to be supported for backward compatibility, but you
1251 should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1252 1.11.
1254 Parameters
1255 ----------
1256 a : ndarray
1257 Input array.
1258 axis : int
1259 The axis to be rolled. The positions of the other axes do not
1260 change relative to one another.
1261 start : int, optional
1262 When ``start <= axis``, the axis is rolled back until it lies in
1263 this position. When ``start > axis``, the axis is rolled until it
1264 lies before this position. The default, 0, results in a "complete"
1265 roll. The following table describes how negative values of ``start``
1266 are interpreted:
1268 .. table::
1269 :align: left
1271 +-------------------+----------------------+
1272 | ``start`` | Normalized ``start`` |
1273 +===================+======================+
1274 | ``-(arr.ndim+1)`` | raise ``AxisError`` |
1275 +-------------------+----------------------+
1276 | ``-arr.ndim`` | 0 |
1277 +-------------------+----------------------+
1278 | |vdots| | |vdots| |
1279 +-------------------+----------------------+
1280 | ``-1`` | ``arr.ndim-1`` |
1281 +-------------------+----------------------+
1282 | ``0`` | ``0`` |
1283 +-------------------+----------------------+
1284 | |vdots| | |vdots| |
1285 +-------------------+----------------------+
1286 | ``arr.ndim`` | ``arr.ndim`` |
1287 +-------------------+----------------------+
1288 | ``arr.ndim + 1`` | raise ``AxisError`` |
1289 +-------------------+----------------------+
1291 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
1293 Returns
1294 -------
1295 res : ndarray
1296 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
1297 NumPy versions a view of `a` is returned only if the order of the
1298 axes is changed, otherwise the input array is returned.
1300 See Also
1301 --------
1302 moveaxis : Move array axes to new positions.
1303 roll : Roll the elements of an array by a number of positions along a
1304 given axis.
1306 Examples
1307 --------
1308 >>> a = np.ones((3,4,5,6))
1309 >>> np.rollaxis(a, 3, 1).shape
1310 (3, 6, 4, 5)
1311 >>> np.rollaxis(a, 2).shape
1312 (5, 3, 4, 6)
1313 >>> np.rollaxis(a, 1, 4).shape
1314 (3, 5, 6, 4)
1316 """
1317 n = a.ndim
1318 axis = normalize_axis_index(axis, n)
1319 if start < 0:
1320 start += n
1321 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1322 if not (0 <= start < n + 1):
1323 raise AxisError(msg % ('start', -n, 'start', n + 1, start))
1324 if axis < start:
1325 # it's been removed
1326 start -= 1
1327 if axis == start:
1328 return a[...]
1329 axes = list(range(0, n))
1330 axes.remove(axis)
1331 axes.insert(start, axis)
1332 return a.transpose(axes)
1335def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
1336 """
1337 Normalizes an axis argument into a tuple of non-negative integer axes.
1339 This handles shorthands such as ``1`` and converts them to ``(1,)``,
1340 as well as performing the handling of negative indices covered by
1341 `normalize_axis_index`.
1343 By default, this forbids axes from being specified multiple times.
1345 Used internally by multi-axis-checking logic.
1347 .. versionadded:: 1.13.0
1349 Parameters
1350 ----------
1351 axis : int, iterable of int
1352 The un-normalized index or indices of the axis.
1353 ndim : int
1354 The number of dimensions of the array that `axis` should be normalized
1355 against.
1356 argname : str, optional
1357 A prefix to put before the error message, typically the name of the
1358 argument.
1359 allow_duplicate : bool, optional
1360 If False, the default, disallow an axis from being specified twice.
1362 Returns
1363 -------
1364 normalized_axes : tuple of int
1365 The normalized axis index, such that `0 <= normalized_axis < ndim`
1367 Raises
1368 ------
1369 AxisError
1370 If any axis provided is out of range
1371 ValueError
1372 If an axis is repeated
1374 See also
1375 --------
1376 normalize_axis_index : normalizing a single scalar axis
1377 """
1378 # Optimization to speed-up the most common cases.
1379 if type(axis) not in (tuple, list):
1380 try:
1381 axis = [operator.index(axis)]
1382 except TypeError:
1383 pass
1384 # Going via an iterator directly is slower than via list comprehension.
1385 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
1386 if not allow_duplicate and len(set(axis)) != len(axis):
1387 if argname:
1388 raise ValueError('repeated axis in `{}` argument'.format(argname))
1389 else:
1390 raise ValueError('repeated axis')
1391 return axis
1394def _moveaxis_dispatcher(a, source, destination):
1395 return (a,)
1398@array_function_dispatch(_moveaxis_dispatcher)
1399def moveaxis(a, source, destination):
1400 """
1401 Move axes of an array to new positions.
1403 Other axes remain in their original order.
1405 .. versionadded:: 1.11.0
1407 Parameters
1408 ----------
1409 a : np.ndarray
1410 The array whose axes should be reordered.
1411 source : int or sequence of int
1412 Original positions of the axes to move. These must be unique.
1413 destination : int or sequence of int
1414 Destination positions for each of the original axes. These must also be
1415 unique.
1417 Returns
1418 -------
1419 result : np.ndarray
1420 Array with moved axes. This array is a view of the input array.
1422 See Also
1423 --------
1424 transpose : Permute the dimensions of an array.
1425 swapaxes : Interchange two axes of an array.
1427 Examples
1428 --------
1429 >>> x = np.zeros((3, 4, 5))
1430 >>> np.moveaxis(x, 0, -1).shape
1431 (4, 5, 3)
1432 >>> np.moveaxis(x, -1, 0).shape
1433 (5, 3, 4)
1435 These all achieve the same result:
1437 >>> np.transpose(x).shape
1438 (5, 4, 3)
1439 >>> np.swapaxes(x, 0, -1).shape
1440 (5, 4, 3)
1441 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
1442 (5, 4, 3)
1443 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
1444 (5, 4, 3)
1446 """
1447 try:
1448 # allow duck-array types if they define transpose
1449 transpose = a.transpose
1450 except AttributeError:
1451 a = asarray(a)
1452 transpose = a.transpose
1454 source = normalize_axis_tuple(source, a.ndim, 'source')
1455 destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1456 if len(source) != len(destination):
1457 raise ValueError('`source` and `destination` arguments must have '
1458 'the same number of elements')
1460 order = [n for n in range(a.ndim) if n not in source]
1462 for dest, src in sorted(zip(destination, source)):
1463 order.insert(dest, src)
1465 result = transpose(order)
1466 return result
1469def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
1470 return (a, b)
1473@array_function_dispatch(_cross_dispatcher)
1474def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
1475 """
1476 Return the cross product of two (arrays of) vectors.
1478 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
1479 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
1480 are defined by the last axis of `a` and `b` by default, and these axes
1481 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
1482 2, the third component of the input vector is assumed to be zero and the
1483 cross product calculated accordingly. In cases where both input vectors
1484 have dimension 2, the z-component of the cross product is returned.
1486 Parameters
1487 ----------
1488 a : array_like
1489 Components of the first vector(s).
1490 b : array_like
1491 Components of the second vector(s).
1492 axisa : int, optional
1493 Axis of `a` that defines the vector(s). By default, the last axis.
1494 axisb : int, optional
1495 Axis of `b` that defines the vector(s). By default, the last axis.
1496 axisc : int, optional
1497 Axis of `c` containing the cross product vector(s). Ignored if
1498 both input vectors have dimension 2, as the return is scalar.
1499 By default, the last axis.
1500 axis : int, optional
1501 If defined, the axis of `a`, `b` and `c` that defines the vector(s)
1502 and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
1504 Returns
1505 -------
1506 c : ndarray
1507 Vector cross product(s).
1509 Raises
1510 ------
1511 ValueError
1512 When the dimension of the vector(s) in `a` and/or `b` does not
1513 equal 2 or 3.
1515 See Also
1516 --------
1517 inner : Inner product
1518 outer : Outer product.
1519 ix_ : Construct index arrays.
1521 Notes
1522 -----
1523 .. versionadded:: 1.9.0
1525 Supports full broadcasting of the inputs.
1527 Examples
1528 --------
1529 Vector cross-product.
1531 >>> x = [1, 2, 3]
1532 >>> y = [4, 5, 6]
1533 >>> np.cross(x, y)
1534 array([-3, 6, -3])
1536 One vector with dimension 2.
1538 >>> x = [1, 2]
1539 >>> y = [4, 5, 6]
1540 >>> np.cross(x, y)
1541 array([12, -6, -3])
1543 Equivalently:
1545 >>> x = [1, 2, 0]
1546 >>> y = [4, 5, 6]
1547 >>> np.cross(x, y)
1548 array([12, -6, -3])
1550 Both vectors with dimension 2.
1552 >>> x = [1,2]
1553 >>> y = [4,5]
1554 >>> np.cross(x, y)
1555 array(-3)
1557 Multiple vector cross-products. Note that the direction of the cross
1558 product vector is defined by the *right-hand rule*.
1560 >>> x = np.array([[1,2,3], [4,5,6]])
1561 >>> y = np.array([[4,5,6], [1,2,3]])
1562 >>> np.cross(x, y)
1563 array([[-3, 6, -3],
1564 [ 3, -6, 3]])
1566 The orientation of `c` can be changed using the `axisc` keyword.
1568 >>> np.cross(x, y, axisc=0)
1569 array([[-3, 3],
1570 [ 6, -6],
1571 [-3, 3]])
1573 Change the vector definition of `x` and `y` using `axisa` and `axisb`.
1575 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
1576 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
1577 >>> np.cross(x, y)
1578 array([[ -6, 12, -6],
1579 [ 0, 0, 0],
1580 [ 6, -12, 6]])
1581 >>> np.cross(x, y, axisa=0, axisb=0)
1582 array([[-24, 48, -24],
1583 [-30, 60, -30],
1584 [-36, 72, -36]])
1586 """
1587 if axis is not None:
1588 axisa, axisb, axisc = (axis,) * 3
1589 a = asarray(a)
1590 b = asarray(b)
1591 # Check axisa and axisb are within bounds
1592 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
1593 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
1595 # Move working axis to the end of the shape
1596 a = moveaxis(a, axisa, -1)
1597 b = moveaxis(b, axisb, -1)
1598 msg = ("incompatible dimensions for cross product\n"
1599 "(dimension must be 2 or 3)")
1600 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1601 raise ValueError(msg)
1603 # Create the output array
1604 shape = broadcast(a[..., 0], b[..., 0]).shape
1605 if a.shape[-1] == 3 or b.shape[-1] == 3:
1606 shape += (3,)
1607 # Check axisc is within bounds
1608 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
1609 dtype = promote_types(a.dtype, b.dtype)
1610 cp = empty(shape, dtype)
1612 # recast arrays as dtype
1613 a = a.astype(dtype)
1614 b = b.astype(dtype)
1616 # create local aliases for readability
1617 a0 = a[..., 0]
1618 a1 = a[..., 1]
1619 if a.shape[-1] == 3:
1620 a2 = a[..., 2]
1621 b0 = b[..., 0]
1622 b1 = b[..., 1]
1623 if b.shape[-1] == 3:
1624 b2 = b[..., 2]
1625 if cp.ndim != 0 and cp.shape[-1] == 3:
1626 cp0 = cp[..., 0]
1627 cp1 = cp[..., 1]
1628 cp2 = cp[..., 2]
1630 if a.shape[-1] == 2:
1631 if b.shape[-1] == 2:
1632 # a0 * b1 - a1 * b0
1633 multiply(a0, b1, out=cp)
1634 cp -= a1 * b0
1635 return cp
1636 else:
1637 assert b.shape[-1] == 3
1638 # cp0 = a1 * b2 - 0 (a2 = 0)
1639 # cp1 = 0 - a0 * b2 (a2 = 0)
1640 # cp2 = a0 * b1 - a1 * b0
1641 multiply(a1, b2, out=cp0)
1642 multiply(a0, b2, out=cp1)
1643 negative(cp1, out=cp1)
1644 multiply(a0, b1, out=cp2)
1645 cp2 -= a1 * b0
1646 else:
1647 assert a.shape[-1] == 3
1648 if b.shape[-1] == 3:
1649 # cp0 = a1 * b2 - a2 * b1
1650 # cp1 = a2 * b0 - a0 * b2
1651 # cp2 = a0 * b1 - a1 * b0
1652 multiply(a1, b2, out=cp0)
1653 tmp = array(a2 * b1)
1654 cp0 -= tmp
1655 multiply(a2, b0, out=cp1)
1656 multiply(a0, b2, out=tmp)
1657 cp1 -= tmp
1658 multiply(a0, b1, out=cp2)
1659 multiply(a1, b0, out=tmp)
1660 cp2 -= tmp
1661 else:
1662 assert b.shape[-1] == 2
1663 # cp0 = 0 - a2 * b1 (b2 = 0)
1664 # cp1 = a2 * b0 - 0 (b2 = 0)
1665 # cp2 = a0 * b1 - a1 * b0
1666 multiply(a2, b1, out=cp0)
1667 negative(cp0, out=cp0)
1668 multiply(a2, b0, out=cp1)
1669 multiply(a0, b1, out=cp2)
1670 cp2 -= a1 * b0
1672 return moveaxis(cp, -1, axisc)
1675little_endian = (sys.byteorder == 'little')
1678@set_module('numpy')
1679def indices(dimensions, dtype=int, sparse=False):
1680 """
1681 Return an array representing the indices of a grid.
1683 Compute an array where the subarrays contain index values 0, 1, ...
1684 varying only along the corresponding axis.
1686 Parameters
1687 ----------
1688 dimensions : sequence of ints
1689 The shape of the grid.
1690 dtype : dtype, optional
1691 Data type of the result.
1692 sparse : boolean, optional
1693 Return a sparse representation of the grid instead of a dense
1694 representation. Default is False.
1696 .. versionadded:: 1.17
1698 Returns
1699 -------
1700 grid : one ndarray or tuple of ndarrays
1701 If sparse is False:
1702 Returns one array of grid indices,
1703 ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1704 If sparse is True:
1705 Returns a tuple of arrays, with
1706 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1707 dimensions[i] in the ith place
1709 See Also
1710 --------
1711 mgrid, ogrid, meshgrid
1713 Notes
1714 -----
1715 The output shape in the dense case is obtained by prepending the number
1716 of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
1717 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
1718 ``(N, r0, ..., rN-1)``.
1720 The subarrays ``grid[k]`` contains the N-D array of indices along the
1721 ``k-th`` axis. Explicitly::
1723 grid[k, i0, i1, ..., iN-1] = ik
1725 Examples
1726 --------
1727 >>> grid = np.indices((2, 3))
1728 >>> grid.shape
1729 (2, 2, 3)
1730 >>> grid[0] # row indices
1731 array([[0, 0, 0],
1732 [1, 1, 1]])
1733 >>> grid[1] # column indices
1734 array([[0, 1, 2],
1735 [0, 1, 2]])
1737 The indices can be used as an index into an array.
1739 >>> x = np.arange(20).reshape(5, 4)
1740 >>> row, col = np.indices((2, 3))
1741 >>> x[row, col]
1742 array([[0, 1, 2],
1743 [4, 5, 6]])
1745 Note that it would be more straightforward in the above example to
1746 extract the required elements directly with ``x[:2, :3]``.
1748 If sparse is set to true, the grid will be returned in a sparse
1749 representation.
1751 >>> i, j = np.indices((2, 3), sparse=True)
1752 >>> i.shape
1753 (2, 1)
1754 >>> j.shape
1755 (1, 3)
1756 >>> i # row indices
1757 array([[0],
1758 [1]])
1759 >>> j # column indices
1760 array([[0, 1, 2]])
1762 """
1763 dimensions = tuple(dimensions)
1764 N = len(dimensions)
1765 shape = (1,)*N
1766 if sparse:
1767 res = tuple()
1768 else:
1769 res = empty((N,)+dimensions, dtype=dtype)
1770 for i, dim in enumerate(dimensions):
1771 idx = arange(dim, dtype=dtype).reshape(
1772 shape[:i] + (dim,) + shape[i+1:]
1773 )
1774 if sparse:
1775 res = res + (idx,)
1776 else:
1777 res[i] = idx
1778 return res
1781def _fromfunction_dispatcher(function, shape, *, dtype=None, like=None, **kwargs):
1782 return (like,)
1785@set_array_function_like_doc
1786@set_module('numpy')
1787def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
1788 """
1789 Construct an array by executing a function over each coordinate.
1791 The resulting array therefore has a value ``fn(x, y, z)`` at
1792 coordinate ``(x, y, z)``.
1794 Parameters
1795 ----------
1796 function : callable
1797 The function is called with N parameters, where N is the rank of
1798 `shape`. Each parameter represents the coordinates of the array
1799 varying along a specific axis. For example, if `shape`
1800 were ``(2, 2)``, then the parameters would be
1801 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
1802 shape : (N,) tuple of ints
1803 Shape of the output array, which also determines the shape of
1804 the coordinate arrays passed to `function`.
1805 dtype : data-type, optional
1806 Data-type of the coordinate arrays passed to `function`.
1807 By default, `dtype` is float.
1808 ${ARRAY_FUNCTION_LIKE}
1810 .. versionadded:: 1.20.0
1812 Returns
1813 -------
1814 fromfunction : any
1815 The result of the call to `function` is passed back directly.
1816 Therefore the shape of `fromfunction` is completely determined by
1817 `function`. If `function` returns a scalar value, the shape of
1818 `fromfunction` would not match the `shape` parameter.
1820 See Also
1821 --------
1822 indices, meshgrid
1824 Notes
1825 -----
1826 Keywords other than `dtype` and `like` are passed to `function`.
1828 Examples
1829 --------
1830 >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
1831 array([[0., 0.],
1832 [1., 1.]])
1834 >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
1835 array([[0., 1.],
1836 [0., 1.]])
1838 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
1839 array([[ True, False, False],
1840 [False, True, False],
1841 [False, False, True]])
1843 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
1844 array([[0, 1, 2],
1845 [1, 2, 3],
1846 [2, 3, 4]])
1848 """
1849 if like is not None:
1850 return _fromfunction_with_like(function, shape, dtype=dtype, like=like, **kwargs)
1852 args = indices(shape, dtype=dtype)
1853 return function(*args, **kwargs)
1856_fromfunction_with_like = array_function_dispatch(
1857 _fromfunction_dispatcher
1858)(fromfunction)
1861def _frombuffer(buf, dtype, shape, order):
1862 return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
1865@set_module('numpy')
1866def isscalar(element):
1867 """
1868 Returns True if the type of `element` is a scalar type.
1870 Parameters
1871 ----------
1872 element : any
1873 Input argument, can be of any type and shape.
1875 Returns
1876 -------
1877 val : bool
1878 True if `element` is a scalar type, False if it is not.
1880 See Also
1881 --------
1882 ndim : Get the number of dimensions of an array
1884 Notes
1885 -----
1886 If you need a stricter way to identify a *numerical* scalar, use
1887 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
1888 non-numerical elements such as strings.
1890 In most cases ``np.ndim(x) == 0`` should be used instead of this function,
1891 as that will also return true for 0d arrays. This is how numpy overloads
1892 functions in the style of the ``dx`` arguments to `gradient` and the ``bins``
1893 argument to `histogram`. Some key differences:
1895 +--------------------------------------+---------------+-------------------+
1896 | x |``isscalar(x)``|``np.ndim(x) == 0``|
1897 +======================================+===============+===================+
1898 | PEP 3141 numeric objects (including | ``True`` | ``True`` |
1899 | builtins) | | |
1900 +--------------------------------------+---------------+-------------------+
1901 | builtin string and buffer objects | ``True`` | ``True`` |
1902 +--------------------------------------+---------------+-------------------+
1903 | other builtin objects, like | ``False`` | ``True`` |
1904 | `pathlib.Path`, `Exception`, | | |
1905 | the result of `re.compile` | | |
1906 +--------------------------------------+---------------+-------------------+
1907 | third-party objects like | ``False`` | ``True`` |
1908 | `matplotlib.figure.Figure` | | |
1909 +--------------------------------------+---------------+-------------------+
1910 | zero-dimensional numpy arrays | ``False`` | ``True`` |
1911 +--------------------------------------+---------------+-------------------+
1912 | other numpy arrays | ``False`` | ``False`` |
1913 +--------------------------------------+---------------+-------------------+
1914 | `list`, `tuple`, and other sequence | ``False`` | ``False`` |
1915 | objects | | |
1916 +--------------------------------------+---------------+-------------------+
1918 Examples
1919 --------
1920 >>> np.isscalar(3.1)
1921 True
1922 >>> np.isscalar(np.array(3.1))
1923 False
1924 >>> np.isscalar([3.1])
1925 False
1926 >>> np.isscalar(False)
1927 True
1928 >>> np.isscalar('numpy')
1929 True
1931 NumPy supports PEP 3141 numbers:
1933 >>> from fractions import Fraction
1934 >>> np.isscalar(Fraction(5, 17))
1935 True
1936 >>> from numbers import Number
1937 >>> np.isscalar(Number())
1938 True
1940 """
1941 return (isinstance(element, generic)
1942 or type(element) in ScalarType
1943 or isinstance(element, numbers.Number))
1946@set_module('numpy')
1947def binary_repr(num, width=None):
1948 """
1949 Return the binary representation of the input number as a string.
1951 For negative numbers, if width is not given, a minus sign is added to the
1952 front. If width is given, the two's complement of the number is
1953 returned, with respect to that width.
1955 In a two's-complement system negative numbers are represented by the two's
1956 complement of the absolute value. This is the most common method of
1957 representing signed integers on computers [1]_. A N-bit two's-complement
1958 system can represent every integer in the range
1959 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
1961 Parameters
1962 ----------
1963 num : int
1964 Only an integer decimal number can be used.
1965 width : int, optional
1966 The length of the returned string if `num` is positive, or the length
1967 of the two's complement if `num` is negative, provided that `width` is
1968 at least a sufficient number of bits for `num` to be represented in the
1969 designated form.
1971 If the `width` value is insufficient, it will be ignored, and `num` will
1972 be returned in binary (`num` > 0) or two's complement (`num` < 0) form
1973 with its width equal to the minimum number of bits needed to represent
1974 the number in the designated form. This behavior is deprecated and will
1975 later raise an error.
1977 .. deprecated:: 1.12.0
1979 Returns
1980 -------
1981 bin : str
1982 Binary representation of `num` or two's complement of `num`.
1984 See Also
1985 --------
1986 base_repr: Return a string representation of a number in the given base
1987 system.
1988 bin: Python's built-in binary representation generator of an integer.
1990 Notes
1991 -----
1992 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
1993 faster.
1995 References
1996 ----------
1997 .. [1] Wikipedia, "Two's complement",
1998 https://en.wikipedia.org/wiki/Two's_complement
2000 Examples
2001 --------
2002 >>> np.binary_repr(3)
2003 '11'
2004 >>> np.binary_repr(-3)
2005 '-11'
2006 >>> np.binary_repr(3, width=4)
2007 '0011'
2009 The two's complement is returned when the input number is negative and
2010 width is specified:
2012 >>> np.binary_repr(-3, width=3)
2013 '101'
2014 >>> np.binary_repr(-3, width=5)
2015 '11101'
2017 """
2018 def warn_if_insufficient(width, binwidth):
2019 if width is not None and width < binwidth:
2020 warnings.warn(
2021 "Insufficient bit width provided. This behavior "
2022 "will raise an error in the future.", DeprecationWarning,
2023 stacklevel=3)
2025 # Ensure that num is a Python integer to avoid overflow or unwanted
2026 # casts to floating point.
2027 num = operator.index(num)
2029 if num == 0:
2030 return '0' * (width or 1)
2032 elif num > 0:
2033 binary = bin(num)[2:]
2034 binwidth = len(binary)
2035 outwidth = (binwidth if width is None
2036 else max(binwidth, width))
2037 warn_if_insufficient(width, binwidth)
2038 return binary.zfill(outwidth)
2040 else:
2041 if width is None:
2042 return '-' + bin(-num)[2:]
2044 else:
2045 poswidth = len(bin(-num)[2:])
2047 # See gh-8679: remove extra digit
2048 # for numbers at boundaries.
2049 if 2**(poswidth - 1) == -num:
2050 poswidth -= 1
2052 twocomp = 2**(poswidth + 1) + num
2053 binary = bin(twocomp)[2:]
2054 binwidth = len(binary)
2056 outwidth = max(binwidth, width)
2057 warn_if_insufficient(width, binwidth)
2058 return '1' * (outwidth - binwidth) + binary
2061@set_module('numpy')
2062def base_repr(number, base=2, padding=0):
2063 """
2064 Return a string representation of a number in the given base system.
2066 Parameters
2067 ----------
2068 number : int
2069 The value to convert. Positive and negative values are handled.
2070 base : int, optional
2071 Convert `number` to the `base` number system. The valid range is 2-36,
2072 the default value is 2.
2073 padding : int, optional
2074 Number of zeros padded on the left. Default is 0 (no padding).
2076 Returns
2077 -------
2078 out : str
2079 String representation of `number` in `base` system.
2081 See Also
2082 --------
2083 binary_repr : Faster version of `base_repr` for base 2.
2085 Examples
2086 --------
2087 >>> np.base_repr(5)
2088 '101'
2089 >>> np.base_repr(6, 5)
2090 '11'
2091 >>> np.base_repr(7, base=5, padding=3)
2092 '00012'
2094 >>> np.base_repr(10, base=16)
2095 'A'
2096 >>> np.base_repr(32, base=16)
2097 '20'
2099 """
2100 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2101 if base > len(digits):
2102 raise ValueError("Bases greater than 36 not handled in base_repr.")
2103 elif base < 2:
2104 raise ValueError("Bases less than 2 not handled in base_repr.")
2106 num = abs(number)
2107 res = []
2108 while num:
2109 res.append(digits[num % base])
2110 num //= base
2111 if padding:
2112 res.append('0' * padding)
2113 if number < 0:
2114 res.append('-')
2115 return ''.join(reversed(res or '0'))
2118# These are all essentially abbreviations
2119# These might wind up in a special abbreviations module
2122def _maketup(descr, val):
2123 dt = dtype(descr)
2124 # Place val in all scalar tuples:
2125 fields = dt.fields
2126 if fields is None:
2127 return val
2128 else:
2129 res = [_maketup(fields[name][0], val) for name in dt.names]
2130 return tuple(res)
2133def _identity_dispatcher(n, dtype=None, *, like=None):
2134 return (like,)
2137@set_array_function_like_doc
2138@set_module('numpy')
2139def identity(n, dtype=None, *, like=None):
2140 """
2141 Return the identity array.
2143 The identity array is a square array with ones on
2144 the main diagonal.
2146 Parameters
2147 ----------
2148 n : int
2149 Number of rows (and columns) in `n` x `n` output.
2150 dtype : data-type, optional
2151 Data-type of the output. Defaults to ``float``.
2152 ${ARRAY_FUNCTION_LIKE}
2154 .. versionadded:: 1.20.0
2156 Returns
2157 -------
2158 out : ndarray
2159 `n` x `n` array with its main diagonal set to one,
2160 and all other elements 0.
2162 Examples
2163 --------
2164 >>> np.identity(3)
2165 array([[1., 0., 0.],
2166 [0., 1., 0.],
2167 [0., 0., 1.]])
2169 """
2170 if like is not None:
2171 return _identity_with_like(n, dtype=dtype, like=like)
2173 from numpy import eye
2174 return eye(n, dtype=dtype, like=like)
2177_identity_with_like = array_function_dispatch(
2178 _identity_dispatcher
2179)(identity)
2182def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2183 return (a, b)
2186@array_function_dispatch(_allclose_dispatcher)
2187def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2188 """
2189 Returns True if two arrays are element-wise equal within a tolerance.
2191 The tolerance values are positive, typically very small numbers. The
2192 relative difference (`rtol` * abs(`b`)) and the absolute difference
2193 `atol` are added together to compare against the absolute difference
2194 between `a` and `b`.
2196 NaNs are treated as equal if they are in the same place and if
2197 ``equal_nan=True``. Infs are treated as equal if they are in the same
2198 place and of the same sign in both arrays.
2200 Parameters
2201 ----------
2202 a, b : array_like
2203 Input arrays to compare.
2204 rtol : float
2205 The relative tolerance parameter (see Notes).
2206 atol : float
2207 The absolute tolerance parameter (see Notes).
2208 equal_nan : bool
2209 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2210 considered equal to NaN's in `b` in the output array.
2212 .. versionadded:: 1.10.0
2214 Returns
2215 -------
2216 allclose : bool
2217 Returns True if the two arrays are equal within the given
2218 tolerance; False otherwise.
2220 See Also
2221 --------
2222 isclose, all, any, equal
2224 Notes
2225 -----
2226 If the following equation is element-wise True, then allclose returns
2227 True.
2229 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2231 The above equation is not symmetric in `a` and `b`, so that
2232 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
2233 some rare cases.
2235 The comparison of `a` and `b` uses standard broadcasting, which
2236 means that `a` and `b` need not have the same shape in order for
2237 ``allclose(a, b)`` to evaluate to True. The same is true for
2238 `equal` but not `array_equal`.
2240 `allclose` is not defined for non-numeric data types.
2241 `bool` is considered a numeric data-type for this purpose.
2243 Examples
2244 --------
2245 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
2246 False
2247 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
2248 True
2249 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
2250 False
2251 >>> np.allclose([1.0, np.nan], [1.0, np.nan])
2252 False
2253 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2254 True
2256 """
2257 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2258 return bool(res)
2261def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2262 return (a, b)
2265@array_function_dispatch(_isclose_dispatcher)
2266def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2267 """
2268 Returns a boolean array where two arrays are element-wise equal within a
2269 tolerance.
2271 The tolerance values are positive, typically very small numbers. The
2272 relative difference (`rtol` * abs(`b`)) and the absolute difference
2273 `atol` are added together to compare against the absolute difference
2274 between `a` and `b`.
2276 .. warning:: The default `atol` is not appropriate for comparing numbers
2277 that are much smaller than one (see Notes).
2279 Parameters
2280 ----------
2281 a, b : array_like
2282 Input arrays to compare.
2283 rtol : float
2284 The relative tolerance parameter (see Notes).
2285 atol : float
2286 The absolute tolerance parameter (see Notes).
2287 equal_nan : bool
2288 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2289 considered equal to NaN's in `b` in the output array.
2291 Returns
2292 -------
2293 y : array_like
2294 Returns a boolean array of where `a` and `b` are equal within the
2295 given tolerance. If both `a` and `b` are scalars, returns a single
2296 boolean value.
2298 See Also
2299 --------
2300 allclose
2301 math.isclose
2303 Notes
2304 -----
2305 .. versionadded:: 1.7.0
2307 For finite values, isclose uses the following equation to test whether
2308 two floating point values are equivalent.
2310 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2312 Unlike the built-in `math.isclose`, the above equation is not symmetric
2313 in `a` and `b` -- it assumes `b` is the reference value -- so that
2314 `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
2315 the default value of atol is not zero, and is used to determine what
2316 small values should be considered close to zero. The default value is
2317 appropriate for expected values of order unity: if the expected values
2318 are significantly smaller than one, it can result in false positives.
2319 `atol` should be carefully selected for the use case at hand. A zero value
2320 for `atol` will result in `False` if either `a` or `b` is zero.
2322 `isclose` is not defined for non-numeric data types.
2323 `bool` is considered a numeric data-type for this purpose.
2325 Examples
2326 --------
2327 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
2328 array([ True, False])
2329 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
2330 array([ True, True])
2331 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
2332 array([False, True])
2333 >>> np.isclose([1.0, np.nan], [1.0, np.nan])
2334 array([ True, False])
2335 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2336 array([ True, True])
2337 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
2338 array([ True, False])
2339 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
2340 array([False, False])
2341 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
2342 array([ True, True])
2343 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
2344 array([False, True])
2345 """
2346 def within_tol(x, y, atol, rtol):
2347 with errstate(invalid='ignore'), _no_nep50_warning():
2348 return less_equal(abs(x-y), atol + rtol * abs(y))
2350 x = asanyarray(a)
2351 y = asanyarray(b)
2353 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
2354 # This will cause casting of x later. Also, make sure to allow subclasses
2355 # (e.g., for numpy.ma).
2356 # NOTE: We explicitly allow timedelta, which used to work. This could
2357 # possibly be deprecated. See also gh-18286.
2358 # timedelta works if `atol` is an integer or also a timedelta.
2359 # Although, the default tolerances are unlikely to be useful
2360 if y.dtype.kind != "m":
2361 dt = multiarray.result_type(y, 1.)
2362 y = asanyarray(y, dtype=dt)
2364 xfin = isfinite(x)
2365 yfin = isfinite(y)
2366 if all(xfin) and all(yfin):
2367 return within_tol(x, y, atol, rtol)
2368 else:
2369 finite = xfin & yfin
2370 cond = zeros_like(finite, subok=True)
2371 # Because we're using boolean indexing, x & y must be the same shape.
2372 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
2373 # lib.stride_tricks, though, so we can't import it here.
2374 x = x * ones_like(cond)
2375 y = y * ones_like(cond)
2376 # Avoid subtraction with infinite/nan values...
2377 cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
2378 # Check for equality of infinite values...
2379 cond[~finite] = (x[~finite] == y[~finite])
2380 if equal_nan:
2381 # Make NaN == NaN
2382 both_nan = isnan(x) & isnan(y)
2384 # Needed to treat masked arrays correctly. = True would not work.
2385 cond[both_nan] = both_nan[both_nan]
2387 return cond[()] # Flatten 0d arrays to scalars
2390def _array_equal_dispatcher(a1, a2, equal_nan=None):
2391 return (a1, a2)
2394@array_function_dispatch(_array_equal_dispatcher)
2395def array_equal(a1, a2, equal_nan=False):
2396 """
2397 True if two arrays have the same shape and elements, False otherwise.
2399 Parameters
2400 ----------
2401 a1, a2 : array_like
2402 Input arrays.
2403 equal_nan : bool
2404 Whether to compare NaN's as equal. If the dtype of a1 and a2 is
2405 complex, values will be considered equal if either the real or the
2406 imaginary component of a given value is ``nan``.
2408 .. versionadded:: 1.19.0
2410 Returns
2411 -------
2412 b : bool
2413 Returns True if the arrays are equal.
2415 See Also
2416 --------
2417 allclose: Returns True if two arrays are element-wise equal within a
2418 tolerance.
2419 array_equiv: Returns True if input arrays are shape consistent and all
2420 elements equal.
2422 Examples
2423 --------
2424 >>> np.array_equal([1, 2], [1, 2])
2425 True
2426 >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
2427 True
2428 >>> np.array_equal([1, 2], [1, 2, 3])
2429 False
2430 >>> np.array_equal([1, 2], [1, 4])
2431 False
2432 >>> a = np.array([1, np.nan])
2433 >>> np.array_equal(a, a)
2434 False
2435 >>> np.array_equal(a, a, equal_nan=True)
2436 True
2438 When ``equal_nan`` is True, complex values with nan components are
2439 considered equal if either the real *or* the imaginary components are nan.
2441 >>> a = np.array([1 + 1j])
2442 >>> b = a.copy()
2443 >>> a.real = np.nan
2444 >>> b.imag = np.nan
2445 >>> np.array_equal(a, b, equal_nan=True)
2446 True
2447 """
2448 try:
2449 a1, a2 = asarray(a1), asarray(a2)
2450 except Exception:
2451 return False
2452 if a1.shape != a2.shape:
2453 return False
2454 if not equal_nan:
2455 return bool(asarray(a1 == a2).all())
2456 # Handling NaN values if equal_nan is True
2457 a1nan, a2nan = isnan(a1), isnan(a2)
2458 # NaN's occur at different locations
2459 if not (a1nan == a2nan).all():
2460 return False
2461 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
2462 return bool(asarray(a1[~a1nan] == a2[~a1nan]).all())
2465def _array_equiv_dispatcher(a1, a2):
2466 return (a1, a2)
2469@array_function_dispatch(_array_equiv_dispatcher)
2470def array_equiv(a1, a2):
2471 """
2472 Returns True if input arrays are shape consistent and all elements equal.
2474 Shape consistent means they are either the same shape, or one input array
2475 can be broadcasted to create the same shape as the other one.
2477 Parameters
2478 ----------
2479 a1, a2 : array_like
2480 Input arrays.
2482 Returns
2483 -------
2484 out : bool
2485 True if equivalent, False otherwise.
2487 Examples
2488 --------
2489 >>> np.array_equiv([1, 2], [1, 2])
2490 True
2491 >>> np.array_equiv([1, 2], [1, 3])
2492 False
2494 Showing the shape equivalence:
2496 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
2497 True
2498 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
2499 False
2501 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
2502 False
2504 """
2505 try:
2506 a1, a2 = asarray(a1), asarray(a2)
2507 except Exception:
2508 return False
2509 try:
2510 multiarray.broadcast(a1, a2)
2511 except Exception:
2512 return False
2514 return bool(asarray(a1 == a2).all())
2517Inf = inf = infty = Infinity = PINF
2518nan = NaN = NAN
2519False_ = bool_(False)
2520True_ = bool_(True)
2523def extend_all(module):
2524 existing = set(__all__)
2525 mall = getattr(module, '__all__')
2526 for a in mall:
2527 if a not in existing:
2528 __all__.append(a)
2531from .umath import *
2532from .numerictypes import *
2533from . import fromnumeric
2534from .fromnumeric import *
2535from . import arrayprint
2536from .arrayprint import *
2537from . import _asarray
2538from ._asarray import *
2539from . import _ufunc_config
2540from ._ufunc_config import *
2541extend_all(fromnumeric)
2542extend_all(umath)
2543extend_all(numerictypes)
2544extend_all(arrayprint)
2545extend_all(_asarray)
2546extend_all(_ufunc_config)