Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/numpy/core/numeric.py: 23%
493 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import functools
2import itertools
3import operator
4import sys
5import warnings
6import numbers
8import numpy as np
9from . import multiarray
10from .multiarray import (
11 _fastCopyAndTranspose as 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)
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 TooHardError, AxisError
30from ._ufunc_config import errstate
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', 'ComplexWarning', 'full', 'full_like',
56 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS',
57 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError']
60@set_module('numpy')
61class ComplexWarning(RuntimeWarning):
62 """
63 The warning raised when casting a complex dtype to a real dtype.
65 As implemented, casting a complex number to a real discards its imaginary
66 part, but this behavior may not be what the user actually wants.
68 """
69 pass
72def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
73 return (a,)
76@array_function_dispatch(_zeros_like_dispatcher)
77def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
78 """
79 Return an array of zeros with the same shape and type as a given array.
81 Parameters
82 ----------
83 a : array_like
84 The shape and data-type of `a` define these same attributes of
85 the returned array.
86 dtype : data-type, optional
87 Overrides the data type of the result.
89 .. versionadded:: 1.6.0
90 order : {'C', 'F', 'A', or 'K'}, optional
91 Overrides the memory layout of the result. 'C' means C-order,
92 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
93 'C' otherwise. 'K' means match the layout of `a` as closely
94 as possible.
96 .. versionadded:: 1.6.0
97 subok : bool, optional.
98 If True, then the newly created array will use the sub-class
99 type of `a`, otherwise it will be a base-class array. Defaults
100 to True.
101 shape : int or sequence of ints, optional.
102 Overrides the shape of the result. If order='K' and the number of
103 dimensions is unchanged, will try to keep order, otherwise,
104 order='C' is implied.
106 .. versionadded:: 1.17.0
108 Returns
109 -------
110 out : ndarray
111 Array of zeros with the same shape and type as `a`.
113 See Also
114 --------
115 empty_like : Return an empty array with shape and type of input.
116 ones_like : Return an array of ones with shape and type of input.
117 full_like : Return a new array with shape of input filled with value.
118 zeros : Return a new array setting values to zero.
120 Examples
121 --------
122 >>> x = np.arange(6)
123 >>> x = x.reshape((2, 3))
124 >>> x
125 array([[0, 1, 2],
126 [3, 4, 5]])
127 >>> np.zeros_like(x)
128 array([[0, 0, 0],
129 [0, 0, 0]])
131 >>> y = np.arange(3, dtype=float)
132 >>> y
133 array([0., 1., 2.])
134 >>> np.zeros_like(y)
135 array([0., 0., 0.])
137 """
138 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
139 # needed instead of a 0 to get same result as zeros for string dtypes
140 z = zeros(1, dtype=res.dtype)
141 multiarray.copyto(res, z, casting='unsafe')
142 return res
145def _ones_dispatcher(shape, dtype=None, order=None, *, like=None):
146 return(like,)
149@set_array_function_like_doc
150@set_module('numpy')
151def ones(shape, dtype=None, order='C', *, like=None):
152 """
153 Return a new array of given shape and type, filled with ones.
155 Parameters
156 ----------
157 shape : int or sequence of ints
158 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
159 dtype : data-type, optional
160 The desired data-type for the array, e.g., `numpy.int8`. Default is
161 `numpy.float64`.
162 order : {'C', 'F'}, optional, default: C
163 Whether to store multi-dimensional data in row-major
164 (C-style) or column-major (Fortran-style) order in
165 memory.
166 ${ARRAY_FUNCTION_LIKE}
168 .. versionadded:: 1.20.0
170 Returns
171 -------
172 out : ndarray
173 Array of ones with the given shape, dtype, and order.
175 See Also
176 --------
177 ones_like : Return an array of ones with shape and type of input.
178 empty : Return a new uninitialized array.
179 zeros : Return a new array setting values to zero.
180 full : Return a new array of given shape filled with value.
183 Examples
184 --------
185 >>> np.ones(5)
186 array([1., 1., 1., 1., 1.])
188 >>> np.ones((5,), dtype=int)
189 array([1, 1, 1, 1, 1])
191 >>> np.ones((2, 1))
192 array([[1.],
193 [1.]])
195 >>> s = (2,2)
196 >>> np.ones(s)
197 array([[1., 1.],
198 [1., 1.]])
200 """
201 if like is not None: 201 ↛ 202line 201 didn't jump to line 202, because the condition on line 201 was never true
202 return _ones_with_like(shape, dtype=dtype, order=order, like=like)
204 a = empty(shape, dtype, order)
205 multiarray.copyto(a, 1, casting='unsafe')
206 return a
209_ones_with_like = array_function_dispatch(
210 _ones_dispatcher
211)(ones)
214def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
215 return (a,)
218@array_function_dispatch(_ones_like_dispatcher)
219def ones_like(a, dtype=None, order='K', subok=True, shape=None):
220 """
221 Return an array of ones with the same shape and type as a given array.
223 Parameters
224 ----------
225 a : array_like
226 The shape and data-type of `a` define these same attributes of
227 the returned array.
228 dtype : data-type, optional
229 Overrides the data type of the result.
231 .. versionadded:: 1.6.0
232 order : {'C', 'F', 'A', or 'K'}, optional
233 Overrides the memory layout of the result. 'C' means C-order,
234 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
235 'C' otherwise. 'K' means match the layout of `a` as closely
236 as possible.
238 .. versionadded:: 1.6.0
239 subok : bool, optional.
240 If True, then the newly created array will use the sub-class
241 type of `a`, otherwise it will be a base-class array. Defaults
242 to True.
243 shape : int or sequence of ints, optional.
244 Overrides the shape of the result. If order='K' and the number of
245 dimensions is unchanged, will try to keep order, otherwise,
246 order='C' is implied.
248 .. versionadded:: 1.17.0
250 Returns
251 -------
252 out : ndarray
253 Array of ones with the same shape and type as `a`.
255 See Also
256 --------
257 empty_like : Return an empty array with shape and type of input.
258 zeros_like : Return an array of zeros with shape and type of input.
259 full_like : Return a new array with shape of input filled with value.
260 ones : Return a new array setting values to one.
262 Examples
263 --------
264 >>> x = np.arange(6)
265 >>> x = x.reshape((2, 3))
266 >>> x
267 array([[0, 1, 2],
268 [3, 4, 5]])
269 >>> np.ones_like(x)
270 array([[1, 1, 1],
271 [1, 1, 1]])
273 >>> y = np.arange(3, dtype=float)
274 >>> y
275 array([0., 1., 2.])
276 >>> np.ones_like(y)
277 array([1., 1., 1.])
279 """
280 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
281 multiarray.copyto(res, 1, casting='unsafe')
282 return res
285def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, like=None):
286 return(like,)
289@set_array_function_like_doc
290@set_module('numpy')
291def full(shape, fill_value, dtype=None, order='C', *, like=None):
292 """
293 Return a new array of given shape and type, filled with `fill_value`.
295 Parameters
296 ----------
297 shape : int or sequence of ints
298 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
299 fill_value : scalar or array_like
300 Fill value.
301 dtype : data-type, optional
302 The desired data-type for the array The default, None, means
303 ``np.array(fill_value).dtype``.
304 order : {'C', 'F'}, optional
305 Whether to store multidimensional data in C- or Fortran-contiguous
306 (row- or column-wise) order in memory.
307 ${ARRAY_FUNCTION_LIKE}
309 .. versionadded:: 1.20.0
311 Returns
312 -------
313 out : ndarray
314 Array of `fill_value` with the given shape, dtype, and order.
316 See Also
317 --------
318 full_like : Return a new array with shape of input filled with value.
319 empty : Return a new uninitialized array.
320 ones : Return a new array setting values to one.
321 zeros : Return a new array setting values to zero.
323 Examples
324 --------
325 >>> np.full((2, 2), np.inf)
326 array([[inf, inf],
327 [inf, inf]])
328 >>> np.full((2, 2), 10)
329 array([[10, 10],
330 [10, 10]])
332 >>> np.full((2, 2), [1, 2])
333 array([[1, 2],
334 [1, 2]])
336 """
337 if like is not None:
338 return _full_with_like(shape, fill_value, dtype=dtype, order=order, like=like)
340 if dtype is None:
341 fill_value = asarray(fill_value)
342 dtype = fill_value.dtype
343 a = empty(shape, dtype, order)
344 multiarray.copyto(a, fill_value, casting='unsafe')
345 return a
348_full_with_like = array_function_dispatch(
349 _full_dispatcher
350)(full)
353def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None):
354 return (a,)
357@array_function_dispatch(_full_like_dispatcher)
358def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
359 """
360 Return a full array with the same shape and type as a given array.
362 Parameters
363 ----------
364 a : array_like
365 The shape and data-type of `a` define these same attributes of
366 the returned array.
367 fill_value : array_like
368 Fill value.
369 dtype : data-type, optional
370 Overrides the data type of the result.
371 order : {'C', 'F', 'A', or 'K'}, optional
372 Overrides the memory layout of the result. 'C' means C-order,
373 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
374 'C' otherwise. 'K' means match the layout of `a` as closely
375 as possible.
376 subok : bool, optional.
377 If True, then the newly created array will use the sub-class
378 type of `a`, otherwise it will be a base-class array. Defaults
379 to True.
380 shape : int or sequence of ints, optional.
381 Overrides the shape of the result. If order='K' and the number of
382 dimensions is unchanged, will try to keep order, otherwise,
383 order='C' is implied.
385 .. versionadded:: 1.17.0
387 Returns
388 -------
389 out : ndarray
390 Array of `fill_value` with the same shape and type as `a`.
392 See Also
393 --------
394 empty_like : Return an empty array with shape and type of input.
395 ones_like : Return an array of ones with shape and type of input.
396 zeros_like : Return an array of zeros with shape and type of input.
397 full : Return a new array of given shape filled with value.
399 Examples
400 --------
401 >>> x = np.arange(6, dtype=int)
402 >>> np.full_like(x, 1)
403 array([1, 1, 1, 1, 1, 1])
404 >>> np.full_like(x, 0.1)
405 array([0, 0, 0, 0, 0, 0])
406 >>> np.full_like(x, 0.1, dtype=np.double)
407 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
408 >>> np.full_like(x, np.nan, dtype=np.double)
409 array([nan, nan, nan, nan, nan, nan])
411 >>> y = np.arange(6, dtype=np.double)
412 >>> np.full_like(y, 0.1)
413 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
415 >>> y = np.zeros([2, 2, 3], dtype=int)
416 >>> np.full_like(y, [0, 0, 255])
417 array([[[ 0, 0, 255],
418 [ 0, 0, 255]],
419 [[ 0, 0, 255],
420 [ 0, 0, 255]]])
421 """
422 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
423 multiarray.copyto(res, fill_value, casting='unsafe')
424 return res
427def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
428 return (a,)
431@array_function_dispatch(_count_nonzero_dispatcher)
432def count_nonzero(a, axis=None, *, keepdims=False):
433 """
434 Counts the number of non-zero values in the array ``a``.
436 The word "non-zero" is in reference to the Python 2.x
437 built-in method ``__nonzero__()`` (renamed ``__bool__()``
438 in Python 3.x) of Python objects that tests an object's
439 "truthfulness". For example, any number is considered
440 truthful if it is nonzero, whereas any string is considered
441 truthful if it is not the empty string. Thus, this function
442 (recursively) counts how many elements in ``a`` (and in
443 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
444 method evaluated to ``True``.
446 Parameters
447 ----------
448 a : array_like
449 The array for which to count non-zeros.
450 axis : int or tuple, optional
451 Axis or tuple of axes along which to count non-zeros.
452 Default is None, meaning that non-zeros will be counted
453 along a flattened version of ``a``.
455 .. versionadded:: 1.12.0
457 keepdims : bool, optional
458 If this is set to True, the axes that are counted are left
459 in the result as dimensions with size one. With this option,
460 the result will broadcast correctly against the input array.
462 .. versionadded:: 1.19.0
464 Returns
465 -------
466 count : int or array of int
467 Number of non-zero values in the array along a given axis.
468 Otherwise, the total number of non-zero values in the array
469 is returned.
471 See Also
472 --------
473 nonzero : Return the coordinates of all the non-zero values.
475 Examples
476 --------
477 >>> np.count_nonzero(np.eye(4))
478 4
479 >>> a = np.array([[0, 1, 7, 0],
480 ... [3, 0, 2, 19]])
481 >>> np.count_nonzero(a)
482 5
483 >>> np.count_nonzero(a, axis=0)
484 array([1, 1, 2, 1])
485 >>> np.count_nonzero(a, axis=1)
486 array([2, 3])
487 >>> np.count_nonzero(a, axis=1, keepdims=True)
488 array([[2],
489 [3]])
490 """
491 if axis is None and not keepdims:
492 return multiarray.count_nonzero(a)
494 a = asanyarray(a)
496 # TODO: this works around .astype(bool) not working properly (gh-9847)
497 if np.issubdtype(a.dtype, np.character):
498 a_bool = a != a.dtype.type()
499 else:
500 a_bool = a.astype(np.bool_, copy=False)
502 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
505@set_module('numpy')
506def isfortran(a):
507 """
508 Check if the array is Fortran contiguous but *not* C contiguous.
510 This function is obsolete and, because of changes due to relaxed stride
511 checking, its return value for the same array may differ for versions
512 of NumPy >= 1.10.0 and previous versions. If you only want to check if an
513 array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
515 Parameters
516 ----------
517 a : ndarray
518 Input array.
520 Returns
521 -------
522 isfortran : bool
523 Returns True if the array is Fortran contiguous but *not* C contiguous.
526 Examples
527 --------
529 np.array allows to specify whether the array is written in C-contiguous
530 order (last index varies the fastest), or FORTRAN-contiguous order in
531 memory (first index varies the fastest).
533 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
534 >>> a
535 array([[1, 2, 3],
536 [4, 5, 6]])
537 >>> np.isfortran(a)
538 False
540 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
541 >>> b
542 array([[1, 2, 3],
543 [4, 5, 6]])
544 >>> np.isfortran(b)
545 True
548 The transpose of a C-ordered array is a FORTRAN-ordered array.
550 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
551 >>> a
552 array([[1, 2, 3],
553 [4, 5, 6]])
554 >>> np.isfortran(a)
555 False
556 >>> b = a.T
557 >>> b
558 array([[1, 4],
559 [2, 5],
560 [3, 6]])
561 >>> np.isfortran(b)
562 True
564 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
566 >>> np.isfortran(np.array([1, 2], order='F'))
567 False
569 """
570 return a.flags.fnc
573def _argwhere_dispatcher(a):
574 return (a,)
577@array_function_dispatch(_argwhere_dispatcher)
578def argwhere(a):
579 """
580 Find the indices of array elements that are non-zero, grouped by element.
582 Parameters
583 ----------
584 a : array_like
585 Input data.
587 Returns
588 -------
589 index_array : (N, a.ndim) ndarray
590 Indices of elements that are non-zero. Indices are grouped by element.
591 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
592 non-zero items.
594 See Also
595 --------
596 where, nonzero
598 Notes
599 -----
600 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
601 but produces a result of the correct shape for a 0D array.
603 The output of ``argwhere`` is not suitable for indexing arrays.
604 For this purpose use ``nonzero(a)`` instead.
606 Examples
607 --------
608 >>> x = np.arange(6).reshape(2,3)
609 >>> x
610 array([[0, 1, 2],
611 [3, 4, 5]])
612 >>> np.argwhere(x>1)
613 array([[0, 2],
614 [1, 0],
615 [1, 1],
616 [1, 2]])
618 """
619 # nonzero does not behave well on 0d, so promote to 1d
620 if np.ndim(a) == 0:
621 a = shape_base.atleast_1d(a)
622 # then remove the added dimension
623 return argwhere(a)[:,:0]
624 return transpose(nonzero(a))
627def _flatnonzero_dispatcher(a):
628 return (a,)
631@array_function_dispatch(_flatnonzero_dispatcher)
632def flatnonzero(a):
633 """
634 Return indices that are non-zero in the flattened version of a.
636 This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
638 Parameters
639 ----------
640 a : array_like
641 Input data.
643 Returns
644 -------
645 res : ndarray
646 Output array, containing the indices of the elements of ``a.ravel()``
647 that are non-zero.
649 See Also
650 --------
651 nonzero : Return the indices of the non-zero elements of the input array.
652 ravel : Return a 1-D array containing the elements of the input array.
654 Examples
655 --------
656 >>> x = np.arange(-2, 3)
657 >>> x
658 array([-2, -1, 0, 1, 2])
659 >>> np.flatnonzero(x)
660 array([0, 1, 3, 4])
662 Use the indices of the non-zero elements as an index array to extract
663 these elements:
665 >>> x.ravel()[np.flatnonzero(x)]
666 array([-2, -1, 1, 2])
668 """
669 return np.nonzero(np.ravel(a))[0]
672def _correlate_dispatcher(a, v, mode=None):
673 return (a, v)
676@array_function_dispatch(_correlate_dispatcher)
677def correlate(a, v, mode='valid'):
678 r"""
679 Cross-correlation of two 1-dimensional sequences.
681 This function computes the correlation as generally defined in signal
682 processing texts:
684 .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v_n}
686 with a and v sequences being zero-padded where necessary and
687 :math:`\overline x` denoting complex conjugation.
689 Parameters
690 ----------
691 a, v : array_like
692 Input sequences.
693 mode : {'valid', 'same', 'full'}, optional
694 Refer to the `convolve` docstring. Note that the default
695 is 'valid', unlike `convolve`, which uses 'full'.
696 old_behavior : bool
697 `old_behavior` was removed in NumPy 1.10. If you need the old
698 behavior, use `multiarray.correlate`.
700 Returns
701 -------
702 out : ndarray
703 Discrete cross-correlation of `a` and `v`.
705 See Also
706 --------
707 convolve : Discrete, linear convolution of two one-dimensional sequences.
708 multiarray.correlate : Old, no conjugate, version of correlate.
709 scipy.signal.correlate : uses FFT which has superior performance on large arrays.
711 Notes
712 -----
713 The definition of correlation above is not unique and sometimes correlation
714 may be defined differently. Another common definition is:
716 .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
718 which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
720 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does
721 not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might
722 be preferable.
725 Examples
726 --------
727 >>> np.correlate([1, 2, 3], [0, 1, 0.5])
728 array([3.5])
729 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
730 array([2. , 3.5, 3. ])
731 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
732 array([0.5, 2. , 3.5, 3. , 0. ])
734 Using complex sequences:
736 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
737 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
739 Note that you get the time reversed, complex conjugated result
740 (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
741 places:
743 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
744 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
746 """
747 return multiarray.correlate2(a, v, mode)
750def _convolve_dispatcher(a, v, mode=None):
751 return (a, v)
754@array_function_dispatch(_convolve_dispatcher)
755def convolve(a, v, mode='full'):
756 """
757 Returns the discrete, linear convolution of two one-dimensional sequences.
759 The convolution operator is often seen in signal processing, where it
760 models the effect of a linear time-invariant system on a signal [1]_. In
761 probability theory, the sum of two independent random variables is
762 distributed according to the convolution of their individual
763 distributions.
765 If `v` is longer than `a`, the arrays are swapped before computation.
767 Parameters
768 ----------
769 a : (N,) array_like
770 First one-dimensional input array.
771 v : (M,) array_like
772 Second one-dimensional input array.
773 mode : {'full', 'valid', 'same'}, optional
774 'full':
775 By default, mode is 'full'. This returns the convolution
776 at each point of overlap, with an output shape of (N+M-1,). At
777 the end-points of the convolution, the signals do not overlap
778 completely, and boundary effects may be seen.
780 'same':
781 Mode 'same' returns output of length ``max(M, N)``. Boundary
782 effects are still visible.
784 'valid':
785 Mode 'valid' returns output of length
786 ``max(M, N) - min(M, N) + 1``. The convolution product is only given
787 for points where the signals overlap completely. Values outside
788 the signal boundary have no effect.
790 Returns
791 -------
792 out : ndarray
793 Discrete, linear convolution of `a` and `v`.
795 See Also
796 --------
797 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
798 Transform.
799 scipy.linalg.toeplitz : Used to construct the convolution operator.
800 polymul : Polynomial multiplication. Same output as convolve, but also
801 accepts poly1d objects as input.
803 Notes
804 -----
805 The discrete convolution operation is defined as
807 .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
809 It can be shown that a convolution :math:`x(t) * y(t)` in time/space
810 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
811 domain, after appropriate padding (padding is necessary to prevent
812 circular convolution). Since multiplication is more efficient (faster)
813 than convolution, the function `scipy.signal.fftconvolve` exploits the
814 FFT to calculate the convolution of large data-sets.
816 References
817 ----------
818 .. [1] Wikipedia, "Convolution",
819 https://en.wikipedia.org/wiki/Convolution
821 Examples
822 --------
823 Note how the convolution operator flips the second array
824 before "sliding" the two across one another:
826 >>> np.convolve([1, 2, 3], [0, 1, 0.5])
827 array([0. , 1. , 2.5, 4. , 1.5])
829 Only return the middle values of the convolution.
830 Contains boundary effects, where zeros are taken
831 into account:
833 >>> np.convolve([1,2,3],[0,1,0.5], 'same')
834 array([1. , 2.5, 4. ])
836 The two arrays are of the same length, so there
837 is only one position where they completely overlap:
839 >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
840 array([2.5])
842 """
843 a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
844 if (len(v) > len(a)):
845 a, v = v, a
846 if len(a) == 0:
847 raise ValueError('a cannot be empty')
848 if len(v) == 0:
849 raise ValueError('v cannot be empty')
850 return multiarray.correlate(a, v[::-1], mode)
853def _outer_dispatcher(a, b, out=None):
854 return (a, b, out)
857@array_function_dispatch(_outer_dispatcher)
858def outer(a, b, out=None):
859 """
860 Compute the outer product of two vectors.
862 Given two vectors, ``a = [a0, a1, ..., aM]`` and
863 ``b = [b0, b1, ..., bN]``,
864 the outer product [1]_ is::
866 [[a0*b0 a0*b1 ... a0*bN ]
867 [a1*b0 .
868 [ ... .
869 [aM*b0 aM*bN ]]
871 Parameters
872 ----------
873 a : (M,) array_like
874 First input vector. Input is flattened if
875 not already 1-dimensional.
876 b : (N,) array_like
877 Second input vector. Input is flattened if
878 not already 1-dimensional.
879 out : (M, N) ndarray, optional
880 A location where the result is stored
882 .. versionadded:: 1.9.0
884 Returns
885 -------
886 out : (M, N) ndarray
887 ``out[i, j] = a[i] * b[j]``
889 See also
890 --------
891 inner
892 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
893 ufunc.outer : A generalization to dimensions other than 1D and other
894 operations. ``np.multiply.outer(a.ravel(), b.ravel())``
895 is the equivalent.
896 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
897 is the equivalent.
899 References
900 ----------
901 .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
902 ed., Baltimore, MD, Johns Hopkins University Press, 1996,
903 pg. 8.
905 Examples
906 --------
907 Make a (*very* coarse) grid for computing a Mandelbrot set:
909 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
910 >>> rl
911 array([[-2., -1., 0., 1., 2.],
912 [-2., -1., 0., 1., 2.],
913 [-2., -1., 0., 1., 2.],
914 [-2., -1., 0., 1., 2.],
915 [-2., -1., 0., 1., 2.]])
916 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
917 >>> im
918 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
919 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
920 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
921 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
922 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
923 >>> grid = rl + im
924 >>> grid
925 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
926 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
927 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
928 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
929 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
931 An example using a "vector" of letters:
933 >>> x = np.array(['a', 'b', 'c'], dtype=object)
934 >>> np.outer(x, [1, 2, 3])
935 array([['a', 'aa', 'aaa'],
936 ['b', 'bb', 'bbb'],
937 ['c', 'cc', 'ccc']], dtype=object)
939 """
940 a = asarray(a)
941 b = asarray(b)
942 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
945def _tensordot_dispatcher(a, b, axes=None):
946 return (a, b)
949@array_function_dispatch(_tensordot_dispatcher)
950def tensordot(a, b, axes=2):
951 """
952 Compute tensor dot product along specified axes.
954 Given two tensors, `a` and `b`, and an array_like object containing
955 two array_like objects, ``(a_axes, b_axes)``, sum the products of
956 `a`'s and `b`'s elements (components) over the axes specified by
957 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
958 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
959 of `a` and the first ``N`` dimensions of `b` are summed over.
961 Parameters
962 ----------
963 a, b : array_like
964 Tensors to "dot".
966 axes : int or (2,) array_like
967 * integer_like
968 If an int N, sum over the last N axes of `a` and the first N axes
969 of `b` in order. The sizes of the corresponding axes must match.
970 * (2,) array_like
971 Or, a list of axes to be summed over, first sequence applying to `a`,
972 second to `b`. Both elements array_like must be of the same length.
974 Returns
975 -------
976 output : ndarray
977 The tensor dot product of the input.
979 See Also
980 --------
981 dot, einsum
983 Notes
984 -----
985 Three common use cases are:
986 * ``axes = 0`` : tensor product :math:`a\\otimes b`
987 * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
988 * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
990 When `axes` is integer_like, the sequence for evaluation will be: first
991 the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
992 Nth axis in `b` last.
994 When there is more than one axis to sum over - and they are not the last
995 (first) axes of `a` (`b`) - the argument `axes` should consist of
996 two sequences of the same length, with the first axis to sum over given
997 first in both sequences, the second axis second, and so forth.
999 The shape of the result consists of the non-contracted axes of the
1000 first tensor, followed by the non-contracted axes of the second.
1002 Examples
1003 --------
1004 A "traditional" example:
1006 >>> a = np.arange(60.).reshape(3,4,5)
1007 >>> b = np.arange(24.).reshape(4,3,2)
1008 >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
1009 >>> c.shape
1010 (5, 2)
1011 >>> c
1012 array([[4400., 4730.],
1013 [4532., 4874.],
1014 [4664., 5018.],
1015 [4796., 5162.],
1016 [4928., 5306.]])
1017 >>> # A slower but equivalent way of computing the same...
1018 >>> d = np.zeros((5,2))
1019 >>> for i in range(5):
1020 ... for j in range(2):
1021 ... for k in range(3):
1022 ... for n in range(4):
1023 ... d[i,j] += a[k,n,i] * b[n,k,j]
1024 >>> c == d
1025 array([[ True, True],
1026 [ True, True],
1027 [ True, True],
1028 [ True, True],
1029 [ True, True]])
1031 An extended example taking advantage of the overloading of + and \\*:
1033 >>> a = np.array(range(1, 9))
1034 >>> a.shape = (2, 2, 2)
1035 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1036 >>> A.shape = (2, 2)
1037 >>> a; A
1038 array([[[1, 2],
1039 [3, 4]],
1040 [[5, 6],
1041 [7, 8]]])
1042 array([['a', 'b'],
1043 ['c', 'd']], dtype=object)
1045 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1046 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1048 >>> np.tensordot(a, A, 1)
1049 array([[['acc', 'bdd'],
1050 ['aaacccc', 'bbbdddd']],
1051 [['aaaaacccccc', 'bbbbbdddddd'],
1052 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1054 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1055 array([[[[['a', 'b'],
1056 ['c', 'd']],
1057 ...
1059 >>> np.tensordot(a, A, (0, 1))
1060 array([[['abbbbb', 'cddddd'],
1061 ['aabbbbbb', 'ccdddddd']],
1062 [['aaabbbbbbb', 'cccddddddd'],
1063 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1065 >>> np.tensordot(a, A, (2, 1))
1066 array([[['abb', 'cdd'],
1067 ['aaabbbb', 'cccdddd']],
1068 [['aaaaabbbbbb', 'cccccdddddd'],
1069 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1071 >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1072 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1074 >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1075 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1077 """
1078 try:
1079 iter(axes)
1080 except Exception:
1081 axes_a = list(range(-axes, 0))
1082 axes_b = list(range(0, axes))
1083 else:
1084 axes_a, axes_b = axes
1085 try:
1086 na = len(axes_a)
1087 axes_a = list(axes_a)
1088 except TypeError:
1089 axes_a = [axes_a]
1090 na = 1
1091 try:
1092 nb = len(axes_b)
1093 axes_b = list(axes_b)
1094 except TypeError:
1095 axes_b = [axes_b]
1096 nb = 1
1098 a, b = asarray(a), asarray(b)
1099 as_ = a.shape
1100 nda = a.ndim
1101 bs = b.shape
1102 ndb = b.ndim
1103 equal = True
1104 if na != nb:
1105 equal = False
1106 else:
1107 for k in range(na):
1108 if as_[axes_a[k]] != bs[axes_b[k]]:
1109 equal = False
1110 break
1111 if axes_a[k] < 0:
1112 axes_a[k] += nda
1113 if axes_b[k] < 0:
1114 axes_b[k] += ndb
1115 if not equal:
1116 raise ValueError("shape-mismatch for sum")
1118 # Move the axes to sum over to the end of "a"
1119 # and to the front of "b"
1120 notin = [k for k in range(nda) if k not in axes_a]
1121 newaxes_a = notin + axes_a
1122 N2 = 1
1123 for axis in axes_a:
1124 N2 *= as_[axis]
1125 newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
1126 olda = [as_[axis] for axis in notin]
1128 notin = [k for k in range(ndb) if k not in axes_b]
1129 newaxes_b = axes_b + notin
1130 N2 = 1
1131 for axis in axes_b:
1132 N2 *= bs[axis]
1133 newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
1134 oldb = [bs[axis] for axis in notin]
1136 at = a.transpose(newaxes_a).reshape(newshape_a)
1137 bt = b.transpose(newaxes_b).reshape(newshape_b)
1138 res = dot(at, bt)
1139 return res.reshape(olda + oldb)
1142def _roll_dispatcher(a, shift, axis=None):
1143 return (a,)
1146@array_function_dispatch(_roll_dispatcher)
1147def roll(a, shift, axis=None):
1148 """
1149 Roll array elements along a given axis.
1151 Elements that roll beyond the last position are re-introduced at
1152 the first.
1154 Parameters
1155 ----------
1156 a : array_like
1157 Input array.
1158 shift : int or tuple of ints
1159 The number of places by which elements are shifted. If a tuple,
1160 then `axis` must be a tuple of the same size, and each of the
1161 given axes is shifted by the corresponding number. If an int
1162 while `axis` is a tuple of ints, then the same value is used for
1163 all given axes.
1164 axis : int or tuple of ints, optional
1165 Axis or axes along which elements are shifted. By default, the
1166 array is flattened before shifting, after which the original
1167 shape is restored.
1169 Returns
1170 -------
1171 res : ndarray
1172 Output array, with the same shape as `a`.
1174 See Also
1175 --------
1176 rollaxis : Roll the specified axis backwards, until it lies in a
1177 given position.
1179 Notes
1180 -----
1181 .. versionadded:: 1.12.0
1183 Supports rolling over multiple dimensions simultaneously.
1185 Examples
1186 --------
1187 >>> x = np.arange(10)
1188 >>> np.roll(x, 2)
1189 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
1190 >>> np.roll(x, -2)
1191 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
1193 >>> x2 = np.reshape(x, (2, 5))
1194 >>> x2
1195 array([[0, 1, 2, 3, 4],
1196 [5, 6, 7, 8, 9]])
1197 >>> np.roll(x2, 1)
1198 array([[9, 0, 1, 2, 3],
1199 [4, 5, 6, 7, 8]])
1200 >>> np.roll(x2, -1)
1201 array([[1, 2, 3, 4, 5],
1202 [6, 7, 8, 9, 0]])
1203 >>> np.roll(x2, 1, axis=0)
1204 array([[5, 6, 7, 8, 9],
1205 [0, 1, 2, 3, 4]])
1206 >>> np.roll(x2, -1, axis=0)
1207 array([[5, 6, 7, 8, 9],
1208 [0, 1, 2, 3, 4]])
1209 >>> np.roll(x2, 1, axis=1)
1210 array([[4, 0, 1, 2, 3],
1211 [9, 5, 6, 7, 8]])
1212 >>> np.roll(x2, -1, axis=1)
1213 array([[1, 2, 3, 4, 0],
1214 [6, 7, 8, 9, 5]])
1215 >>> np.roll(x2, (1, 1), axis=(1, 0))
1216 array([[9, 5, 6, 7, 8],
1217 [4, 0, 1, 2, 3]])
1218 >>> np.roll(x2, (2, 1), axis=(1, 0))
1219 array([[8, 9, 5, 6, 7],
1220 [3, 4, 0, 1, 2]])
1222 """
1223 a = asanyarray(a)
1224 if axis is None:
1225 return roll(a.ravel(), shift, 0).reshape(a.shape)
1227 else:
1228 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1229 broadcasted = broadcast(shift, axis)
1230 if broadcasted.ndim > 1:
1231 raise ValueError(
1232 "'shift' and 'axis' should be scalars or 1D sequences")
1233 shifts = {ax: 0 for ax in range(a.ndim)}
1234 for sh, ax in broadcasted:
1235 shifts[ax] += sh
1237 rolls = [((slice(None), slice(None)),)] * a.ndim
1238 for ax, offset in shifts.items():
1239 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
1240 if offset:
1241 # (original, result), (original, result)
1242 rolls[ax] = ((slice(None, -offset), slice(offset, None)),
1243 (slice(-offset, None), slice(None, offset)))
1245 result = empty_like(a)
1246 for indices in itertools.product(*rolls):
1247 arr_index, res_index = zip(*indices)
1248 result[res_index] = a[arr_index]
1250 return result
1253def _rollaxis_dispatcher(a, axis, start=None):
1254 return (a,)
1257@array_function_dispatch(_rollaxis_dispatcher)
1258def rollaxis(a, axis, start=0):
1259 """
1260 Roll the specified axis backwards, until it lies in a given position.
1262 This function continues to be supported for backward compatibility, but you
1263 should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1264 1.11.
1266 Parameters
1267 ----------
1268 a : ndarray
1269 Input array.
1270 axis : int
1271 The axis to be rolled. The positions of the other axes do not
1272 change relative to one another.
1273 start : int, optional
1274 When ``start <= axis``, the axis is rolled back until it lies in
1275 this position. When ``start > axis``, the axis is rolled until it
1276 lies before this position. The default, 0, results in a "complete"
1277 roll. The following table describes how negative values of ``start``
1278 are interpreted:
1280 .. table::
1281 :align: left
1283 +-------------------+----------------------+
1284 | ``start`` | Normalized ``start`` |
1285 +===================+======================+
1286 | ``-(arr.ndim+1)`` | raise ``AxisError`` |
1287 +-------------------+----------------------+
1288 | ``-arr.ndim`` | 0 |
1289 +-------------------+----------------------+
1290 | |vdots| | |vdots| |
1291 +-------------------+----------------------+
1292 | ``-1`` | ``arr.ndim-1`` |
1293 +-------------------+----------------------+
1294 | ``0`` | ``0`` |
1295 +-------------------+----------------------+
1296 | |vdots| | |vdots| |
1297 +-------------------+----------------------+
1298 | ``arr.ndim`` | ``arr.ndim`` |
1299 +-------------------+----------------------+
1300 | ``arr.ndim + 1`` | raise ``AxisError`` |
1301 +-------------------+----------------------+
1303 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
1305 Returns
1306 -------
1307 res : ndarray
1308 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
1309 NumPy versions a view of `a` is returned only if the order of the
1310 axes is changed, otherwise the input array is returned.
1312 See Also
1313 --------
1314 moveaxis : Move array axes to new positions.
1315 roll : Roll the elements of an array by a number of positions along a
1316 given axis.
1318 Examples
1319 --------
1320 >>> a = np.ones((3,4,5,6))
1321 >>> np.rollaxis(a, 3, 1).shape
1322 (3, 6, 4, 5)
1323 >>> np.rollaxis(a, 2).shape
1324 (5, 3, 4, 6)
1325 >>> np.rollaxis(a, 1, 4).shape
1326 (3, 5, 6, 4)
1328 """
1329 n = a.ndim
1330 axis = normalize_axis_index(axis, n)
1331 if start < 0:
1332 start += n
1333 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1334 if not (0 <= start < n + 1):
1335 raise AxisError(msg % ('start', -n, 'start', n + 1, start))
1336 if axis < start:
1337 # it's been removed
1338 start -= 1
1339 if axis == start:
1340 return a[...]
1341 axes = list(range(0, n))
1342 axes.remove(axis)
1343 axes.insert(start, axis)
1344 return a.transpose(axes)
1347def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
1348 """
1349 Normalizes an axis argument into a tuple of non-negative integer axes.
1351 This handles shorthands such as ``1`` and converts them to ``(1,)``,
1352 as well as performing the handling of negative indices covered by
1353 `normalize_axis_index`.
1355 By default, this forbids axes from being specified multiple times.
1357 Used internally by multi-axis-checking logic.
1359 .. versionadded:: 1.13.0
1361 Parameters
1362 ----------
1363 axis : int, iterable of int
1364 The un-normalized index or indices of the axis.
1365 ndim : int
1366 The number of dimensions of the array that `axis` should be normalized
1367 against.
1368 argname : str, optional
1369 A prefix to put before the error message, typically the name of the
1370 argument.
1371 allow_duplicate : bool, optional
1372 If False, the default, disallow an axis from being specified twice.
1374 Returns
1375 -------
1376 normalized_axes : tuple of int
1377 The normalized axis index, such that `0 <= normalized_axis < ndim`
1379 Raises
1380 ------
1381 AxisError
1382 If any axis provided is out of range
1383 ValueError
1384 If an axis is repeated
1386 See also
1387 --------
1388 normalize_axis_index : normalizing a single scalar axis
1389 """
1390 # Optimization to speed-up the most common cases.
1391 if type(axis) not in (tuple, list):
1392 try:
1393 axis = [operator.index(axis)]
1394 except TypeError:
1395 pass
1396 # Going via an iterator directly is slower than via list comprehension.
1397 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
1398 if not allow_duplicate and len(set(axis)) != len(axis):
1399 if argname:
1400 raise ValueError('repeated axis in `{}` argument'.format(argname))
1401 else:
1402 raise ValueError('repeated axis')
1403 return axis
1406def _moveaxis_dispatcher(a, source, destination):
1407 return (a,)
1410@array_function_dispatch(_moveaxis_dispatcher)
1411def moveaxis(a, source, destination):
1412 """
1413 Move axes of an array to new positions.
1415 Other axes remain in their original order.
1417 .. versionadded:: 1.11.0
1419 Parameters
1420 ----------
1421 a : np.ndarray
1422 The array whose axes should be reordered.
1423 source : int or sequence of int
1424 Original positions of the axes to move. These must be unique.
1425 destination : int or sequence of int
1426 Destination positions for each of the original axes. These must also be
1427 unique.
1429 Returns
1430 -------
1431 result : np.ndarray
1432 Array with moved axes. This array is a view of the input array.
1434 See Also
1435 --------
1436 transpose : Permute the dimensions of an array.
1437 swapaxes : Interchange two axes of an array.
1439 Examples
1440 --------
1441 >>> x = np.zeros((3, 4, 5))
1442 >>> np.moveaxis(x, 0, -1).shape
1443 (4, 5, 3)
1444 >>> np.moveaxis(x, -1, 0).shape
1445 (5, 3, 4)
1447 These all achieve the same result:
1449 >>> np.transpose(x).shape
1450 (5, 4, 3)
1451 >>> np.swapaxes(x, 0, -1).shape
1452 (5, 4, 3)
1453 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
1454 (5, 4, 3)
1455 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
1456 (5, 4, 3)
1458 """
1459 try:
1460 # allow duck-array types if they define transpose
1461 transpose = a.transpose
1462 except AttributeError:
1463 a = asarray(a)
1464 transpose = a.transpose
1466 source = normalize_axis_tuple(source, a.ndim, 'source')
1467 destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1468 if len(source) != len(destination):
1469 raise ValueError('`source` and `destination` arguments must have '
1470 'the same number of elements')
1472 order = [n for n in range(a.ndim) if n not in source]
1474 for dest, src in sorted(zip(destination, source)):
1475 order.insert(dest, src)
1477 result = transpose(order)
1478 return result
1481def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
1482 return (a, b)
1485@array_function_dispatch(_cross_dispatcher)
1486def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
1487 """
1488 Return the cross product of two (arrays of) vectors.
1490 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
1491 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
1492 are defined by the last axis of `a` and `b` by default, and these axes
1493 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
1494 2, the third component of the input vector is assumed to be zero and the
1495 cross product calculated accordingly. In cases where both input vectors
1496 have dimension 2, the z-component of the cross product is returned.
1498 Parameters
1499 ----------
1500 a : array_like
1501 Components of the first vector(s).
1502 b : array_like
1503 Components of the second vector(s).
1504 axisa : int, optional
1505 Axis of `a` that defines the vector(s). By default, the last axis.
1506 axisb : int, optional
1507 Axis of `b` that defines the vector(s). By default, the last axis.
1508 axisc : int, optional
1509 Axis of `c` containing the cross product vector(s). Ignored if
1510 both input vectors have dimension 2, as the return is scalar.
1511 By default, the last axis.
1512 axis : int, optional
1513 If defined, the axis of `a`, `b` and `c` that defines the vector(s)
1514 and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
1516 Returns
1517 -------
1518 c : ndarray
1519 Vector cross product(s).
1521 Raises
1522 ------
1523 ValueError
1524 When the dimension of the vector(s) in `a` and/or `b` does not
1525 equal 2 or 3.
1527 See Also
1528 --------
1529 inner : Inner product
1530 outer : Outer product.
1531 ix_ : Construct index arrays.
1533 Notes
1534 -----
1535 .. versionadded:: 1.9.0
1537 Supports full broadcasting of the inputs.
1539 Examples
1540 --------
1541 Vector cross-product.
1543 >>> x = [1, 2, 3]
1544 >>> y = [4, 5, 6]
1545 >>> np.cross(x, y)
1546 array([-3, 6, -3])
1548 One vector with dimension 2.
1550 >>> x = [1, 2]
1551 >>> y = [4, 5, 6]
1552 >>> np.cross(x, y)
1553 array([12, -6, -3])
1555 Equivalently:
1557 >>> x = [1, 2, 0]
1558 >>> y = [4, 5, 6]
1559 >>> np.cross(x, y)
1560 array([12, -6, -3])
1562 Both vectors with dimension 2.
1564 >>> x = [1,2]
1565 >>> y = [4,5]
1566 >>> np.cross(x, y)
1567 array(-3)
1569 Multiple vector cross-products. Note that the direction of the cross
1570 product vector is defined by the *right-hand rule*.
1572 >>> x = np.array([[1,2,3], [4,5,6]])
1573 >>> y = np.array([[4,5,6], [1,2,3]])
1574 >>> np.cross(x, y)
1575 array([[-3, 6, -3],
1576 [ 3, -6, 3]])
1578 The orientation of `c` can be changed using the `axisc` keyword.
1580 >>> np.cross(x, y, axisc=0)
1581 array([[-3, 3],
1582 [ 6, -6],
1583 [-3, 3]])
1585 Change the vector definition of `x` and `y` using `axisa` and `axisb`.
1587 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
1588 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
1589 >>> np.cross(x, y)
1590 array([[ -6, 12, -6],
1591 [ 0, 0, 0],
1592 [ 6, -12, 6]])
1593 >>> np.cross(x, y, axisa=0, axisb=0)
1594 array([[-24, 48, -24],
1595 [-30, 60, -30],
1596 [-36, 72, -36]])
1598 """
1599 if axis is not None:
1600 axisa, axisb, axisc = (axis,) * 3
1601 a = asarray(a)
1602 b = asarray(b)
1603 # Check axisa and axisb are within bounds
1604 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
1605 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
1607 # Move working axis to the end of the shape
1608 a = moveaxis(a, axisa, -1)
1609 b = moveaxis(b, axisb, -1)
1610 msg = ("incompatible dimensions for cross product\n"
1611 "(dimension must be 2 or 3)")
1612 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1613 raise ValueError(msg)
1615 # Create the output array
1616 shape = broadcast(a[..., 0], b[..., 0]).shape
1617 if a.shape[-1] == 3 or b.shape[-1] == 3:
1618 shape += (3,)
1619 # Check axisc is within bounds
1620 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
1621 dtype = promote_types(a.dtype, b.dtype)
1622 cp = empty(shape, dtype)
1624 # create local aliases for readability
1625 a0 = a[..., 0]
1626 a1 = a[..., 1]
1627 if a.shape[-1] == 3:
1628 a2 = a[..., 2]
1629 b0 = b[..., 0]
1630 b1 = b[..., 1]
1631 if b.shape[-1] == 3:
1632 b2 = b[..., 2]
1633 if cp.ndim != 0 and cp.shape[-1] == 3:
1634 cp0 = cp[..., 0]
1635 cp1 = cp[..., 1]
1636 cp2 = cp[..., 2]
1638 if a.shape[-1] == 2:
1639 if b.shape[-1] == 2:
1640 # a0 * b1 - a1 * b0
1641 multiply(a0, b1, out=cp)
1642 cp -= a1 * b0
1643 return cp
1644 else:
1645 assert b.shape[-1] == 3
1646 # cp0 = a1 * b2 - 0 (a2 = 0)
1647 # cp1 = 0 - a0 * b2 (a2 = 0)
1648 # cp2 = a0 * b1 - a1 * b0
1649 multiply(a1, b2, out=cp0)
1650 multiply(a0, b2, out=cp1)
1651 negative(cp1, out=cp1)
1652 multiply(a0, b1, out=cp2)
1653 cp2 -= a1 * b0
1654 else:
1655 assert a.shape[-1] == 3
1656 if b.shape[-1] == 3:
1657 # cp0 = a1 * b2 - a2 * b1
1658 # cp1 = a2 * b0 - a0 * b2
1659 # cp2 = a0 * b1 - a1 * b0
1660 multiply(a1, b2, out=cp0)
1661 tmp = array(a2 * b1)
1662 cp0 -= tmp
1663 multiply(a2, b0, out=cp1)
1664 multiply(a0, b2, out=tmp)
1665 cp1 -= tmp
1666 multiply(a0, b1, out=cp2)
1667 multiply(a1, b0, out=tmp)
1668 cp2 -= tmp
1669 else:
1670 assert b.shape[-1] == 2
1671 # cp0 = 0 - a2 * b1 (b2 = 0)
1672 # cp1 = a2 * b0 - 0 (b2 = 0)
1673 # cp2 = a0 * b1 - a1 * b0
1674 multiply(a2, b1, out=cp0)
1675 negative(cp0, out=cp0)
1676 multiply(a2, b0, out=cp1)
1677 multiply(a0, b1, out=cp2)
1678 cp2 -= a1 * b0
1680 return moveaxis(cp, -1, axisc)
1683little_endian = (sys.byteorder == 'little')
1686@set_module('numpy')
1687def indices(dimensions, dtype=int, sparse=False):
1688 """
1689 Return an array representing the indices of a grid.
1691 Compute an array where the subarrays contain index values 0, 1, ...
1692 varying only along the corresponding axis.
1694 Parameters
1695 ----------
1696 dimensions : sequence of ints
1697 The shape of the grid.
1698 dtype : dtype, optional
1699 Data type of the result.
1700 sparse : boolean, optional
1701 Return a sparse representation of the grid instead of a dense
1702 representation. Default is False.
1704 .. versionadded:: 1.17
1706 Returns
1707 -------
1708 grid : one ndarray or tuple of ndarrays
1709 If sparse is False:
1710 Returns one array of grid indices,
1711 ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1712 If sparse is True:
1713 Returns a tuple of arrays, with
1714 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1715 dimensions[i] in the ith place
1717 See Also
1718 --------
1719 mgrid, ogrid, meshgrid
1721 Notes
1722 -----
1723 The output shape in the dense case is obtained by prepending the number
1724 of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
1725 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
1726 ``(N, r0, ..., rN-1)``.
1728 The subarrays ``grid[k]`` contains the N-D array of indices along the
1729 ``k-th`` axis. Explicitly::
1731 grid[k, i0, i1, ..., iN-1] = ik
1733 Examples
1734 --------
1735 >>> grid = np.indices((2, 3))
1736 >>> grid.shape
1737 (2, 2, 3)
1738 >>> grid[0] # row indices
1739 array([[0, 0, 0],
1740 [1, 1, 1]])
1741 >>> grid[1] # column indices
1742 array([[0, 1, 2],
1743 [0, 1, 2]])
1745 The indices can be used as an index into an array.
1747 >>> x = np.arange(20).reshape(5, 4)
1748 >>> row, col = np.indices((2, 3))
1749 >>> x[row, col]
1750 array([[0, 1, 2],
1751 [4, 5, 6]])
1753 Note that it would be more straightforward in the above example to
1754 extract the required elements directly with ``x[:2, :3]``.
1756 If sparse is set to true, the grid will be returned in a sparse
1757 representation.
1759 >>> i, j = np.indices((2, 3), sparse=True)
1760 >>> i.shape
1761 (2, 1)
1762 >>> j.shape
1763 (1, 3)
1764 >>> i # row indices
1765 array([[0],
1766 [1]])
1767 >>> j # column indices
1768 array([[0, 1, 2]])
1770 """
1771 dimensions = tuple(dimensions)
1772 N = len(dimensions)
1773 shape = (1,)*N
1774 if sparse:
1775 res = tuple()
1776 else:
1777 res = empty((N,)+dimensions, dtype=dtype)
1778 for i, dim in enumerate(dimensions):
1779 idx = arange(dim, dtype=dtype).reshape(
1780 shape[:i] + (dim,) + shape[i+1:]
1781 )
1782 if sparse:
1783 res = res + (idx,)
1784 else:
1785 res[i] = idx
1786 return res
1789def _fromfunction_dispatcher(function, shape, *, dtype=None, like=None, **kwargs):
1790 return (like,)
1793@set_array_function_like_doc
1794@set_module('numpy')
1795def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
1796 """
1797 Construct an array by executing a function over each coordinate.
1799 The resulting array therefore has a value ``fn(x, y, z)`` at
1800 coordinate ``(x, y, z)``.
1802 Parameters
1803 ----------
1804 function : callable
1805 The function is called with N parameters, where N is the rank of
1806 `shape`. Each parameter represents the coordinates of the array
1807 varying along a specific axis. For example, if `shape`
1808 were ``(2, 2)``, then the parameters would be
1809 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
1810 shape : (N,) tuple of ints
1811 Shape of the output array, which also determines the shape of
1812 the coordinate arrays passed to `function`.
1813 dtype : data-type, optional
1814 Data-type of the coordinate arrays passed to `function`.
1815 By default, `dtype` is float.
1816 ${ARRAY_FUNCTION_LIKE}
1818 .. versionadded:: 1.20.0
1820 Returns
1821 -------
1822 fromfunction : any
1823 The result of the call to `function` is passed back directly.
1824 Therefore the shape of `fromfunction` is completely determined by
1825 `function`. If `function` returns a scalar value, the shape of
1826 `fromfunction` would not match the `shape` parameter.
1828 See Also
1829 --------
1830 indices, meshgrid
1832 Notes
1833 -----
1834 Keywords other than `dtype` are passed to `function`.
1836 Examples
1837 --------
1838 >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
1839 array([[0., 0.],
1840 [1., 1.]])
1842 >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
1843 array([[0., 1.],
1844 [0., 1.]])
1846 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
1847 array([[ True, False, False],
1848 [False, True, False],
1849 [False, False, True]])
1851 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
1852 array([[0, 1, 2],
1853 [1, 2, 3],
1854 [2, 3, 4]])
1856 """
1857 if like is not None:
1858 return _fromfunction_with_like(function, shape, dtype=dtype, like=like, **kwargs)
1860 args = indices(shape, dtype=dtype)
1861 return function(*args, **kwargs)
1864_fromfunction_with_like = array_function_dispatch(
1865 _fromfunction_dispatcher
1866)(fromfunction)
1869def _frombuffer(buf, dtype, shape, order):
1870 return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
1873@set_module('numpy')
1874def isscalar(element):
1875 """
1876 Returns True if the type of `element` is a scalar type.
1878 Parameters
1879 ----------
1880 element : any
1881 Input argument, can be of any type and shape.
1883 Returns
1884 -------
1885 val : bool
1886 True if `element` is a scalar type, False if it is not.
1888 See Also
1889 --------
1890 ndim : Get the number of dimensions of an array
1892 Notes
1893 -----
1894 If you need a stricter way to identify a *numerical* scalar, use
1895 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
1896 non-numerical elements such as strings.
1898 In most cases ``np.ndim(x) == 0`` should be used instead of this function,
1899 as that will also return true for 0d arrays. This is how numpy overloads
1900 functions in the style of the ``dx`` arguments to `gradient` and the ``bins``
1901 argument to `histogram`. Some key differences:
1903 +--------------------------------------+---------------+-------------------+
1904 | x |``isscalar(x)``|``np.ndim(x) == 0``|
1905 +======================================+===============+===================+
1906 | PEP 3141 numeric objects (including | ``True`` | ``True`` |
1907 | builtins) | | |
1908 +--------------------------------------+---------------+-------------------+
1909 | builtin string and buffer objects | ``True`` | ``True`` |
1910 +--------------------------------------+---------------+-------------------+
1911 | other builtin objects, like | ``False`` | ``True`` |
1912 | `pathlib.Path`, `Exception`, | | |
1913 | the result of `re.compile` | | |
1914 +--------------------------------------+---------------+-------------------+
1915 | third-party objects like | ``False`` | ``True`` |
1916 | `matplotlib.figure.Figure` | | |
1917 +--------------------------------------+---------------+-------------------+
1918 | zero-dimensional numpy arrays | ``False`` | ``True`` |
1919 +--------------------------------------+---------------+-------------------+
1920 | other numpy arrays | ``False`` | ``False`` |
1921 +--------------------------------------+---------------+-------------------+
1922 | `list`, `tuple`, and other sequence | ``False`` | ``False`` |
1923 | objects | | |
1924 +--------------------------------------+---------------+-------------------+
1926 Examples
1927 --------
1928 >>> np.isscalar(3.1)
1929 True
1930 >>> np.isscalar(np.array(3.1))
1931 False
1932 >>> np.isscalar([3.1])
1933 False
1934 >>> np.isscalar(False)
1935 True
1936 >>> np.isscalar('numpy')
1937 True
1939 NumPy supports PEP 3141 numbers:
1941 >>> from fractions import Fraction
1942 >>> np.isscalar(Fraction(5, 17))
1943 True
1944 >>> from numbers import Number
1945 >>> np.isscalar(Number())
1946 True
1948 """
1949 return (isinstance(element, generic)
1950 or type(element) in ScalarType
1951 or isinstance(element, numbers.Number))
1954@set_module('numpy')
1955def binary_repr(num, width=None):
1956 """
1957 Return the binary representation of the input number as a string.
1959 For negative numbers, if width is not given, a minus sign is added to the
1960 front. If width is given, the two's complement of the number is
1961 returned, with respect to that width.
1963 In a two's-complement system negative numbers are represented by the two's
1964 complement of the absolute value. This is the most common method of
1965 representing signed integers on computers [1]_. A N-bit two's-complement
1966 system can represent every integer in the range
1967 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
1969 Parameters
1970 ----------
1971 num : int
1972 Only an integer decimal number can be used.
1973 width : int, optional
1974 The length of the returned string if `num` is positive, or the length
1975 of the two's complement if `num` is negative, provided that `width` is
1976 at least a sufficient number of bits for `num` to be represented in the
1977 designated form.
1979 If the `width` value is insufficient, it will be ignored, and `num` will
1980 be returned in binary (`num` > 0) or two's complement (`num` < 0) form
1981 with its width equal to the minimum number of bits needed to represent
1982 the number in the designated form. This behavior is deprecated and will
1983 later raise an error.
1985 .. deprecated:: 1.12.0
1987 Returns
1988 -------
1989 bin : str
1990 Binary representation of `num` or two's complement of `num`.
1992 See Also
1993 --------
1994 base_repr: Return a string representation of a number in the given base
1995 system.
1996 bin: Python's built-in binary representation generator of an integer.
1998 Notes
1999 -----
2000 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
2001 faster.
2003 References
2004 ----------
2005 .. [1] Wikipedia, "Two's complement",
2006 https://en.wikipedia.org/wiki/Two's_complement
2008 Examples
2009 --------
2010 >>> np.binary_repr(3)
2011 '11'
2012 >>> np.binary_repr(-3)
2013 '-11'
2014 >>> np.binary_repr(3, width=4)
2015 '0011'
2017 The two's complement is returned when the input number is negative and
2018 width is specified:
2020 >>> np.binary_repr(-3, width=3)
2021 '101'
2022 >>> np.binary_repr(-3, width=5)
2023 '11101'
2025 """
2026 def warn_if_insufficient(width, binwidth):
2027 if width is not None and width < binwidth:
2028 warnings.warn(
2029 "Insufficient bit width provided. This behavior "
2030 "will raise an error in the future.", DeprecationWarning,
2031 stacklevel=3)
2033 # Ensure that num is a Python integer to avoid overflow or unwanted
2034 # casts to floating point.
2035 num = operator.index(num)
2037 if num == 0:
2038 return '0' * (width or 1)
2040 elif num > 0:
2041 binary = bin(num)[2:]
2042 binwidth = len(binary)
2043 outwidth = (binwidth if width is None
2044 else max(binwidth, width))
2045 warn_if_insufficient(width, binwidth)
2046 return binary.zfill(outwidth)
2048 else:
2049 if width is None:
2050 return '-' + bin(-num)[2:]
2052 else:
2053 poswidth = len(bin(-num)[2:])
2055 # See gh-8679: remove extra digit
2056 # for numbers at boundaries.
2057 if 2**(poswidth - 1) == -num:
2058 poswidth -= 1
2060 twocomp = 2**(poswidth + 1) + num
2061 binary = bin(twocomp)[2:]
2062 binwidth = len(binary)
2064 outwidth = max(binwidth, width)
2065 warn_if_insufficient(width, binwidth)
2066 return '1' * (outwidth - binwidth) + binary
2069@set_module('numpy')
2070def base_repr(number, base=2, padding=0):
2071 """
2072 Return a string representation of a number in the given base system.
2074 Parameters
2075 ----------
2076 number : int
2077 The value to convert. Positive and negative values are handled.
2078 base : int, optional
2079 Convert `number` to the `base` number system. The valid range is 2-36,
2080 the default value is 2.
2081 padding : int, optional
2082 Number of zeros padded on the left. Default is 0 (no padding).
2084 Returns
2085 -------
2086 out : str
2087 String representation of `number` in `base` system.
2089 See Also
2090 --------
2091 binary_repr : Faster version of `base_repr` for base 2.
2093 Examples
2094 --------
2095 >>> np.base_repr(5)
2096 '101'
2097 >>> np.base_repr(6, 5)
2098 '11'
2099 >>> np.base_repr(7, base=5, padding=3)
2100 '00012'
2102 >>> np.base_repr(10, base=16)
2103 'A'
2104 >>> np.base_repr(32, base=16)
2105 '20'
2107 """
2108 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2109 if base > len(digits):
2110 raise ValueError("Bases greater than 36 not handled in base_repr.")
2111 elif base < 2:
2112 raise ValueError("Bases less than 2 not handled in base_repr.")
2114 num = abs(number)
2115 res = []
2116 while num:
2117 res.append(digits[num % base])
2118 num //= base
2119 if padding:
2120 res.append('0' * padding)
2121 if number < 0:
2122 res.append('-')
2123 return ''.join(reversed(res or '0'))
2126# These are all essentially abbreviations
2127# These might wind up in a special abbreviations module
2130def _maketup(descr, val):
2131 dt = dtype(descr)
2132 # Place val in all scalar tuples:
2133 fields = dt.fields
2134 if fields is None:
2135 return val
2136 else:
2137 res = [_maketup(fields[name][0], val) for name in dt.names]
2138 return tuple(res)
2141def _identity_dispatcher(n, dtype=None, *, like=None):
2142 return (like,)
2145@set_array_function_like_doc
2146@set_module('numpy')
2147def identity(n, dtype=None, *, like=None):
2148 """
2149 Return the identity array.
2151 The identity array is a square array with ones on
2152 the main diagonal.
2154 Parameters
2155 ----------
2156 n : int
2157 Number of rows (and columns) in `n` x `n` output.
2158 dtype : data-type, optional
2159 Data-type of the output. Defaults to ``float``.
2160 ${ARRAY_FUNCTION_LIKE}
2162 .. versionadded:: 1.20.0
2164 Returns
2165 -------
2166 out : ndarray
2167 `n` x `n` array with its main diagonal set to one,
2168 and all other elements 0.
2170 Examples
2171 --------
2172 >>> np.identity(3)
2173 array([[1., 0., 0.],
2174 [0., 1., 0.],
2175 [0., 0., 1.]])
2177 """
2178 if like is not None:
2179 return _identity_with_like(n, dtype=dtype, like=like)
2181 from numpy import eye
2182 return eye(n, dtype=dtype, like=like)
2185_identity_with_like = array_function_dispatch(
2186 _identity_dispatcher
2187)(identity)
2190def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2191 return (a, b)
2194@array_function_dispatch(_allclose_dispatcher)
2195def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2196 """
2197 Returns True if two arrays are element-wise equal within a tolerance.
2199 The tolerance values are positive, typically very small numbers. The
2200 relative difference (`rtol` * abs(`b`)) and the absolute difference
2201 `atol` are added together to compare against the absolute difference
2202 between `a` and `b`.
2204 NaNs are treated as equal if they are in the same place and if
2205 ``equal_nan=True``. Infs are treated as equal if they are in the same
2206 place and of the same sign in both arrays.
2208 Parameters
2209 ----------
2210 a, b : array_like
2211 Input arrays to compare.
2212 rtol : float
2213 The relative tolerance parameter (see Notes).
2214 atol : float
2215 The absolute tolerance parameter (see Notes).
2216 equal_nan : bool
2217 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2218 considered equal to NaN's in `b` in the output array.
2220 .. versionadded:: 1.10.0
2222 Returns
2223 -------
2224 allclose : bool
2225 Returns True if the two arrays are equal within the given
2226 tolerance; False otherwise.
2228 See Also
2229 --------
2230 isclose, all, any, equal
2232 Notes
2233 -----
2234 If the following equation is element-wise True, then allclose returns
2235 True.
2237 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2239 The above equation is not symmetric in `a` and `b`, so that
2240 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
2241 some rare cases.
2243 The comparison of `a` and `b` uses standard broadcasting, which
2244 means that `a` and `b` need not have the same shape in order for
2245 ``allclose(a, b)`` to evaluate to True. The same is true for
2246 `equal` but not `array_equal`.
2248 `allclose` is not defined for non-numeric data types.
2249 `bool` is considered a numeric data-type for this purpose.
2251 Examples
2252 --------
2253 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
2254 False
2255 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
2256 True
2257 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
2258 False
2259 >>> np.allclose([1.0, np.nan], [1.0, np.nan])
2260 False
2261 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2262 True
2264 """
2265 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2266 return bool(res)
2269def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2270 return (a, b)
2273@array_function_dispatch(_isclose_dispatcher)
2274def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2275 """
2276 Returns a boolean array where two arrays are element-wise equal within a
2277 tolerance.
2279 The tolerance values are positive, typically very small numbers. The
2280 relative difference (`rtol` * abs(`b`)) and the absolute difference
2281 `atol` are added together to compare against the absolute difference
2282 between `a` and `b`.
2284 .. warning:: The default `atol` is not appropriate for comparing numbers
2285 that are much smaller than one (see Notes).
2287 Parameters
2288 ----------
2289 a, b : array_like
2290 Input arrays to compare.
2291 rtol : float
2292 The relative tolerance parameter (see Notes).
2293 atol : float
2294 The absolute tolerance parameter (see Notes).
2295 equal_nan : bool
2296 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2297 considered equal to NaN's in `b` in the output array.
2299 Returns
2300 -------
2301 y : array_like
2302 Returns a boolean array of where `a` and `b` are equal within the
2303 given tolerance. If both `a` and `b` are scalars, returns a single
2304 boolean value.
2306 See Also
2307 --------
2308 allclose
2309 math.isclose
2311 Notes
2312 -----
2313 .. versionadded:: 1.7.0
2315 For finite values, isclose uses the following equation to test whether
2316 two floating point values are equivalent.
2318 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2320 Unlike the built-in `math.isclose`, the above equation is not symmetric
2321 in `a` and `b` -- it assumes `b` is the reference value -- so that
2322 `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
2323 the default value of atol is not zero, and is used to determine what
2324 small values should be considered close to zero. The default value is
2325 appropriate for expected values of order unity: if the expected values
2326 are significantly smaller than one, it can result in false positives.
2327 `atol` should be carefully selected for the use case at hand. A zero value
2328 for `atol` will result in `False` if either `a` or `b` is zero.
2330 `isclose` is not defined for non-numeric data types.
2331 `bool` is considered a numeric data-type for this purpose.
2333 Examples
2334 --------
2335 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
2336 array([ True, False])
2337 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
2338 array([ True, True])
2339 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
2340 array([False, True])
2341 >>> np.isclose([1.0, np.nan], [1.0, np.nan])
2342 array([ True, False])
2343 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2344 array([ True, True])
2345 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
2346 array([ True, False])
2347 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
2348 array([False, False])
2349 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
2350 array([ True, True])
2351 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
2352 array([False, True])
2353 """
2354 def within_tol(x, y, atol, rtol):
2355 with errstate(invalid='ignore'):
2356 return less_equal(abs(x-y), atol + rtol * abs(y))
2358 x = asanyarray(a)
2359 y = asanyarray(b)
2361 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
2362 # This will cause casting of x later. Also, make sure to allow subclasses
2363 # (e.g., for numpy.ma).
2364 # NOTE: We explicitly allow timedelta, which used to work. This could
2365 # possibly be deprecated. See also gh-18286.
2366 # timedelta works if `atol` is an integer or also a timedelta.
2367 # Although, the default tolerances are unlikely to be useful
2368 if y.dtype.kind != "m":
2369 dt = multiarray.result_type(y, 1.)
2370 y = asanyarray(y, dtype=dt)
2372 xfin = isfinite(x)
2373 yfin = isfinite(y)
2374 if all(xfin) and all(yfin):
2375 return within_tol(x, y, atol, rtol)
2376 else:
2377 finite = xfin & yfin
2378 cond = zeros_like(finite, subok=True)
2379 # Because we're using boolean indexing, x & y must be the same shape.
2380 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
2381 # lib.stride_tricks, though, so we can't import it here.
2382 x = x * ones_like(cond)
2383 y = y * ones_like(cond)
2384 # Avoid subtraction with infinite/nan values...
2385 cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
2386 # Check for equality of infinite values...
2387 cond[~finite] = (x[~finite] == y[~finite])
2388 if equal_nan:
2389 # Make NaN == NaN
2390 both_nan = isnan(x) & isnan(y)
2392 # Needed to treat masked arrays correctly. = True would not work.
2393 cond[both_nan] = both_nan[both_nan]
2395 return cond[()] # Flatten 0d arrays to scalars
2398def _array_equal_dispatcher(a1, a2, equal_nan=None):
2399 return (a1, a2)
2402@array_function_dispatch(_array_equal_dispatcher)
2403def array_equal(a1, a2, equal_nan=False):
2404 """
2405 True if two arrays have the same shape and elements, False otherwise.
2407 Parameters
2408 ----------
2409 a1, a2 : array_like
2410 Input arrays.
2411 equal_nan : bool
2412 Whether to compare NaN's as equal. If the dtype of a1 and a2 is
2413 complex, values will be considered equal if either the real or the
2414 imaginary component of a given value is ``nan``.
2416 .. versionadded:: 1.19.0
2418 Returns
2419 -------
2420 b : bool
2421 Returns True if the arrays are equal.
2423 See Also
2424 --------
2425 allclose: Returns True if two arrays are element-wise equal within a
2426 tolerance.
2427 array_equiv: Returns True if input arrays are shape consistent and all
2428 elements equal.
2430 Examples
2431 --------
2432 >>> np.array_equal([1, 2], [1, 2])
2433 True
2434 >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
2435 True
2436 >>> np.array_equal([1, 2], [1, 2, 3])
2437 False
2438 >>> np.array_equal([1, 2], [1, 4])
2439 False
2440 >>> a = np.array([1, np.nan])
2441 >>> np.array_equal(a, a)
2442 False
2443 >>> np.array_equal(a, a, equal_nan=True)
2444 True
2446 When ``equal_nan`` is True, complex values with nan components are
2447 considered equal if either the real *or* the imaginary components are nan.
2449 >>> a = np.array([1 + 1j])
2450 >>> b = a.copy()
2451 >>> a.real = np.nan
2452 >>> b.imag = np.nan
2453 >>> np.array_equal(a, b, equal_nan=True)
2454 True
2455 """
2456 try:
2457 a1, a2 = asarray(a1), asarray(a2)
2458 except Exception:
2459 return False
2460 if a1.shape != a2.shape:
2461 return False
2462 if not equal_nan:
2463 return bool(asarray(a1 == a2).all())
2464 # Handling NaN values if equal_nan is True
2465 a1nan, a2nan = isnan(a1), isnan(a2)
2466 # NaN's occur at different locations
2467 if not (a1nan == a2nan).all():
2468 return False
2469 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
2470 return bool(asarray(a1[~a1nan] == a2[~a1nan]).all())
2473def _array_equiv_dispatcher(a1, a2):
2474 return (a1, a2)
2477@array_function_dispatch(_array_equiv_dispatcher)
2478def array_equiv(a1, a2):
2479 """
2480 Returns True if input arrays are shape consistent and all elements equal.
2482 Shape consistent means they are either the same shape, or one input array
2483 can be broadcasted to create the same shape as the other one.
2485 Parameters
2486 ----------
2487 a1, a2 : array_like
2488 Input arrays.
2490 Returns
2491 -------
2492 out : bool
2493 True if equivalent, False otherwise.
2495 Examples
2496 --------
2497 >>> np.array_equiv([1, 2], [1, 2])
2498 True
2499 >>> np.array_equiv([1, 2], [1, 3])
2500 False
2502 Showing the shape equivalence:
2504 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
2505 True
2506 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
2507 False
2509 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
2510 False
2512 """
2513 try:
2514 a1, a2 = asarray(a1), asarray(a2)
2515 except Exception:
2516 return False
2517 try:
2518 multiarray.broadcast(a1, a2)
2519 except Exception:
2520 return False
2522 return bool(asarray(a1 == a2).all())
2525Inf = inf = infty = Infinity = PINF
2526nan = NaN = NAN
2527False_ = bool_(False)
2528True_ = bool_(True)
2531def extend_all(module):
2532 existing = set(__all__)
2533 mall = getattr(module, '__all__')
2534 for a in mall:
2535 if a not in existing: 2535 ↛ 2534line 2535 didn't jump to line 2534, because the condition on line 2535 was never false
2536 __all__.append(a)
2539from .umath import *
2540from .numerictypes import *
2541from . import fromnumeric
2542from .fromnumeric import *
2543from . import arrayprint
2544from .arrayprint import *
2545from . import _asarray
2546from ._asarray import *
2547from . import _ufunc_config
2548from ._ufunc_config import *
2549extend_all(fromnumeric)
2550extend_all(umath)
2551extend_all(numerictypes)
2552extend_all(arrayprint)
2553extend_all(_asarray)
2554extend_all(_ufunc_config)