Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/numpy/_core/numeric.py: 27%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import builtins
2import functools
3import itertools
4import math
5import numbers
6import operator
7import sys
8import warnings
10import numpy as np
11from numpy.exceptions import AxisError
13from . import multiarray, numerictypes, numerictypes as nt, overrides, shape_base, umath
14from ._ufunc_config import errstate
15from .multiarray import ( # noqa: F401
16 ALLOW_THREADS,
17 BUFSIZE,
18 CLIP,
19 MAXDIMS,
20 MAY_SHARE_BOUNDS,
21 MAY_SHARE_EXACT,
22 RAISE,
23 WRAP,
24 arange,
25 array,
26 asanyarray,
27 asarray,
28 ascontiguousarray,
29 asfortranarray,
30 broadcast,
31 can_cast,
32 concatenate,
33 copyto,
34 dot,
35 dtype,
36 empty,
37 empty_like,
38 flatiter,
39 from_dlpack,
40 frombuffer,
41 fromfile,
42 fromiter,
43 fromstring,
44 inner,
45 lexsort,
46 matmul,
47 may_share_memory,
48 min_scalar_type,
49 ndarray,
50 nditer,
51 nested_iters,
52 normalize_axis_index,
53 promote_types,
54 putmask,
55 result_type,
56 shares_memory,
57 vdot,
58 vecdot,
59 where,
60 zeros,
61)
62from .overrides import finalize_array_function_like, set_module
63from .umath import NAN, PINF, invert, multiply, sin
65bitwise_not = invert
66ufunc = type(sin)
67newaxis = None
69array_function_dispatch = functools.partial(
70 overrides.array_function_dispatch, module='numpy')
73__all__ = [
74 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
75 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
76 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
77 'fromstring', 'fromfile', 'frombuffer', 'from_dlpack', 'where',
78 'argwhere', 'copyto', 'concatenate', 'lexsort', 'astype',
79 'can_cast', 'promote_types', 'min_scalar_type',
80 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
81 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
82 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
83 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
84 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
85 'identity', 'allclose', 'putmask',
86 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not',
87 'full', 'full_like', 'matmul', 'vecdot', 'shares_memory',
88 'may_share_memory']
91def _zeros_like_dispatcher(
92 a, dtype=None, order=None, subok=None, shape=None, *, device=None
93):
94 return (a,)
97@array_function_dispatch(_zeros_like_dispatcher)
98def zeros_like(
99 a, dtype=None, order='K', subok=True, shape=None, *, device=None
100):
101 """
102 Return an array of zeros with the same shape and type as a given array.
104 Parameters
105 ----------
106 a : array_like
107 The shape and data-type of `a` define these same attributes of
108 the returned array.
109 dtype : data-type, optional
110 Overrides the data type of the result.
111 order : {'C', 'F', 'A', or 'K'}, optional
112 Overrides the memory layout of the result. 'C' means C-order,
113 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
114 'C' otherwise. 'K' means match the layout of `a` as closely
115 as possible.
116 subok : bool, optional.
117 If True, then the newly created array will use the sub-class
118 type of `a`, otherwise it will be a base-class array. Defaults
119 to True.
120 shape : int or sequence of ints, optional.
121 Overrides the shape of the result. If order='K' and the number of
122 dimensions is unchanged, will try to keep order, otherwise,
123 order='C' is implied.
124 device : str, optional
125 The device on which to place the created array. Default: None.
126 For Array-API interoperability only, so must be ``"cpu"`` if passed.
128 .. versionadded:: 2.0.0
130 Returns
131 -------
132 out : ndarray
133 Array of zeros with the same shape and type as `a`.
135 See Also
136 --------
137 empty_like : Return an empty array with shape and type of input.
138 ones_like : Return an array of ones with shape and type of input.
139 full_like : Return a new array with shape of input filled with value.
140 zeros : Return a new array setting values to zero.
142 Examples
143 --------
144 >>> import numpy as np
145 >>> x = np.arange(6)
146 >>> x = x.reshape((2, 3))
147 >>> x
148 array([[0, 1, 2],
149 [3, 4, 5]])
150 >>> np.zeros_like(x)
151 array([[0, 0, 0],
152 [0, 0, 0]])
154 >>> y = np.arange(3, dtype=float)
155 >>> y
156 array([0., 1., 2.])
157 >>> np.zeros_like(y)
158 array([0., 0., 0.])
160 """
161 res = empty_like(
162 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
163 )
164 # needed instead of a 0 to get same result as zeros for string dtypes
165 z = zeros(1, dtype=res.dtype)
166 multiarray.copyto(res, z, casting='unsafe')
167 return res
170@finalize_array_function_like
171@set_module('numpy')
172def ones(shape, dtype=None, order='C', *, device=None, like=None):
173 """
174 Return a new array of given shape and type, filled with ones.
176 Parameters
177 ----------
178 shape : int or sequence of ints
179 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
180 dtype : data-type, optional
181 The desired data-type for the array, e.g., `numpy.int8`. Default is
182 `numpy.float64`.
183 order : {'C', 'F'}, optional, default: C
184 Whether to store multi-dimensional data in row-major
185 (C-style) or column-major (Fortran-style) order in
186 memory.
187 device : str, optional
188 The device on which to place the created array. Default: None.
189 For Array-API interoperability only, so must be ``"cpu"`` if passed.
191 .. versionadded:: 2.0.0
192 ${ARRAY_FUNCTION_LIKE}
194 .. versionadded:: 1.20.0
196 Returns
197 -------
198 out : ndarray
199 Array of ones with the given shape, dtype, and order.
201 See Also
202 --------
203 ones_like : Return an array of ones with shape and type of input.
204 empty : Return a new uninitialized array.
205 zeros : Return a new array setting values to zero.
206 full : Return a new array of given shape filled with value.
208 Examples
209 --------
210 >>> import numpy as np
211 >>> np.ones(5)
212 array([1., 1., 1., 1., 1.])
214 >>> np.ones((5,), dtype=int)
215 array([1, 1, 1, 1, 1])
217 >>> np.ones((2, 1))
218 array([[1.],
219 [1.]])
221 >>> s = (2,2)
222 >>> np.ones(s)
223 array([[1., 1.],
224 [1., 1.]])
226 """
227 if like is not None:
228 return _ones_with_like(
229 like, shape, dtype=dtype, order=order, device=device
230 )
232 a = empty(shape, dtype, order, device=device)
233 multiarray.copyto(a, 1, casting='unsafe')
234 return a
237_ones_with_like = array_function_dispatch()(ones)
240def _ones_like_dispatcher(
241 a, dtype=None, order=None, subok=None, shape=None, *, device=None
242):
243 return (a,)
246@array_function_dispatch(_ones_like_dispatcher)
247def ones_like(
248 a, dtype=None, order='K', subok=True, shape=None, *, device=None
249):
250 """
251 Return an array of ones with the same shape and type as a given array.
253 Parameters
254 ----------
255 a : array_like
256 The shape and data-type of `a` define these same attributes of
257 the returned array.
258 dtype : data-type, optional
259 Overrides the data type of the result.
260 order : {'C', 'F', 'A', or 'K'}, optional
261 Overrides the memory layout of the result. 'C' means C-order,
262 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
263 'C' otherwise. 'K' means match the layout of `a` as closely
264 as possible.
265 subok : bool, optional.
266 If True, then the newly created array will use the sub-class
267 type of `a`, otherwise it will be a base-class array. Defaults
268 to True.
269 shape : int or sequence of ints, optional.
270 Overrides the shape of the result. If order='K' and the number of
271 dimensions is unchanged, will try to keep order, otherwise,
272 order='C' is implied.
273 device : str, optional
274 The device on which to place the created array. Default: None.
275 For Array-API interoperability only, so must be ``"cpu"`` if passed.
277 .. versionadded:: 2.0.0
279 Returns
280 -------
281 out : ndarray
282 Array of ones with the same shape and type as `a`.
284 See Also
285 --------
286 empty_like : Return an empty array with shape and type of input.
287 zeros_like : Return an array of zeros with shape and type of input.
288 full_like : Return a new array with shape of input filled with value.
289 ones : Return a new array setting values to one.
291 Examples
292 --------
293 >>> import numpy as np
294 >>> x = np.arange(6)
295 >>> x = x.reshape((2, 3))
296 >>> x
297 array([[0, 1, 2],
298 [3, 4, 5]])
299 >>> np.ones_like(x)
300 array([[1, 1, 1],
301 [1, 1, 1]])
303 >>> y = np.arange(3, dtype=float)
304 >>> y
305 array([0., 1., 2.])
306 >>> np.ones_like(y)
307 array([1., 1., 1.])
309 """
310 res = empty_like(
311 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
312 )
313 multiarray.copyto(res, 1, casting='unsafe')
314 return res
317def _full_dispatcher(
318 shape, fill_value, dtype=None, order=None, *, device=None, like=None
319):
320 return (like,)
323@finalize_array_function_like
324@set_module('numpy')
325def full(shape, fill_value, dtype=None, order='C', *, device=None, like=None):
326 """
327 Return a new array of given shape and type, filled with `fill_value`.
329 Parameters
330 ----------
331 shape : int or sequence of ints
332 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
333 fill_value : scalar or array_like
334 Fill value.
335 dtype : data-type, optional
336 The desired data-type for the array The default, None, means
337 ``np.array(fill_value).dtype``.
338 order : {'C', 'F'}, optional
339 Whether to store multidimensional data in C- or Fortran-contiguous
340 (row- or column-wise) order in memory.
341 device : str, optional
342 The device on which to place the created array. Default: None.
343 For Array-API interoperability only, so must be ``"cpu"`` if passed.
345 .. versionadded:: 2.0.0
346 ${ARRAY_FUNCTION_LIKE}
348 .. versionadded:: 1.20.0
350 Returns
351 -------
352 out : ndarray
353 Array of `fill_value` with the given shape, dtype, and order.
355 See Also
356 --------
357 full_like : Return a new array with shape of input filled with value.
358 empty : Return a new uninitialized array.
359 ones : Return a new array setting values to one.
360 zeros : Return a new array setting values to zero.
362 Examples
363 --------
364 >>> import numpy as np
365 >>> np.full((2, 2), np.inf)
366 array([[inf, inf],
367 [inf, inf]])
368 >>> np.full((2, 2), 10)
369 array([[10, 10],
370 [10, 10]])
372 >>> np.full((2, 2), [1, 2])
373 array([[1, 2],
374 [1, 2]])
376 """
377 if like is not None:
378 return _full_with_like(
379 like, shape, fill_value, dtype=dtype, order=order, device=device
380 )
382 if dtype is None:
383 fill_value = asarray(fill_value)
384 dtype = fill_value.dtype
385 a = empty(shape, dtype, order, device=device)
386 multiarray.copyto(a, fill_value, casting='unsafe')
387 return a
390_full_with_like = array_function_dispatch()(full)
393def _full_like_dispatcher(
394 a, fill_value, dtype=None, order=None, subok=None, shape=None,
395 *, device=None
396):
397 return (a,)
400@array_function_dispatch(_full_like_dispatcher)
401def full_like(
402 a, fill_value, dtype=None, order='K', subok=True, shape=None,
403 *, device=None
404):
405 """
406 Return a full array with the same shape and type as a given array.
408 Parameters
409 ----------
410 a : array_like
411 The shape and data-type of `a` define these same attributes of
412 the returned array.
413 fill_value : array_like
414 Fill value.
415 dtype : data-type, optional
416 Overrides the data type of the result.
417 order : {'C', 'F', 'A', or 'K'}, optional
418 Overrides the memory layout of the result. 'C' means C-order,
419 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
420 'C' otherwise. 'K' means match the layout of `a` as closely
421 as possible.
422 subok : bool, optional.
423 If True, then the newly created array will use the sub-class
424 type of `a`, otherwise it will be a base-class array. Defaults
425 to True.
426 shape : int or sequence of ints, optional.
427 Overrides the shape of the result. If order='K' and the number of
428 dimensions is unchanged, will try to keep order, otherwise,
429 order='C' is implied.
430 device : str, optional
431 The device on which to place the created array. Default: None.
432 For Array-API interoperability only, so must be ``"cpu"`` if passed.
434 .. versionadded:: 2.0.0
436 Returns
437 -------
438 out : ndarray
439 Array of `fill_value` with the same shape and type as `a`.
441 See Also
442 --------
443 empty_like : Return an empty array with shape and type of input.
444 ones_like : Return an array of ones with shape and type of input.
445 zeros_like : Return an array of zeros with shape and type of input.
446 full : Return a new array of given shape filled with value.
448 Examples
449 --------
450 >>> import numpy as np
451 >>> x = np.arange(6, dtype=int)
452 >>> np.full_like(x, 1)
453 array([1, 1, 1, 1, 1, 1])
454 >>> np.full_like(x, 0.1)
455 array([0, 0, 0, 0, 0, 0])
456 >>> np.full_like(x, 0.1, dtype=np.double)
457 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
458 >>> np.full_like(x, np.nan, dtype=np.double)
459 array([nan, nan, nan, nan, nan, nan])
461 >>> y = np.arange(6, dtype=np.double)
462 >>> np.full_like(y, 0.1)
463 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
465 >>> y = np.zeros([2, 2, 3], dtype=int)
466 >>> np.full_like(y, [0, 0, 255])
467 array([[[ 0, 0, 255],
468 [ 0, 0, 255]],
469 [[ 0, 0, 255],
470 [ 0, 0, 255]]])
471 """
472 res = empty_like(
473 a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
474 )
475 multiarray.copyto(res, fill_value, casting='unsafe')
476 return res
479def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
480 return (a,)
483@array_function_dispatch(_count_nonzero_dispatcher)
484def count_nonzero(a, axis=None, *, keepdims=False):
485 """
486 Counts the number of non-zero values in the array ``a``.
488 The word "non-zero" is in reference to the Python 2.x
489 built-in method ``__nonzero__()`` (renamed ``__bool__()``
490 in Python 3.x) of Python objects that tests an object's
491 "truthfulness". For example, any number is considered
492 truthful if it is nonzero, whereas any string is considered
493 truthful if it is not the empty string. Thus, this function
494 (recursively) counts how many elements in ``a`` (and in
495 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
496 method evaluated to ``True``.
498 Parameters
499 ----------
500 a : array_like
501 The array for which to count non-zeros.
502 axis : int or tuple, optional
503 Axis or tuple of axes along which to count non-zeros.
504 Default is None, meaning that non-zeros will be counted
505 along a flattened version of ``a``.
506 keepdims : bool, optional
507 If this is set to True, the axes that are counted are left
508 in the result as dimensions with size one. With this option,
509 the result will broadcast correctly against the input array.
511 Returns
512 -------
513 count : int or array of int
514 Number of non-zero values in the array along a given axis.
515 Otherwise, the total number of non-zero values in the array
516 is returned.
518 See Also
519 --------
520 nonzero : Return the coordinates of all the non-zero values.
522 Examples
523 --------
524 >>> import numpy as np
525 >>> np.count_nonzero(np.eye(4))
526 np.int64(4)
527 >>> a = np.array([[0, 1, 7, 0],
528 ... [3, 0, 2, 19]])
529 >>> np.count_nonzero(a)
530 np.int64(5)
531 >>> np.count_nonzero(a, axis=0)
532 array([1, 1, 2, 1])
533 >>> np.count_nonzero(a, axis=1)
534 array([2, 3])
535 >>> np.count_nonzero(a, axis=1, keepdims=True)
536 array([[2],
537 [3]])
538 """
539 if axis is None and not keepdims:
540 return multiarray.count_nonzero(a)
542 a = asanyarray(a)
544 # TODO: this works around .astype(bool) not working properly (gh-9847)
545 if np.issubdtype(a.dtype, np.character):
546 a_bool = a != a.dtype.type()
547 else:
548 a_bool = a.astype(np.bool, copy=False)
550 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
553@set_module('numpy')
554def isfortran(a):
555 """
556 Check if the array is Fortran contiguous but *not* C contiguous.
558 This function is obsolete. If you only want to check if an array is Fortran
559 contiguous use ``a.flags.f_contiguous`` instead.
561 Parameters
562 ----------
563 a : ndarray
564 Input array.
566 Returns
567 -------
568 isfortran : bool
569 Returns True if the array is Fortran contiguous but *not* C contiguous.
572 Examples
573 --------
575 np.array allows to specify whether the array is written in C-contiguous
576 order (last index varies the fastest), or FORTRAN-contiguous order in
577 memory (first index varies the fastest).
579 >>> import numpy as np
580 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
581 >>> a
582 array([[1, 2, 3],
583 [4, 5, 6]])
584 >>> np.isfortran(a)
585 False
587 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
588 >>> b
589 array([[1, 2, 3],
590 [4, 5, 6]])
591 >>> np.isfortran(b)
592 True
595 The transpose of a C-ordered array is a FORTRAN-ordered array.
597 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
598 >>> a
599 array([[1, 2, 3],
600 [4, 5, 6]])
601 >>> np.isfortran(a)
602 False
603 >>> b = a.T
604 >>> b
605 array([[1, 4],
606 [2, 5],
607 [3, 6]])
608 >>> np.isfortran(b)
609 True
611 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
613 >>> np.isfortran(np.array([1, 2], order='F'))
614 False
616 """
617 return a.flags.fnc
620def _argwhere_dispatcher(a):
621 return (a,)
624@array_function_dispatch(_argwhere_dispatcher)
625def argwhere(a):
626 """
627 Find the indices of array elements that are non-zero, grouped by element.
629 Parameters
630 ----------
631 a : array_like
632 Input data.
634 Returns
635 -------
636 index_array : (N, a.ndim) ndarray
637 Indices of elements that are non-zero. Indices are grouped by element.
638 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
639 non-zero items.
641 See Also
642 --------
643 where, nonzero
645 Notes
646 -----
647 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
648 but produces a result of the correct shape for a 0D array.
650 The output of ``argwhere`` is not suitable for indexing arrays.
651 For this purpose use ``nonzero(a)`` instead.
653 Examples
654 --------
655 >>> import numpy as np
656 >>> x = np.arange(6).reshape(2,3)
657 >>> x
658 array([[0, 1, 2],
659 [3, 4, 5]])
660 >>> np.argwhere(x>1)
661 array([[0, 2],
662 [1, 0],
663 [1, 1],
664 [1, 2]])
666 """
667 # nonzero does not behave well on 0d, so promote to 1d
668 if np.ndim(a) == 0:
669 a = shape_base.atleast_1d(a)
670 # then remove the added dimension
671 return argwhere(a)[:, :0]
672 return transpose(nonzero(a))
675def _flatnonzero_dispatcher(a):
676 return (a,)
679@array_function_dispatch(_flatnonzero_dispatcher)
680def flatnonzero(a):
681 """
682 Return indices that are non-zero in the flattened version of a.
684 This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
686 Parameters
687 ----------
688 a : array_like
689 Input data.
691 Returns
692 -------
693 res : ndarray
694 Output array, containing the indices of the elements of ``a.ravel()``
695 that are non-zero.
697 See Also
698 --------
699 nonzero : Return the indices of the non-zero elements of the input array.
700 ravel : Return a 1-D array containing the elements of the input array.
702 Examples
703 --------
704 >>> import numpy as np
705 >>> x = np.arange(-2, 3)
706 >>> x
707 array([-2, -1, 0, 1, 2])
708 >>> np.flatnonzero(x)
709 array([0, 1, 3, 4])
711 Use the indices of the non-zero elements as an index array to extract
712 these elements:
714 >>> x.ravel()[np.flatnonzero(x)]
715 array([-2, -1, 1, 2])
717 """
718 return np.nonzero(np.ravel(a))[0]
721def _correlate_dispatcher(a, v, mode=None):
722 return (a, v)
725@array_function_dispatch(_correlate_dispatcher)
726def correlate(a, v, mode='valid'):
727 r"""
728 Cross-correlation of two 1-dimensional sequences.
730 This function computes the correlation as generally defined in signal
731 processing texts [1]_:
733 .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
735 with a and v sequences being zero-padded where necessary and
736 :math:`\overline v` denoting complex conjugation.
738 Parameters
739 ----------
740 a, v : array_like
741 Input sequences.
742 mode : {'valid', 'same', 'full'}, optional
743 Refer to the `convolve` docstring. Note that the default
744 is 'valid', unlike `convolve`, which uses 'full'.
746 Returns
747 -------
748 out : ndarray
749 Discrete cross-correlation of `a` and `v`.
751 See Also
752 --------
753 convolve : Discrete, linear convolution of two one-dimensional sequences.
754 scipy.signal.correlate : uses FFT which has superior performance
755 on large arrays.
757 Notes
758 -----
759 The definition of correlation above is not unique and sometimes
760 correlation may be defined differently. Another common definition is [1]_:
762 .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
764 which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
766 `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5)
767 because it does not use the FFT to compute the convolution; in that case,
768 `scipy.signal.correlate` might be preferable.
770 References
771 ----------
772 .. [1] Wikipedia, "Cross-correlation",
773 https://en.wikipedia.org/wiki/Cross-correlation
775 Examples
776 --------
777 >>> import numpy as np
778 >>> np.correlate([1, 2, 3], [0, 1, 0.5])
779 array([3.5])
780 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
781 array([2. , 3.5, 3. ])
782 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
783 array([0.5, 2. , 3.5, 3. , 0. ])
785 Using complex sequences:
787 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
788 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
790 Note that you get the time reversed, complex conjugated result
791 (:math:`\overline{c_{-k}}`) when the two input sequences a and v change
792 places:
794 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
795 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
797 """
798 return multiarray.correlate2(a, v, mode)
801def _convolve_dispatcher(a, v, mode=None):
802 return (a, v)
805@array_function_dispatch(_convolve_dispatcher)
806def convolve(a, v, mode='full'):
807 """
808 Returns the discrete, linear convolution of two one-dimensional sequences.
810 The convolution operator is often seen in signal processing, where it
811 models the effect of a linear time-invariant system on a signal [1]_. In
812 probability theory, the sum of two independent random variables is
813 distributed according to the convolution of their individual
814 distributions.
816 If `v` is longer than `a`, the arrays are swapped before computation.
818 Parameters
819 ----------
820 a : (N,) array_like
821 First one-dimensional input array.
822 v : (M,) array_like
823 Second one-dimensional input array.
824 mode : {'full', 'valid', 'same'}, optional
825 'full':
826 By default, mode is 'full'. This returns the convolution
827 at each point of overlap, with an output shape of (N+M-1,). At
828 the end-points of the convolution, the signals do not overlap
829 completely, and boundary effects may be seen.
831 'same':
832 Mode 'same' returns output of length ``max(M, N)``. Boundary
833 effects are still visible.
835 'valid':
836 Mode 'valid' returns output of length
837 ``max(M, N) - min(M, N) + 1``. The convolution product is only given
838 for points where the signals overlap completely. Values outside
839 the signal boundary have no effect.
841 Returns
842 -------
843 out : ndarray
844 Discrete, linear convolution of `a` and `v`.
846 See Also
847 --------
848 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
849 Transform.
850 scipy.linalg.toeplitz : Used to construct the convolution operator.
851 polymul : Polynomial multiplication. Same output as convolve, but also
852 accepts poly1d objects as input.
854 Notes
855 -----
856 The discrete convolution operation is defined as
858 .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m}
860 It can be shown that a convolution :math:`x(t) * y(t)` in time/space
861 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
862 domain, after appropriate padding (padding is necessary to prevent
863 circular convolution). Since multiplication is more efficient (faster)
864 than convolution, the function `scipy.signal.fftconvolve` exploits the
865 FFT to calculate the convolution of large data-sets.
867 References
868 ----------
869 .. [1] Wikipedia, "Convolution",
870 https://en.wikipedia.org/wiki/Convolution
872 Examples
873 --------
874 Note how the convolution operator flips the second array
875 before "sliding" the two across one another:
877 >>> import numpy as np
878 >>> np.convolve([1, 2, 3], [0, 1, 0.5])
879 array([0. , 1. , 2.5, 4. , 1.5])
881 Only return the middle values of the convolution.
882 Contains boundary effects, where zeros are taken
883 into account:
885 >>> np.convolve([1,2,3],[0,1,0.5], 'same')
886 array([1. , 2.5, 4. ])
888 The two arrays are of the same length, so there
889 is only one position where they completely overlap:
891 >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
892 array([2.5])
894 """
895 a, v = array(a, copy=None, ndmin=1), array(v, copy=None, ndmin=1)
896 if len(a) == 0:
897 raise ValueError('a cannot be empty')
898 if len(v) == 0:
899 raise ValueError('v cannot be empty')
900 if len(v) > len(a):
901 a, v = v, a
902 return multiarray.correlate(a, v[::-1], mode)
905def _outer_dispatcher(a, b, out=None):
906 return (a, b, out)
909@array_function_dispatch(_outer_dispatcher)
910def outer(a, b, out=None):
911 """
912 Compute the outer product of two vectors.
914 Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
915 the outer product [1]_ is::
917 [[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
918 [a_1*b_0 .
919 [ ... .
920 [a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
922 Parameters
923 ----------
924 a : (M,) array_like
925 First input vector. Input is flattened if
926 not already 1-dimensional.
927 b : (N,) array_like
928 Second input vector. Input is flattened if
929 not already 1-dimensional.
930 out : (M, N) ndarray, optional
931 A location where the result is stored
933 Returns
934 -------
935 out : (M, N) ndarray
936 ``out[i, j] = a[i] * b[j]``
938 See also
939 --------
940 inner
941 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
942 ufunc.outer : A generalization to dimensions other than 1D and other
943 operations. ``np.multiply.outer(a.ravel(), b.ravel())``
944 is the equivalent.
945 linalg.outer : An Array API compatible variation of ``np.outer``,
946 which accepts 1-dimensional inputs only.
947 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
948 is the equivalent.
950 References
951 ----------
952 .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
953 ed., Baltimore, MD, Johns Hopkins University Press, 1996,
954 pg. 8.
956 Examples
957 --------
958 Make a (*very* coarse) grid for computing a Mandelbrot set:
960 >>> import numpy as np
961 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
962 >>> rl
963 array([[-2., -1., 0., 1., 2.],
964 [-2., -1., 0., 1., 2.],
965 [-2., -1., 0., 1., 2.],
966 [-2., -1., 0., 1., 2.],
967 [-2., -1., 0., 1., 2.]])
968 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
969 >>> im
970 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
971 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
972 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
973 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
974 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
975 >>> grid = rl + im
976 >>> grid
977 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
978 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
979 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
980 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
981 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
983 An example using a "vector" of letters:
985 >>> x = np.array(['a', 'b', 'c'], dtype=object)
986 >>> np.outer(x, [1, 2, 3])
987 array([['a', 'aa', 'aaa'],
988 ['b', 'bb', 'bbb'],
989 ['c', 'cc', 'ccc']], dtype=object)
991 """
992 a = asarray(a)
993 b = asarray(b)
994 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
997def _tensordot_dispatcher(a, b, axes=None):
998 return (a, b)
1001@array_function_dispatch(_tensordot_dispatcher)
1002def tensordot(a, b, axes=2):
1003 """
1004 Compute tensor dot product along specified axes.
1006 Given two tensors, `a` and `b`, and an array_like object containing
1007 two array_like objects, ``(a_axes, b_axes)``, sum the products of
1008 `a`'s and `b`'s elements (components) over the axes specified by
1009 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
1010 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
1011 of `a` and the first ``N`` dimensions of `b` are summed over.
1013 Parameters
1014 ----------
1015 a, b : array_like
1016 Tensors to "dot".
1018 axes : int or (2,) array_like
1019 * integer_like
1020 If an int N, sum over the last N axes of `a` and the first N axes
1021 of `b` in order. The sizes of the corresponding axes must match.
1022 * (2,) array_like
1023 Or, a list of axes to be summed over, first sequence applying to `a`,
1024 second to `b`. Both elements array_like must be of the same length.
1025 Each axis may appear at most once; repeated axes are not allowed.
1026 For example, ``axes=([1, 1], [0, 0])`` is invalid.
1027 Returns
1028 -------
1029 output : ndarray
1030 The tensor dot product of the input.
1032 See Also
1033 --------
1034 dot, einsum
1036 Notes
1037 -----
1038 Three common use cases are:
1039 * ``axes = 0`` : tensor product :math:`a\\otimes b`
1040 * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
1041 * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
1043 When `axes` is integer_like, the sequence of axes for evaluation
1044 will be: from the -Nth axis to the -1th axis in `a`,
1045 and from the 0th axis to (N-1)th axis in `b`.
1046 For example, ``axes = 2`` is the equal to
1047 ``axes = [[-2, -1], [0, 1]]``.
1048 When N-1 is smaller than 0, or when -N is larger than -1,
1049 the element of `a` and `b` are defined as the `axes`.
1051 When there is more than one axis to sum over - and they are not the last
1052 (first) axes of `a` (`b`) - the argument `axes` should consist of
1053 two sequences of the same length, with the first axis to sum over given
1054 first in both sequences, the second axis second, and so forth.
1055 The calculation can be referred to ``numpy.einsum``.
1057 For example, if ``a.shape == (2, 3, 4)`` and ``b.shape == (3, 4, 5)``,
1058 then ``axes=([1, 2], [0, 1])`` sums over the ``(3, 4)`` dimensions of
1059 both arrays and produces an output of shape ``(2, 5)``.
1061 Each summation axis corresponds to a distinct contraction index; repeating
1062 an axis (for example ``axes=([1, 1], [0, 0])``) is invalid.
1064 The shape of the result consists of the non-contracted axes of the
1065 first tensor, followed by the non-contracted axes of the second.
1067 Examples
1068 --------
1069 An example on integer_like:
1071 >>> a_0 = np.array([[1, 2], [3, 4]])
1072 >>> b_0 = np.array([[5, 6], [7, 8]])
1073 >>> c_0 = np.tensordot(a_0, b_0, axes=0)
1074 >>> c_0.shape
1075 (2, 2, 2, 2)
1076 >>> c_0
1077 array([[[[ 5, 6],
1078 [ 7, 8]],
1079 [[10, 12],
1080 [14, 16]]],
1081 [[[15, 18],
1082 [21, 24]],
1083 [[20, 24],
1084 [28, 32]]]])
1086 An example on array_like:
1088 >>> a = np.arange(60.).reshape(3,4,5)
1089 >>> b = np.arange(24.).reshape(4,3,2)
1090 >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
1091 >>> c.shape
1092 (5, 2)
1093 >>> c
1094 array([[4400., 4730.],
1095 [4532., 4874.],
1096 [4664., 5018.],
1097 [4796., 5162.],
1098 [4928., 5306.]])
1100 A slower but equivalent way of computing the same...
1102 >>> d = np.zeros((5,2))
1103 >>> for i in range(5):
1104 ... for j in range(2):
1105 ... for k in range(3):
1106 ... for n in range(4):
1107 ... d[i,j] += a[k,n,i] * b[n,k,j]
1108 >>> c == d
1109 array([[ True, True],
1110 [ True, True],
1111 [ True, True],
1112 [ True, True],
1113 [ True, True]])
1115 An extended example taking advantage of the overloading of + and \\*:
1117 >>> a = np.array(range(1, 9)).reshape((2, 2, 2))
1118 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1119 >>> A = A.reshape((2, 2))
1120 >>> a; A
1121 array([[[1, 2],
1122 [3, 4]],
1123 [[5, 6],
1124 [7, 8]]])
1125 array([['a', 'b'],
1126 ['c', 'd']], dtype=object)
1128 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1129 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1131 >>> np.tensordot(a, A, 1)
1132 array([[['acc', 'bdd'],
1133 ['aaacccc', 'bbbdddd']],
1134 [['aaaaacccccc', 'bbbbbdddddd'],
1135 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1137 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1138 array([[[[['a', 'b'],
1139 ['c', 'd']],
1140 ...
1142 >>> np.tensordot(a, A, (0, 1))
1143 array([[['abbbbb', 'cddddd'],
1144 ['aabbbbbb', 'ccdddddd']],
1145 [['aaabbbbbbb', 'cccddddddd'],
1146 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1148 >>> np.tensordot(a, A, (2, 1))
1149 array([[['abb', 'cdd'],
1150 ['aaabbbb', 'cccdddd']],
1151 [['aaaaabbbbbb', 'cccccdddddd'],
1152 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1154 >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1155 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1157 >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1158 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1160 """
1161 try:
1162 iter(axes)
1163 except Exception:
1164 axes_a = list(range(-axes, 0))
1165 axes_b = list(range(axes))
1166 else:
1167 axes_a, axes_b = axes
1168 try:
1169 na = len(axes_a)
1170 axes_a = list(axes_a)
1171 except TypeError:
1172 axes_a = [axes_a]
1173 na = 1
1174 try:
1175 nb = len(axes_b)
1176 axes_b = list(axes_b)
1177 except TypeError:
1178 axes_b = [axes_b]
1179 nb = 1
1181 if len(set(axes_a)) != len(axes_a):
1182 raise ValueError("duplicate axes are not allowed in tensordot")
1183 if len(set(axes_b)) != len(axes_b):
1184 raise ValueError("duplicate axes are not allowed in tensordot")
1186 a, b = asarray(a), asarray(b)
1187 as_ = a.shape
1188 nda = a.ndim
1189 bs = b.shape
1190 ndb = b.ndim
1191 equal = True
1192 if na != nb:
1193 equal = False
1194 else:
1195 for k in range(na):
1196 if as_[axes_a[k]] != bs[axes_b[k]]:
1197 equal = False
1198 break
1199 if axes_a[k] < 0:
1200 axes_a[k] += nda
1201 if axes_b[k] < 0:
1202 axes_b[k] += ndb
1203 if not equal:
1204 raise ValueError("shape-mismatch for sum")
1206 # Move the axes to sum over to the end of "a"
1207 # and to the front of "b"
1208 notin = [k for k in range(nda) if k not in axes_a]
1209 newaxes_a = notin + axes_a
1210 N2 = math.prod(as_[axis] for axis in axes_a)
1211 newshape_a = (math.prod(as_[ax] for ax in notin), N2)
1212 olda = [as_[axis] for axis in notin]
1214 notin = [k for k in range(ndb) if k not in axes_b]
1215 newaxes_b = axes_b + notin
1216 N2 = math.prod(bs[axis] for axis in axes_b)
1217 newshape_b = (N2, math.prod(bs[ax] for ax in notin))
1218 oldb = [bs[axis] for axis in notin]
1220 at = a.transpose(newaxes_a).reshape(newshape_a)
1221 bt = b.transpose(newaxes_b).reshape(newshape_b)
1222 res = dot(at, bt)
1223 return res.reshape(olda + oldb)
1226def _roll_dispatcher(a, shift, axis=None):
1227 return (a,)
1230@array_function_dispatch(_roll_dispatcher)
1231def roll(a, shift, axis=None):
1232 """
1233 Roll array elements along a given axis.
1235 Elements that roll beyond the last position are re-introduced at
1236 the first.
1238 Parameters
1239 ----------
1240 a : array_like
1241 Input array.
1242 shift : int or tuple of ints
1243 The number of places by which elements are shifted. If a tuple,
1244 then `axis` must be a tuple of the same size, and each of the
1245 given axes is shifted by the corresponding number. If an int
1246 while `axis` is a tuple of ints, then the same value is used for
1247 all given axes.
1248 axis : int or tuple of ints, optional
1249 Axis or axes along which elements are shifted. By default, the
1250 array is flattened before shifting, after which the original
1251 shape is restored.
1253 Returns
1254 -------
1255 res : ndarray
1256 Output array, with the same shape as `a`.
1258 See Also
1259 --------
1260 rollaxis : Roll the specified axis backwards, until it lies in a
1261 given position.
1263 Notes
1264 -----
1265 Supports rolling over multiple dimensions simultaneously.
1267 Examples
1268 --------
1269 >>> import numpy as np
1270 >>> x = np.arange(10)
1271 >>> np.roll(x, 2)
1272 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
1273 >>> np.roll(x, -2)
1274 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
1276 >>> x2 = np.reshape(x, (2, 5))
1277 >>> x2
1278 array([[0, 1, 2, 3, 4],
1279 [5, 6, 7, 8, 9]])
1280 >>> np.roll(x2, 1)
1281 array([[9, 0, 1, 2, 3],
1282 [4, 5, 6, 7, 8]])
1283 >>> np.roll(x2, -1)
1284 array([[1, 2, 3, 4, 5],
1285 [6, 7, 8, 9, 0]])
1286 >>> np.roll(x2, 1, axis=0)
1287 array([[5, 6, 7, 8, 9],
1288 [0, 1, 2, 3, 4]])
1289 >>> np.roll(x2, -1, axis=0)
1290 array([[5, 6, 7, 8, 9],
1291 [0, 1, 2, 3, 4]])
1292 >>> np.roll(x2, 1, axis=1)
1293 array([[4, 0, 1, 2, 3],
1294 [9, 5, 6, 7, 8]])
1295 >>> np.roll(x2, -1, axis=1)
1296 array([[1, 2, 3, 4, 0],
1297 [6, 7, 8, 9, 5]])
1298 >>> np.roll(x2, (1, 1), axis=(1, 0))
1299 array([[9, 5, 6, 7, 8],
1300 [4, 0, 1, 2, 3]])
1301 >>> np.roll(x2, (2, 1), axis=(1, 0))
1302 array([[8, 9, 5, 6, 7],
1303 [3, 4, 0, 1, 2]])
1305 """
1306 a = asanyarray(a)
1307 if axis is None:
1308 return roll(a.ravel(), shift, 0).reshape(a.shape)
1310 else:
1311 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1312 broadcasted = broadcast(shift, axis)
1313 if broadcasted.ndim > 1:
1314 raise ValueError(
1315 "'shift' and 'axis' should be scalars or 1D sequences")
1316 shifts = dict.fromkeys(range(a.ndim), 0)
1317 for sh, ax in broadcasted:
1318 shifts[ax] += int(sh)
1320 rolls = [((slice(None), slice(None)),)] * a.ndim
1321 for ax, offset in shifts.items():
1322 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
1323 if offset:
1324 # (original, result), (original, result)
1325 rolls[ax] = ((slice(None, -offset), slice(offset, None)),
1326 (slice(-offset, None), slice(None, offset)))
1328 result = empty_like(a)
1329 for indices in itertools.product(*rolls):
1330 arr_index, res_index = zip(*indices)
1331 result[res_index] = a[arr_index]
1333 return result
1336def _rollaxis_dispatcher(a, axis, start=None):
1337 return (a,)
1340@array_function_dispatch(_rollaxis_dispatcher)
1341def rollaxis(a, axis, start=0):
1342 """
1343 Roll the specified axis backwards, until it lies in a given position.
1345 This function continues to be supported for backward compatibility, but you
1346 should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1347 1.11.
1349 Parameters
1350 ----------
1351 a : ndarray
1352 Input array.
1353 axis : int
1354 The axis to be rolled. The positions of the other axes do not
1355 change relative to one another.
1356 start : int, optional
1357 When ``start <= axis``, the axis is rolled back until it lies in
1358 this position. When ``start > axis``, the axis is rolled until it
1359 lies before this position. The default, 0, results in a "complete"
1360 roll. The following table describes how negative values of ``start``
1361 are interpreted:
1363 .. table::
1364 :align: left
1366 +-------------------+----------------------+
1367 | ``start`` | Normalized ``start`` |
1368 +===================+======================+
1369 | ``-(arr.ndim+1)`` | raise ``AxisError`` |
1370 +-------------------+----------------------+
1371 | ``-arr.ndim`` | 0 |
1372 +-------------------+----------------------+
1373 | |vdots| | |vdots| |
1374 +-------------------+----------------------+
1375 | ``-1`` | ``arr.ndim-1`` |
1376 +-------------------+----------------------+
1377 | ``0`` | ``0`` |
1378 +-------------------+----------------------+
1379 | |vdots| | |vdots| |
1380 +-------------------+----------------------+
1381 | ``arr.ndim`` | ``arr.ndim`` |
1382 +-------------------+----------------------+
1383 | ``arr.ndim + 1`` | raise ``AxisError`` |
1384 +-------------------+----------------------+
1386 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
1388 Returns
1389 -------
1390 res : ndarray
1391 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
1392 NumPy versions a view of `a` is returned only if the order of the
1393 axes is changed, otherwise the input array is returned.
1395 See Also
1396 --------
1397 moveaxis : Move array axes to new positions.
1398 roll : Roll the elements of an array by a number of positions along a
1399 given axis.
1401 Examples
1402 --------
1403 >>> import numpy as np
1404 >>> a = np.ones((3,4,5,6))
1405 >>> np.rollaxis(a, 3, 1).shape
1406 (3, 6, 4, 5)
1407 >>> np.rollaxis(a, 2).shape
1408 (5, 3, 4, 6)
1409 >>> np.rollaxis(a, 1, 4).shape
1410 (3, 5, 6, 4)
1412 """
1413 n = a.ndim
1414 axis = normalize_axis_index(axis, n)
1415 if start < 0:
1416 start += n
1417 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1418 if not (0 <= start < n + 1):
1419 raise AxisError(msg % ('start', -n, 'start', n + 1, start))
1420 if axis < start:
1421 # it's been removed
1422 start -= 1
1423 if axis == start:
1424 return a[...]
1425 axes = list(range(n))
1426 axes.remove(axis)
1427 axes.insert(start, axis)
1428 return a.transpose(axes)
1431@set_module("numpy.lib.array_utils")
1432def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
1433 """
1434 Normalizes an axis argument into a tuple of non-negative integer axes.
1436 This handles shorthands such as ``1`` and converts them to ``(1,)``,
1437 as well as performing the handling of negative indices covered by
1438 `normalize_axis_index`.
1440 By default, this forbids axes from being specified multiple times.
1442 Used internally by multi-axis-checking logic.
1444 Parameters
1445 ----------
1446 axis : int, iterable of int
1447 The un-normalized index or indices of the axis.
1448 ndim : int
1449 The number of dimensions of the array that `axis` should be normalized
1450 against.
1451 argname : str, optional
1452 A prefix to put before the error message, typically the name of the
1453 argument.
1454 allow_duplicate : bool, optional
1455 If False, the default, disallow an axis from being specified twice.
1457 Returns
1458 -------
1459 normalized_axes : tuple of int
1460 The normalized axis index, such that `0 <= normalized_axis < ndim`
1462 Raises
1463 ------
1464 AxisError
1465 If any axis provided is out of range
1466 ValueError
1467 If an axis is repeated
1469 See also
1470 --------
1471 normalize_axis_index : normalizing a single scalar axis
1472 """
1473 # Optimization to speed-up the most common cases.
1474 if not isinstance(axis, (tuple, list)):
1475 try:
1476 axis = [operator.index(axis)]
1477 except TypeError:
1478 pass
1479 # Going via an iterator directly is slower than via list comprehension.
1480 axis = tuple(normalize_axis_index(ax, ndim, argname) for ax in axis)
1481 if not allow_duplicate and len(set(axis)) != len(axis):
1482 if argname:
1483 raise ValueError(f'repeated axis in `{argname}` argument')
1484 else:
1485 raise ValueError('repeated axis')
1486 return axis
1489def _moveaxis_dispatcher(a, source, destination):
1490 return (a,)
1493@array_function_dispatch(_moveaxis_dispatcher)
1494def moveaxis(a, source, destination):
1495 """
1496 Move axes of an array to new positions.
1498 Other axes remain in their original order.
1500 Parameters
1501 ----------
1502 a : np.ndarray
1503 The array whose axes should be reordered.
1504 source : int or sequence of int
1505 Original positions of the axes to move. These must be unique.
1506 destination : int or sequence of int
1507 Destination positions for each of the original axes. These must also be
1508 unique.
1510 Returns
1511 -------
1512 result : np.ndarray
1513 Array with moved axes. This array is a view of the input array.
1515 See Also
1516 --------
1517 transpose : Permute the dimensions of an array.
1518 swapaxes : Interchange two axes of an array.
1520 Examples
1521 --------
1522 >>> import numpy as np
1523 >>> x = np.zeros((3, 4, 5))
1524 >>> np.moveaxis(x, 0, -1).shape
1525 (4, 5, 3)
1526 >>> np.moveaxis(x, -1, 0).shape
1527 (5, 3, 4)
1529 These all achieve the same result:
1531 >>> np.transpose(x).shape
1532 (5, 4, 3)
1533 >>> np.swapaxes(x, 0, -1).shape
1534 (5, 4, 3)
1535 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
1536 (5, 4, 3)
1537 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
1538 (5, 4, 3)
1540 """
1541 try:
1542 # allow duck-array types if they define transpose
1543 transpose = a.transpose
1544 except AttributeError:
1545 a = asarray(a)
1546 transpose = a.transpose
1548 source = normalize_axis_tuple(source, a.ndim, 'source')
1549 destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1550 if len(source) != len(destination):
1551 raise ValueError('`source` and `destination` arguments must have '
1552 'the same number of elements')
1554 order = [n for n in range(a.ndim) if n not in source]
1556 for dest, src in sorted(zip(destination, source)):
1557 order.insert(dest, src)
1559 result = transpose(order)
1560 return result
1563def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
1564 return (a, b)
1567@array_function_dispatch(_cross_dispatcher)
1568def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
1569 """
1570 Return the cross product of two (arrays of) vectors.
1572 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
1573 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
1574 are defined by the last axis of `a` and `b` by default, and these axes
1575 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
1576 2, the third component of the input vector is assumed to be zero and the
1577 cross product calculated accordingly. In cases where both input vectors
1578 have dimension 2, the z-component of the cross product is returned.
1580 Parameters
1581 ----------
1582 a : array_like
1583 Components of the first vector(s).
1584 b : array_like
1585 Components of the second vector(s).
1586 axisa : int, optional
1587 Axis of `a` that defines the vector(s). By default, the last axis.
1588 axisb : int, optional
1589 Axis of `b` that defines the vector(s). By default, the last axis.
1590 axisc : int, optional
1591 Axis of `c` containing the cross product vector(s). Ignored if
1592 both input vectors have dimension 2, as the return is scalar.
1593 By default, the last axis.
1594 axis : int, optional
1595 If defined, the axis of `a`, `b` and `c` that defines the vector(s)
1596 and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
1598 Returns
1599 -------
1600 c : ndarray
1601 Vector cross product(s).
1603 Raises
1604 ------
1605 ValueError
1606 When the dimension of the vector(s) in `a` and/or `b` does not
1607 equal 2 or 3.
1609 See Also
1610 --------
1611 inner : Inner product
1612 outer : Outer product.
1613 linalg.cross : An Array API compatible variation of ``np.cross``,
1614 which accepts (arrays of) 3-element vectors only.
1615 ix_ : Construct index arrays.
1617 Notes
1618 -----
1619 Supports full broadcasting of the inputs.
1621 Dimension-2 input arrays were deprecated in 2.0.0. If you do need this
1622 functionality, you can use::
1624 def cross2d(x, y):
1625 return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0]
1627 Examples
1628 --------
1629 Vector cross-product.
1631 >>> import numpy as np
1632 >>> x = [1, 2, 3]
1633 >>> y = [4, 5, 6]
1634 >>> np.cross(x, y)
1635 array([-3, 6, -3])
1637 One vector with dimension 2.
1639 >>> x = [1, 2]
1640 >>> y = [4, 5, 6]
1641 >>> np.cross(x, y)
1642 array([12, -6, -3])
1644 Equivalently:
1646 >>> x = [1, 2, 0]
1647 >>> y = [4, 5, 6]
1648 >>> np.cross(x, y)
1649 array([12, -6, -3])
1651 Both vectors with dimension 2.
1653 >>> x = [1,2]
1654 >>> y = [4,5]
1655 >>> np.cross(x, y)
1656 array(-3)
1658 Multiple vector cross-products. Note that the direction of the cross
1659 product vector is defined by the *right-hand rule*.
1661 >>> x = np.array([[1,2,3], [4,5,6]])
1662 >>> y = np.array([[4,5,6], [1,2,3]])
1663 >>> np.cross(x, y)
1664 array([[-3, 6, -3],
1665 [ 3, -6, 3]])
1667 The orientation of `c` can be changed using the `axisc` keyword.
1669 >>> np.cross(x, y, axisc=0)
1670 array([[-3, 3],
1671 [ 6, -6],
1672 [-3, 3]])
1674 Change the vector definition of `x` and `y` using `axisa` and `axisb`.
1676 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
1677 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
1678 >>> np.cross(x, y)
1679 array([[ -6, 12, -6],
1680 [ 0, 0, 0],
1681 [ 6, -12, 6]])
1682 >>> np.cross(x, y, axisa=0, axisb=0)
1683 array([[-24, 48, -24],
1684 [-30, 60, -30],
1685 [-36, 72, -36]])
1687 """
1688 if axis is not None:
1689 axisa, axisb, axisc = (axis,) * 3
1690 a = asarray(a)
1691 b = asarray(b)
1693 if (a.ndim < 1) or (b.ndim < 1):
1694 raise ValueError("At least one array has zero dimension")
1696 # Check axisa and axisb are within bounds
1697 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
1698 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
1700 # Move working axis to the end of the shape
1701 a = moveaxis(a, axisa, -1)
1702 b = moveaxis(b, axisb, -1)
1703 msg = ("incompatible dimensions for cross product\n"
1704 "(dimension must be 2 or 3)")
1705 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1706 raise ValueError(msg)
1707 if a.shape[-1] == 2 or b.shape[-1] == 2:
1708 # Deprecated in NumPy 2.0, 2023-09-26
1709 warnings.warn(
1710 "Arrays of 2-dimensional vectors are deprecated. Use arrays of "
1711 "3-dimensional vectors instead. (deprecated in NumPy 2.0)",
1712 DeprecationWarning, stacklevel=2
1713 )
1715 # Create the output array
1716 shape = broadcast(a[..., 0], b[..., 0]).shape
1717 if a.shape[-1] == 3 or b.shape[-1] == 3:
1718 shape += (3,)
1719 # Check axisc is within bounds
1720 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
1721 dtype = promote_types(a.dtype, b.dtype)
1722 cp = empty(shape, dtype)
1724 # recast arrays as dtype
1725 a = a.astype(dtype)
1726 b = b.astype(dtype)
1728 # create local aliases for readability
1729 a0 = a[..., 0]
1730 a1 = a[..., 1]
1731 if a.shape[-1] == 3:
1732 a2 = a[..., 2]
1733 b0 = b[..., 0]
1734 b1 = b[..., 1]
1735 if b.shape[-1] == 3:
1736 b2 = b[..., 2]
1737 if cp.ndim != 0 and cp.shape[-1] == 3:
1738 cp0 = cp[..., 0]
1739 cp1 = cp[..., 1]
1740 cp2 = cp[..., 2]
1742 if a.shape[-1] == 2:
1743 if b.shape[-1] == 2:
1744 # a0 * b1 - a1 * b0
1745 multiply(a0, b1, out=cp)
1746 cp -= a1 * b0
1747 return cp
1748 else:
1749 assert b.shape[-1] == 3
1750 # cp0 = a1 * b2 - 0 (a2 = 0)
1751 # cp1 = 0 - a0 * b2 (a2 = 0)
1752 # cp2 = a0 * b1 - a1 * b0
1753 multiply(a1, b2, out=cp0)
1754 multiply(a0, b2, out=cp1)
1755 negative(cp1, out=cp1)
1756 multiply(a0, b1, out=cp2)
1757 cp2 -= a1 * b0
1758 else:
1759 assert a.shape[-1] == 3
1760 if b.shape[-1] == 3:
1761 # cp0 = a1 * b2 - a2 * b1
1762 # cp1 = a2 * b0 - a0 * b2
1763 # cp2 = a0 * b1 - a1 * b0
1764 multiply(a1, b2, out=cp0)
1765 tmp = np.multiply(a2, b1, out=...)
1766 cp0 -= tmp
1767 multiply(a2, b0, out=cp1)
1768 multiply(a0, b2, out=tmp)
1769 cp1 -= tmp
1770 multiply(a0, b1, out=cp2)
1771 multiply(a1, b0, out=tmp)
1772 cp2 -= tmp
1773 else:
1774 assert b.shape[-1] == 2
1775 # cp0 = 0 - a2 * b1 (b2 = 0)
1776 # cp1 = a2 * b0 - 0 (b2 = 0)
1777 # cp2 = a0 * b1 - a1 * b0
1778 multiply(a2, b1, out=cp0)
1779 negative(cp0, out=cp0)
1780 multiply(a2, b0, out=cp1)
1781 multiply(a0, b1, out=cp2)
1782 cp2 -= a1 * b0
1784 return moveaxis(cp, -1, axisc)
1787little_endian = (sys.byteorder == 'little')
1790@set_module('numpy')
1791def indices(dimensions, dtype=int, sparse=False):
1792 """
1793 Return an array representing the indices of a grid.
1795 Compute an array where the subarrays contain index values 0, 1, ...
1796 varying only along the corresponding axis.
1798 Parameters
1799 ----------
1800 dimensions : sequence of ints
1801 The shape of the grid.
1802 dtype : dtype, optional
1803 Data type of the result.
1804 sparse : boolean, optional
1805 Return a sparse representation of the grid instead of a dense
1806 representation. Default is False.
1808 Returns
1809 -------
1810 grid : one ndarray or tuple of ndarrays
1811 If sparse is False:
1812 Returns one array of grid indices,
1813 ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1814 If sparse is True:
1815 Returns a tuple of arrays, with
1816 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1817 dimensions[i] in the ith place
1819 See Also
1820 --------
1821 mgrid, ogrid, meshgrid
1823 Notes
1824 -----
1825 The output shape in the dense case is obtained by prepending the number
1826 of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
1827 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
1828 ``(N, r0, ..., rN-1)``.
1830 The subarrays ``grid[k]`` contains the N-D array of indices along the
1831 ``k-th`` axis. Explicitly::
1833 grid[k, i0, i1, ..., iN-1] = ik
1835 Examples
1836 --------
1837 >>> import numpy as np
1838 >>> grid = np.indices((2, 3))
1839 >>> grid.shape
1840 (2, 2, 3)
1841 >>> grid[0] # row indices
1842 array([[0, 0, 0],
1843 [1, 1, 1]])
1844 >>> grid[1] # column indices
1845 array([[0, 1, 2],
1846 [0, 1, 2]])
1848 The indices can be used as an index into an array.
1850 >>> x = np.arange(20).reshape(5, 4)
1851 >>> row, col = np.indices((2, 3))
1852 >>> x[row, col]
1853 array([[0, 1, 2],
1854 [4, 5, 6]])
1856 Note that it would be more straightforward in the above example to
1857 extract the required elements directly with ``x[:2, :3]``.
1859 If sparse is set to true, the grid will be returned in a sparse
1860 representation.
1862 >>> i, j = np.indices((2, 3), sparse=True)
1863 >>> i.shape
1864 (2, 1)
1865 >>> j.shape
1866 (1, 3)
1867 >>> i # row indices
1868 array([[0],
1869 [1]])
1870 >>> j # column indices
1871 array([[0, 1, 2]])
1873 """
1874 dimensions = tuple(dimensions)
1875 N = len(dimensions)
1876 shape = (1,) * N
1877 if sparse:
1878 res = ()
1879 else:
1880 res = empty((N,) + dimensions, dtype=dtype)
1881 for i, dim in enumerate(dimensions):
1882 idx = arange(dim, dtype=dtype).reshape(
1883 shape[:i] + (dim,) + shape[i + 1:]
1884 )
1885 if sparse:
1886 res = res + (idx,)
1887 else:
1888 res[i] = idx
1889 return res
1892@finalize_array_function_like
1893@set_module('numpy')
1894def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
1895 """
1896 Construct an array by executing a function over each coordinate.
1898 The resulting array therefore has a value ``fn(x, y, z)`` at
1899 coordinate ``(x, y, z)``.
1901 Parameters
1902 ----------
1903 function : callable
1904 The function is called with N parameters, where N is the rank of
1905 `shape`. Each parameter represents the coordinates of the array
1906 varying along a specific axis. For example, if `shape`
1907 were ``(2, 2)``, then the parameters would be
1908 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
1909 shape : (N,) tuple of ints
1910 Shape of the output array, which also determines the shape of
1911 the coordinate arrays passed to `function`.
1912 dtype : data-type, optional
1913 Data-type of the coordinate arrays passed to `function`.
1914 By default, `dtype` is float.
1915 ${ARRAY_FUNCTION_LIKE}
1917 .. versionadded:: 1.20.0
1919 Returns
1920 -------
1921 fromfunction : any
1922 The result of the call to `function` is passed back directly.
1923 Therefore the shape of `fromfunction` is completely determined by
1924 `function`. If `function` returns a scalar value, the shape of
1925 `fromfunction` would not match the `shape` parameter.
1927 See Also
1928 --------
1929 indices, meshgrid
1931 Notes
1932 -----
1933 Keywords other than `dtype` and `like` are passed to `function`.
1935 Examples
1936 --------
1937 >>> import numpy as np
1938 >>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
1939 array([[0., 0.],
1940 [1., 1.]])
1942 >>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
1943 array([[0., 1.],
1944 [0., 1.]])
1946 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
1947 array([[ True, False, False],
1948 [False, True, False],
1949 [False, False, True]])
1951 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
1952 array([[0, 1, 2],
1953 [1, 2, 3],
1954 [2, 3, 4]])
1956 """
1957 if like is not None:
1958 return _fromfunction_with_like(
1959 like, function, shape, dtype=dtype, **kwargs)
1961 args = indices(shape, dtype=dtype)
1962 return function(*args, **kwargs)
1965_fromfunction_with_like = array_function_dispatch()(fromfunction)
1968def _frombuffer(buf, dtype, shape, order, axis_order=None):
1969 array = frombuffer(buf, dtype=dtype)
1970 if order == 'K' and axis_order is not None:
1971 return array.reshape(shape, order='C').transpose(axis_order)
1972 return array.reshape(shape, order=order)
1975@set_module('numpy')
1976def isscalar(element):
1977 """
1978 Returns True if the type of `element` is a scalar type.
1980 Parameters
1981 ----------
1982 element : any
1983 Input argument, can be of any type and shape.
1985 Returns
1986 -------
1987 val : bool
1988 True if `element` is a scalar type, False if it is not.
1990 See Also
1991 --------
1992 ndim : Get the number of dimensions of an array
1994 Notes
1995 -----
1996 If you need a stricter way to identify a *numerical* scalar, use
1997 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
1998 non-numerical elements such as strings.
2000 In most cases ``np.ndim(x) == 0`` should be used instead of this function,
2001 as that will also return true for 0d arrays. This is how numpy overloads
2002 functions in the style of the ``dx`` arguments to `gradient` and
2003 the ``bins`` argument to `histogram`. Some key differences:
2005 +------------------------------------+---------------+-------------------+
2006 | x |``isscalar(x)``|``np.ndim(x) == 0``|
2007 +====================================+===============+===================+
2008 | PEP 3141 numeric objects | ``True`` | ``True`` |
2009 | (including builtins) | | |
2010 +------------------------------------+---------------+-------------------+
2011 | builtin string and buffer objects | ``True`` | ``True`` |
2012 +------------------------------------+---------------+-------------------+
2013 | other builtin objects, like | ``False`` | ``True`` |
2014 | `pathlib.Path`, `Exception`, | | |
2015 | the result of `re.compile` | | |
2016 +------------------------------------+---------------+-------------------+
2017 | third-party objects like | ``False`` | ``True`` |
2018 | `matplotlib.figure.Figure` | | |
2019 +------------------------------------+---------------+-------------------+
2020 | zero-dimensional numpy arrays | ``False`` | ``True`` |
2021 +------------------------------------+---------------+-------------------+
2022 | other numpy arrays | ``False`` | ``False`` |
2023 +------------------------------------+---------------+-------------------+
2024 | `list`, `tuple`, and other | ``False`` | ``False`` |
2025 | sequence objects | | |
2026 +------------------------------------+---------------+-------------------+
2028 Examples
2029 --------
2030 >>> import numpy as np
2032 >>> np.isscalar(3.1)
2033 True
2035 >>> np.isscalar(np.array(3.1))
2036 False
2038 >>> np.isscalar([3.1])
2039 False
2041 >>> np.isscalar(False)
2042 True
2044 >>> np.isscalar('numpy')
2045 True
2047 NumPy supports PEP 3141 numbers:
2049 >>> from fractions import Fraction
2050 >>> np.isscalar(Fraction(5, 17))
2051 True
2052 >>> from numbers import Number
2053 >>> np.isscalar(Number())
2054 True
2056 """
2057 return (isinstance(element, generic)
2058 or type(element) in ScalarType
2059 or isinstance(element, numbers.Number))
2062@set_module('numpy')
2063def binary_repr(num, width=None):
2064 """
2065 Return the binary representation of the input number as a string.
2067 For negative numbers, if width is not given, a minus sign is added to the
2068 front. If width is given, the two's complement of the number is
2069 returned, with respect to that width.
2071 In a two's-complement system negative numbers are represented by the two's
2072 complement of the absolute value. This is the most common method of
2073 representing signed integers on computers [1]_. A N-bit two's-complement
2074 system can represent every integer in the range
2075 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
2077 Parameters
2078 ----------
2079 num : int
2080 Only an integer decimal number can be used.
2081 width : int, optional
2082 The length of the returned string if `num` is positive, or the length
2083 of the two's complement if `num` is negative, provided that `width` is
2084 at least a sufficient number of bits for `num` to be represented in
2085 the designated form. If the `width` value is insufficient, an error is
2086 raised.
2088 Returns
2089 -------
2090 bin : str
2091 Binary representation of `num` or two's complement of `num`.
2093 See Also
2094 --------
2095 base_repr: Return a string representation of a number in the given base
2096 system.
2097 bin: Python's built-in binary representation generator of an integer.
2099 Notes
2100 -----
2101 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
2102 faster.
2104 References
2105 ----------
2106 .. [1] Wikipedia, "Two's complement",
2107 https://en.wikipedia.org/wiki/Two's_complement
2109 Examples
2110 --------
2111 >>> import numpy as np
2112 >>> np.binary_repr(3)
2113 '11'
2114 >>> np.binary_repr(-3)
2115 '-11'
2116 >>> np.binary_repr(3, width=4)
2117 '0011'
2119 The two's complement is returned when the input number is negative and
2120 width is specified:
2122 >>> np.binary_repr(-3, width=3)
2123 '101'
2124 >>> np.binary_repr(-3, width=5)
2125 '11101'
2127 """
2128 def err_if_insufficient(width, binwidth):
2129 if width is not None and width < binwidth:
2130 raise ValueError(
2131 f"Insufficient bit {width=} provided for {binwidth=}"
2132 )
2134 # Ensure that num is a Python integer to avoid overflow or unwanted
2135 # casts to floating point.
2136 num = operator.index(num)
2138 if num == 0:
2139 return '0' * (width or 1)
2141 elif num > 0:
2142 binary = f'{num:b}'
2143 binwidth = len(binary)
2144 outwidth = (binwidth if width is None
2145 else builtins.max(binwidth, width))
2146 err_if_insufficient(width, binwidth)
2147 return binary.zfill(outwidth)
2149 elif width is None:
2150 return f'-{-num:b}'
2152 else:
2153 poswidth = len(f'{-num:b}')
2155 # See gh-8679: remove extra digit
2156 # for numbers at boundaries.
2157 if 2**(poswidth - 1) == -num:
2158 poswidth -= 1
2160 twocomp = 2**(poswidth + 1) + num
2161 binary = f'{twocomp:b}'
2162 binwidth = len(binary)
2164 outwidth = builtins.max(binwidth, width)
2165 err_if_insufficient(width, binwidth)
2166 return '1' * (outwidth - binwidth) + binary
2169@set_module('numpy')
2170def base_repr(number, base=2, padding=0):
2171 """
2172 Return a string representation of a number in the given base system.
2174 Parameters
2175 ----------
2176 number : int
2177 The value to convert. Positive and negative values are handled.
2178 base : int, optional
2179 Convert `number` to the `base` number system. The valid range is 2-36,
2180 the default value is 2.
2181 padding : int, optional
2182 Number of zeros padded on the left. Default is 0 (no padding).
2184 Returns
2185 -------
2186 out : str
2187 String representation of `number` in `base` system.
2189 See Also
2190 --------
2191 binary_repr : Faster version of `base_repr` for base 2.
2193 Examples
2194 --------
2195 >>> import numpy as np
2196 >>> np.base_repr(5)
2197 '101'
2198 >>> np.base_repr(6, 5)
2199 '11'
2200 >>> np.base_repr(7, base=5, padding=3)
2201 '00012'
2203 >>> np.base_repr(10, base=16)
2204 'A'
2205 >>> np.base_repr(32, base=16)
2206 '20'
2208 """
2209 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2210 if base > len(digits):
2211 raise ValueError("Bases greater than 36 not handled in base_repr.")
2212 elif base < 2:
2213 raise ValueError("Bases less than 2 not handled in base_repr.")
2215 num = abs(int(number))
2216 res = []
2217 while num:
2218 res.append(digits[num % base])
2219 num //= base
2220 if padding:
2221 res.append('0' * padding)
2222 if number < 0:
2223 res.append('-')
2224 return ''.join(reversed(res or '0'))
2227# These are all essentially abbreviations
2228# These might wind up in a special abbreviations module
2231def _maketup(descr, val):
2232 dt = dtype(descr)
2233 # Place val in all scalar tuples:
2234 fields = dt.fields
2235 if fields is None:
2236 return val
2237 else:
2238 res = [_maketup(fields[name][0], val) for name in dt.names]
2239 return tuple(res)
2242@finalize_array_function_like
2243@set_module('numpy')
2244def identity(n, dtype=None, *, like=None):
2245 """
2246 Return the identity array.
2248 The identity array is a square array with ones on
2249 the main diagonal.
2251 Parameters
2252 ----------
2253 n : int
2254 Number of rows (and columns) in `n` x `n` output.
2255 dtype : data-type, optional
2256 Data-type of the output. Defaults to ``float``.
2257 ${ARRAY_FUNCTION_LIKE}
2259 .. versionadded:: 1.20.0
2261 Returns
2262 -------
2263 out : ndarray
2264 `n` x `n` array with its main diagonal set to one,
2265 and all other elements 0.
2267 Examples
2268 --------
2269 >>> import numpy as np
2270 >>> np.identity(3)
2271 array([[1., 0., 0.],
2272 [0., 1., 0.],
2273 [0., 0., 1.]])
2275 """
2276 if like is not None:
2277 return _identity_with_like(like, n, dtype=dtype)
2279 from numpy import eye
2280 return eye(n, dtype=dtype, like=like)
2283_identity_with_like = array_function_dispatch()(identity)
2286def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2287 return (a, b, rtol, atol)
2290@array_function_dispatch(_allclose_dispatcher)
2291def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2292 """
2293 Returns True if two arrays are element-wise equal within a tolerance.
2295 The tolerance values are positive, typically very small numbers. The
2296 relative difference (`rtol` * abs(`b`)) and the absolute difference
2297 `atol` are added together to compare against the absolute difference
2298 between `a` and `b`.
2300 .. warning:: The default `atol` is not appropriate for comparing numbers
2301 with magnitudes much smaller than one (see Notes).
2303 NaNs are treated as equal if they are in the same place and if
2304 ``equal_nan=True``. Infs are treated as equal if they are in the same
2305 place and of the same sign in both arrays.
2307 Parameters
2308 ----------
2309 a, b : array_like
2310 Input arrays to compare.
2311 rtol : array_like
2312 The relative tolerance parameter (see Notes).
2313 atol : array_like
2314 The absolute tolerance parameter (see Notes).
2315 equal_nan : bool
2316 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2317 considered equal to NaN's in `b` in the output array.
2319 Returns
2320 -------
2321 allclose : bool
2322 Returns True if the two arrays are equal within the given
2323 tolerance; False otherwise.
2325 See Also
2326 --------
2327 isclose, all, any, equal
2329 Notes
2330 -----
2331 If the following equation is element-wise True, then allclose returns
2332 True.::
2334 absolute(a - b) <= (atol + rtol * absolute(b))
2336 The above equation is not symmetric in `a` and `b`, so that
2337 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
2338 some rare cases.
2340 The default value of `atol` is not appropriate when the reference value
2341 `b` has magnitude smaller than one. For example, it is unlikely that
2342 ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
2343 ``allclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
2344 to select `atol` for the use case at hand, especially for defining the
2345 threshold below which a non-zero value in `a` will be considered "close"
2346 to a very small or zero value in `b`.
2348 The comparison of `a` and `b` uses standard broadcasting, which
2349 means that `a` and `b` need not have the same shape in order for
2350 ``allclose(a, b)`` to evaluate to True. The same is true for
2351 `equal` but not `array_equal`.
2353 `allclose` is not defined for non-numeric data types.
2354 `bool` is considered a numeric data-type for this purpose.
2356 Examples
2357 --------
2358 >>> import numpy as np
2359 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
2360 False
2362 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
2363 True
2365 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
2366 False
2368 >>> np.allclose([1.0, np.nan], [1.0, np.nan])
2369 False
2371 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2372 True
2375 """
2376 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2377 return builtins.bool(res)
2380def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2381 return (a, b, rtol, atol)
2384@array_function_dispatch(_isclose_dispatcher)
2385def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2386 """
2387 Returns a boolean array where two arrays are element-wise equal within a
2388 tolerance.
2390 The tolerance values are positive, typically very small numbers. The
2391 relative difference (`rtol` * abs(`b`)) and the absolute difference
2392 `atol` are added together to compare against the absolute difference
2393 between `a` and `b`.
2395 .. warning:: The default `atol` is not appropriate for comparing numbers
2396 with magnitudes much smaller than one (see Notes).
2398 Parameters
2399 ----------
2400 a, b : array_like
2401 Input arrays to compare.
2402 rtol : array_like
2403 The relative tolerance parameter (see Notes).
2404 atol : array_like
2405 The absolute tolerance parameter (see Notes).
2406 equal_nan : bool
2407 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2408 considered equal to NaN's in `b` in the output array.
2410 Returns
2411 -------
2412 y : array_like
2413 Returns a boolean array of where `a` and `b` are equal within the
2414 given tolerance. If both `a` and `b` are scalars, returns a single
2415 boolean value.
2417 See Also
2418 --------
2419 allclose
2420 math.isclose
2422 Notes
2423 -----
2424 For finite values, isclose uses the following equation to test whether
2425 two floating point values are equivalent.::
2427 absolute(a - b) <= (atol + rtol * absolute(b))
2429 Unlike the built-in `math.isclose`, the above equation is not symmetric
2430 in `a` and `b` -- it assumes `b` is the reference value -- so that
2431 `isclose(a, b)` might be different from `isclose(b, a)`.
2433 The default value of `atol` is not appropriate when the reference value
2434 `b` has magnitude smaller than one. For example, it is unlikely that
2435 ``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
2436 ``isclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
2437 to select `atol` for the use case at hand, especially for defining the
2438 threshold below which a non-zero value in `a` will be considered "close"
2439 to a very small or zero value in `b`.
2441 `isclose` is not defined for non-numeric data types.
2442 :class:`bool` is considered a numeric data-type for this purpose.
2444 Examples
2445 --------
2446 >>> import numpy as np
2447 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
2448 array([ True, False])
2450 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
2451 array([ True, True])
2453 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
2454 array([False, True])
2456 >>> np.isclose([1.0, np.nan], [1.0, np.nan])
2457 array([ True, False])
2459 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2460 array([ True, True])
2462 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
2463 array([ True, False])
2465 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
2466 array([False, False])
2468 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
2469 array([ True, True])
2471 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
2472 array([False, True])
2474 """
2475 # Turn all but python scalars into arrays.
2476 x, y, atol, rtol = (
2477 a if isinstance(a, (int, float, complex)) else asanyarray(a)
2478 for a in (a, b, atol, rtol))
2480 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
2481 # This will cause casting of x later. Also, make sure to allow subclasses
2482 # (e.g., for numpy.ma).
2483 # NOTE: We explicitly allow timedelta, which used to work. This could
2484 # possibly be deprecated. See also gh-18286.
2485 # timedelta works if `atol` is an integer or also a timedelta.
2486 # Although, the default tolerances are unlikely to be useful
2487 if (dtype := getattr(y, "dtype", None)) is not None and dtype.kind != "m":
2488 dt = multiarray.result_type(y, 1.)
2489 y = asanyarray(y, dtype=dt)
2490 elif isinstance(y, int):
2491 y = float(y)
2493 # atol and rtol can be arrays
2494 if not (np.all(np.isfinite(atol)) and np.all(np.isfinite(rtol))):
2495 err_s = np.geterr()["invalid"]
2496 err_msg = f"One of rtol or atol is not valid, atol: {atol}, rtol: {rtol}"
2498 if err_s == "warn":
2499 warnings.warn(err_msg, RuntimeWarning, stacklevel=2)
2500 elif err_s == "raise":
2501 raise FloatingPointError(err_msg)
2502 elif err_s == "print":
2503 print(err_msg)
2505 with errstate(invalid='ignore'):
2507 result = (less_equal(abs(x - y), atol + rtol * abs(y))
2508 & isfinite(y)
2509 | (x == y))
2510 if equal_nan:
2511 result |= isnan(x) & isnan(y)
2513 return result[()] # Flatten 0d arrays to scalars
2516def _array_equal_dispatcher(a1, a2, equal_nan=None):
2517 return (a1, a2)
2520_no_nan_types = {
2521 # should use np.dtype.BoolDType, but as of writing
2522 # that fails the reloading test.
2523 type(dtype(nt.bool)),
2524 type(dtype(nt.int8)),
2525 type(dtype(nt.int16)),
2526 type(dtype(nt.int32)),
2527 type(dtype(nt.int64)),
2528}
2531def _dtype_cannot_hold_nan(dtype):
2532 return type(dtype) in _no_nan_types
2535@array_function_dispatch(_array_equal_dispatcher)
2536def array_equal(a1, a2, equal_nan=False):
2537 """
2538 True if two arrays have the same shape and elements, False otherwise.
2540 Parameters
2541 ----------
2542 a1, a2 : array_like
2543 Input arrays.
2544 equal_nan : bool
2545 Whether to compare NaN's as equal. If the dtype of a1 and a2 is
2546 complex, values will be considered equal if either the real or the
2547 imaginary component of a given value is ``nan``.
2549 Returns
2550 -------
2551 b : bool
2552 Returns True if the arrays are equal.
2554 See Also
2555 --------
2556 allclose: Returns True if two arrays are element-wise equal within a
2557 tolerance.
2558 array_equiv: Returns True if input arrays are shape consistent and all
2559 elements equal.
2561 Examples
2562 --------
2563 >>> import numpy as np
2565 >>> np.array_equal([1, 2], [1, 2])
2566 True
2568 >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
2569 True
2571 >>> np.array_equal([1, 2], [1, 2, 3])
2572 False
2574 >>> np.array_equal([1, 2], [1, 4])
2575 False
2577 >>> a = np.array([1, np.nan])
2578 >>> np.array_equal(a, a)
2579 False
2581 >>> np.array_equal(a, a, equal_nan=True)
2582 True
2584 When ``equal_nan`` is True, complex values with nan components are
2585 considered equal if either the real *or* the imaginary components are nan.
2587 >>> a = np.array([1 + 1j])
2588 >>> b = a.copy()
2589 >>> a.real = np.nan
2590 >>> b.imag = np.nan
2591 >>> np.array_equal(a, b, equal_nan=True)
2592 True
2593 """
2594 try:
2595 a1, a2 = asarray(a1), asarray(a2)
2596 except Exception:
2597 return False
2598 if a1.shape != a2.shape:
2599 return False
2600 if not equal_nan:
2601 return builtins.bool((asanyarray(a1 == a2)).all())
2603 if a1 is a2:
2604 # nan will compare equal so an array will compare equal to itself.
2605 return True
2607 cannot_have_nan = (_dtype_cannot_hold_nan(a1.dtype)
2608 and _dtype_cannot_hold_nan(a2.dtype))
2609 if cannot_have_nan:
2610 return builtins.bool(asarray(a1 == a2).all())
2612 # Handling NaN values if equal_nan is True
2613 a1nan, a2nan = isnan(a1), isnan(a2)
2614 # NaN's occur at different locations
2615 if not (a1nan == a2nan).all():
2616 return False
2617 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
2618 return builtins.bool((a1[~a1nan] == a2[~a1nan]).all())
2621def _array_equiv_dispatcher(a1, a2):
2622 return (a1, a2)
2625@array_function_dispatch(_array_equiv_dispatcher)
2626def array_equiv(a1, a2):
2627 """
2628 Returns True if input arrays are shape consistent and all elements equal.
2630 Shape consistent means they are either the same shape, or one input array
2631 can be broadcasted to create the same shape as the other one.
2633 Parameters
2634 ----------
2635 a1, a2 : array_like
2636 Input arrays.
2638 Returns
2639 -------
2640 out : bool
2641 True if equivalent, False otherwise.
2643 Examples
2644 --------
2645 >>> import numpy as np
2646 >>> np.array_equiv([1, 2], [1, 2])
2647 True
2648 >>> np.array_equiv([1, 2], [1, 3])
2649 False
2651 Showing the shape equivalence:
2653 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
2654 True
2655 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
2656 False
2658 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
2659 False
2661 """
2662 try:
2663 a1, a2 = asarray(a1), asarray(a2)
2664 except Exception:
2665 return False
2666 try:
2667 multiarray.broadcast(a1, a2)
2668 except Exception:
2669 return False
2671 return builtins.bool(asanyarray(a1 == a2).all())
2674def _astype_dispatcher(x, dtype, /, *, copy=None, device=None):
2675 return (x, dtype)
2678@array_function_dispatch(_astype_dispatcher)
2679def astype(x, dtype, /, *, copy=True, device=None):
2680 """
2681 Copies an array to a specified data type.
2683 This function is an Array API compatible alternative to
2684 `numpy.ndarray.astype`.
2686 Parameters
2687 ----------
2688 x : ndarray
2689 Input NumPy array to cast. ``array_likes`` are explicitly not
2690 supported here.
2691 dtype : dtype
2692 Data type of the result.
2693 copy : bool, optional
2694 Specifies whether to copy an array when the specified dtype matches
2695 the data type of the input array ``x``. If ``True``, a newly allocated
2696 array must always be returned. If ``False`` and the specified dtype
2697 matches the data type of the input array, the input array must be
2698 returned; otherwise, a newly allocated array must be returned.
2699 Defaults to ``True``.
2700 device : str, optional
2701 The device on which to place the returned array. Default: None.
2702 For Array-API interoperability only, so must be ``"cpu"`` if passed.
2704 .. versionadded:: 2.1.0
2706 Returns
2707 -------
2708 out : ndarray
2709 An array having the specified data type.
2711 See Also
2712 --------
2713 ndarray.astype
2715 Examples
2716 --------
2717 >>> import numpy as np
2718 >>> arr = np.array([1, 2, 3]); arr
2719 array([1, 2, 3])
2720 >>> np.astype(arr, np.float64)
2721 array([1., 2., 3.])
2723 Non-copy case:
2725 >>> arr = np.array([1, 2, 3])
2726 >>> arr_noncpy = np.astype(arr, arr.dtype, copy=False)
2727 >>> np.shares_memory(arr, arr_noncpy)
2728 True
2730 """
2731 if not (isinstance(x, np.ndarray) or isscalar(x)):
2732 raise TypeError(
2733 "Input should be a NumPy array or scalar. "
2734 f"It is a {type(x)} instead."
2735 )
2736 if device is not None and device != "cpu":
2737 raise ValueError(
2738 'Device not understood. Only "cpu" is allowed, but received:'
2739 f' {device}'
2740 )
2741 return x.astype(dtype, copy=copy)
2744inf = PINF
2745nan = NAN
2746False_ = nt.bool(False)
2747True_ = nt.bool(True)
2750def extend_all(module):
2751 existing = set(__all__)
2752 mall = module.__all__
2753 for a in mall:
2754 if a not in existing:
2755 __all__.append(a)
2758from . import _asarray, _ufunc_config, arrayprint, fromnumeric
2759from ._asarray import *
2760from ._ufunc_config import *
2761from .arrayprint import *
2762from .fromnumeric import *
2763from .numerictypes import *
2764from .umath import *
2766extend_all(fromnumeric)
2767extend_all(umath)
2768extend_all(numerictypes)
2769extend_all(arrayprint)
2770extend_all(_asarray)
2771extend_all(_ufunc_config)