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