Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/numpy/core/numeric.py : 28%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import functools
2import itertools
3import operator
4import sys
5import warnings
6import numbers
8import numpy as np
9from . import multiarray
10from .multiarray import (
11 _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS,
12 BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE,
13 WRAP, arange, array, broadcast, can_cast, compare_chararrays,
14 concatenate, copyto, dot, dtype, empty,
15 empty_like, flatiter, frombuffer, fromfile, fromiter, fromstring,
16 inner, lexsort, matmul, may_share_memory,
17 min_scalar_type, ndarray, nditer, nested_iters, promote_types,
18 putmask, result_type, set_numeric_ops, shares_memory, vdot, where,
19 zeros, normalize_axis_index)
21from . import overrides
22from . import umath
23from . import shape_base
24from .overrides import set_module
25from .umath import (multiply, invert, sin, PINF, NAN)
26from . import numerictypes
27from .numerictypes import longlong, intc, int_, float_, complex_, bool_
28from ._exceptions import TooHardError, AxisError
29from ._asarray import asarray, asanyarray
30from ._ufunc_config import errstate
32bitwise_not = invert
33ufunc = type(sin)
34newaxis = None
36array_function_dispatch = functools.partial(
37 overrides.array_function_dispatch, module='numpy')
40__all__ = [
41 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
42 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
43 'fromstring', 'fromfile', 'frombuffer', 'where',
44 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
45 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
46 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
47 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
48 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
49 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
50 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
51 'identity', 'allclose', 'compare_chararrays', 'putmask',
52 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN',
53 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS',
54 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like',
55 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS',
56 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError']
59@set_module('numpy')
60class ComplexWarning(RuntimeWarning):
61 """
62 The warning raised when casting a complex dtype to a real dtype.
64 As implemented, casting a complex number to a real discards its imaginary
65 part, but this behavior may not be what the user actually wants.
67 """
68 pass
71def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
72 return (a,)
75@array_function_dispatch(_zeros_like_dispatcher)
76def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
77 """
78 Return an array of zeros with the same shape and type as a given array.
80 Parameters
81 ----------
82 a : array_like
83 The shape and data-type of `a` define these same attributes of
84 the returned array.
85 dtype : data-type, optional
86 Overrides the data type of the result.
88 .. versionadded:: 1.6.0
89 order : {'C', 'F', 'A', or 'K'}, optional
90 Overrides the memory layout of the result. 'C' means C-order,
91 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
92 'C' otherwise. 'K' means match the layout of `a` as closely
93 as possible.
95 .. versionadded:: 1.6.0
96 subok : bool, optional.
97 If True, then the newly created array will use the sub-class
98 type of 'a', otherwise it will be a base-class array. Defaults
99 to True.
100 shape : int or sequence of ints, optional.
101 Overrides the shape of the result. If order='K' and the number of
102 dimensions is unchanged, will try to keep order, otherwise,
103 order='C' is implied.
105 .. versionadded:: 1.17.0
107 Returns
108 -------
109 out : ndarray
110 Array of zeros with the same shape and type as `a`.
112 See Also
113 --------
114 empty_like : Return an empty array with shape and type of input.
115 ones_like : Return an array of ones with shape and type of input.
116 full_like : Return a new array with shape of input filled with value.
117 zeros : Return a new array setting values to zero.
119 Examples
120 --------
121 >>> x = np.arange(6)
122 >>> x = x.reshape((2, 3))
123 >>> x
124 array([[0, 1, 2],
125 [3, 4, 5]])
126 >>> np.zeros_like(x)
127 array([[0, 0, 0],
128 [0, 0, 0]])
130 >>> y = np.arange(3, dtype=float)
131 >>> y
132 array([0., 1., 2.])
133 >>> np.zeros_like(y)
134 array([0., 0., 0.])
136 """
137 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
138 # needed instead of a 0 to get same result as zeros for for string dtypes
139 z = zeros(1, dtype=res.dtype)
140 multiarray.copyto(res, z, casting='unsafe')
141 return res
144@set_module('numpy')
145def ones(shape, dtype=None, order='C'):
146 """
147 Return a new array of given shape and type, filled with ones.
149 Parameters
150 ----------
151 shape : int or sequence of ints
152 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
153 dtype : data-type, optional
154 The desired data-type for the array, e.g., `numpy.int8`. Default is
155 `numpy.float64`.
156 order : {'C', 'F'}, optional, default: C
157 Whether to store multi-dimensional data in row-major
158 (C-style) or column-major (Fortran-style) order in
159 memory.
161 Returns
162 -------
163 out : ndarray
164 Array of ones with the given shape, dtype, and order.
166 See Also
167 --------
168 ones_like : Return an array of ones with shape and type of input.
169 empty : Return a new uninitialized array.
170 zeros : Return a new array setting values to zero.
171 full : Return a new array of given shape filled with value.
174 Examples
175 --------
176 >>> np.ones(5)
177 array([1., 1., 1., 1., 1.])
179 >>> np.ones((5,), dtype=int)
180 array([1, 1, 1, 1, 1])
182 >>> np.ones((2, 1))
183 array([[1.],
184 [1.]])
186 >>> s = (2,2)
187 >>> np.ones(s)
188 array([[1., 1.],
189 [1., 1.]])
191 """
192 a = empty(shape, dtype, order)
193 multiarray.copyto(a, 1, casting='unsafe')
194 return a
197def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
198 return (a,)
201@array_function_dispatch(_ones_like_dispatcher)
202def ones_like(a, dtype=None, order='K', subok=True, shape=None):
203 """
204 Return an array of ones with the same shape and type as a given array.
206 Parameters
207 ----------
208 a : array_like
209 The shape and data-type of `a` define these same attributes of
210 the returned array.
211 dtype : data-type, optional
212 Overrides the data type of the result.
214 .. versionadded:: 1.6.0
215 order : {'C', 'F', 'A', or 'K'}, optional
216 Overrides the memory layout of the result. 'C' means C-order,
217 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
218 'C' otherwise. 'K' means match the layout of `a` as closely
219 as possible.
221 .. versionadded:: 1.6.0
222 subok : bool, optional.
223 If True, then the newly created array will use the sub-class
224 type of 'a', otherwise it will be a base-class array. Defaults
225 to True.
226 shape : int or sequence of ints, optional.
227 Overrides the shape of the result. If order='K' and the number of
228 dimensions is unchanged, will try to keep order, otherwise,
229 order='C' is implied.
231 .. versionadded:: 1.17.0
233 Returns
234 -------
235 out : ndarray
236 Array of ones with the same shape and type as `a`.
238 See Also
239 --------
240 empty_like : Return an empty array with shape and type of input.
241 zeros_like : Return an array of zeros with shape and type of input.
242 full_like : Return a new array with shape of input filled with value.
243 ones : Return a new array setting values to one.
245 Examples
246 --------
247 >>> x = np.arange(6)
248 >>> x = x.reshape((2, 3))
249 >>> x
250 array([[0, 1, 2],
251 [3, 4, 5]])
252 >>> np.ones_like(x)
253 array([[1, 1, 1],
254 [1, 1, 1]])
256 >>> y = np.arange(3, dtype=float)
257 >>> y
258 array([0., 1., 2.])
259 >>> np.ones_like(y)
260 array([1., 1., 1.])
262 """
263 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
264 multiarray.copyto(res, 1, casting='unsafe')
265 return res
268@set_module('numpy')
269def full(shape, fill_value, dtype=None, order='C'):
270 """
271 Return a new array of given shape and type, filled with `fill_value`.
273 Parameters
274 ----------
275 shape : int or sequence of ints
276 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
277 fill_value : scalar or array_like
278 Fill value.
279 dtype : data-type, optional
280 The desired data-type for the array The default, None, means
281 `np.array(fill_value).dtype`.
282 order : {'C', 'F'}, optional
283 Whether to store multidimensional data in C- or Fortran-contiguous
284 (row- or column-wise) order in memory.
286 Returns
287 -------
288 out : ndarray
289 Array of `fill_value` with the given shape, dtype, and order.
291 See Also
292 --------
293 full_like : Return a new array with shape of input filled with value.
294 empty : Return a new uninitialized array.
295 ones : Return a new array setting values to one.
296 zeros : Return a new array setting values to zero.
298 Examples
299 --------
300 >>> np.full((2, 2), np.inf)
301 array([[inf, inf],
302 [inf, inf]])
303 >>> np.full((2, 2), 10)
304 array([[10, 10],
305 [10, 10]])
307 >>> np.full((2, 2), [1, 2])
308 array([[1, 2],
309 [1, 2]])
311 """
312 if dtype is None:
313 dtype = array(fill_value).dtype
314 a = empty(shape, dtype, order)
315 multiarray.copyto(a, fill_value, casting='unsafe')
316 return a
319def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None):
320 return (a,)
323@array_function_dispatch(_full_like_dispatcher)
324def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
325 """
326 Return a full array with the same shape and type as a given array.
328 Parameters
329 ----------
330 a : array_like
331 The shape and data-type of `a` define these same attributes of
332 the returned array.
333 fill_value : scalar
334 Fill value.
335 dtype : data-type, optional
336 Overrides the data type of the result.
337 order : {'C', 'F', 'A', or 'K'}, optional
338 Overrides the memory layout of the result. 'C' means C-order,
339 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
340 'C' otherwise. 'K' means match the layout of `a` as closely
341 as possible.
342 subok : bool, optional.
343 If True, then the newly created array will use the sub-class
344 type of 'a', otherwise it will be a base-class array. Defaults
345 to True.
346 shape : int or sequence of ints, optional.
347 Overrides the shape of the result. If order='K' and the number of
348 dimensions is unchanged, will try to keep order, otherwise,
349 order='C' is implied.
351 .. versionadded:: 1.17.0
353 Returns
354 -------
355 out : ndarray
356 Array of `fill_value` with the same shape and type as `a`.
358 See Also
359 --------
360 empty_like : Return an empty array with shape and type of input.
361 ones_like : Return an array of ones with shape and type of input.
362 zeros_like : Return an array of zeros with shape and type of input.
363 full : Return a new array of given shape filled with value.
365 Examples
366 --------
367 >>> x = np.arange(6, dtype=int)
368 >>> np.full_like(x, 1)
369 array([1, 1, 1, 1, 1, 1])
370 >>> np.full_like(x, 0.1)
371 array([0, 0, 0, 0, 0, 0])
372 >>> np.full_like(x, 0.1, dtype=np.double)
373 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
374 >>> np.full_like(x, np.nan, dtype=np.double)
375 array([nan, nan, nan, nan, nan, nan])
377 >>> y = np.arange(6, dtype=np.double)
378 >>> np.full_like(y, 0.1)
379 array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
381 """
382 res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
383 multiarray.copyto(res, fill_value, casting='unsafe')
384 return res
387def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
388 return (a,)
391@array_function_dispatch(_count_nonzero_dispatcher)
392def count_nonzero(a, axis=None, *, keepdims=False):
393 """
394 Counts the number of non-zero values in the array ``a``.
396 The word "non-zero" is in reference to the Python 2.x
397 built-in method ``__nonzero__()`` (renamed ``__bool__()``
398 in Python 3.x) of Python objects that tests an object's
399 "truthfulness". For example, any number is considered
400 truthful if it is nonzero, whereas any string is considered
401 truthful if it is not the empty string. Thus, this function
402 (recursively) counts how many elements in ``a`` (and in
403 sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
404 method evaluated to ``True``.
406 Parameters
407 ----------
408 a : array_like
409 The array for which to count non-zeros.
410 axis : int or tuple, optional
411 Axis or tuple of axes along which to count non-zeros.
412 Default is None, meaning that non-zeros will be counted
413 along a flattened version of ``a``.
415 .. versionadded:: 1.12.0
417 keepdims : bool, optional
418 If this is set to True, the axes that are counted are left
419 in the result as dimensions with size one. With this option,
420 the result will broadcast correctly against the input array.
422 .. versionadded:: 1.19.0
424 Returns
425 -------
426 count : int or array of int
427 Number of non-zero values in the array along a given axis.
428 Otherwise, the total number of non-zero values in the array
429 is returned.
431 See Also
432 --------
433 nonzero : Return the coordinates of all the non-zero values.
435 Examples
436 --------
437 >>> np.count_nonzero(np.eye(4))
438 4
439 >>> a = np.array([[0, 1, 7, 0],
440 ... [3, 0, 2, 19]])
441 >>> np.count_nonzero(a)
442 5
443 >>> np.count_nonzero(a, axis=0)
444 array([1, 1, 2, 1])
445 >>> np.count_nonzero(a, axis=1)
446 array([2, 3])
447 >>> np.count_nonzero(a, axis=1, keepdims=True)
448 array([[2],
449 [3]])
450 """
451 if axis is None and not keepdims:
452 return multiarray.count_nonzero(a)
454 a = asanyarray(a)
456 # TODO: this works around .astype(bool) not working properly (gh-9847)
457 if np.issubdtype(a.dtype, np.character):
458 a_bool = a != a.dtype.type()
459 else:
460 a_bool = a.astype(np.bool_, copy=False)
462 return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
465@set_module('numpy')
466def isfortran(a):
467 """
468 Check if the array is Fortran contiguous but *not* C contiguous.
470 This function is obsolete and, because of changes due to relaxed stride
471 checking, its return value for the same array may differ for versions
472 of NumPy >= 1.10.0 and previous versions. If you only want to check if an
473 array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
475 Parameters
476 ----------
477 a : ndarray
478 Input array.
480 Returns
481 -------
482 isfortran : bool
483 Returns True if the array is Fortran contiguous but *not* C contiguous.
486 Examples
487 --------
489 np.array allows to specify whether the array is written in C-contiguous
490 order (last index varies the fastest), or FORTRAN-contiguous order in
491 memory (first index varies the fastest).
493 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
494 >>> a
495 array([[1, 2, 3],
496 [4, 5, 6]])
497 >>> np.isfortran(a)
498 False
500 >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
501 >>> b
502 array([[1, 2, 3],
503 [4, 5, 6]])
504 >>> np.isfortran(b)
505 True
508 The transpose of a C-ordered array is a FORTRAN-ordered array.
510 >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
511 >>> a
512 array([[1, 2, 3],
513 [4, 5, 6]])
514 >>> np.isfortran(a)
515 False
516 >>> b = a.T
517 >>> b
518 array([[1, 4],
519 [2, 5],
520 [3, 6]])
521 >>> np.isfortran(b)
522 True
524 C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
526 >>> np.isfortran(np.array([1, 2], order='F'))
527 False
529 """
530 return a.flags.fnc
533def _argwhere_dispatcher(a):
534 return (a,)
537@array_function_dispatch(_argwhere_dispatcher)
538def argwhere(a):
539 """
540 Find the indices of array elements that are non-zero, grouped by element.
542 Parameters
543 ----------
544 a : array_like
545 Input data.
547 Returns
548 -------
549 index_array : (N, a.ndim) ndarray
550 Indices of elements that are non-zero. Indices are grouped by element.
551 This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
552 non-zero items.
554 See Also
555 --------
556 where, nonzero
558 Notes
559 -----
560 ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
561 but produces a result of the correct shape for a 0D array.
563 The output of ``argwhere`` is not suitable for indexing arrays.
564 For this purpose use ``nonzero(a)`` instead.
566 Examples
567 --------
568 >>> x = np.arange(6).reshape(2,3)
569 >>> x
570 array([[0, 1, 2],
571 [3, 4, 5]])
572 >>> np.argwhere(x>1)
573 array([[0, 2],
574 [1, 0],
575 [1, 1],
576 [1, 2]])
578 """
579 # nonzero does not behave well on 0d, so promote to 1d
580 if np.ndim(a) == 0:
581 a = shape_base.atleast_1d(a)
582 # then remove the added dimension
583 return argwhere(a)[:,:0]
584 return transpose(nonzero(a))
587def _flatnonzero_dispatcher(a):
588 return (a,)
591@array_function_dispatch(_flatnonzero_dispatcher)
592def flatnonzero(a):
593 """
594 Return indices that are non-zero in the flattened version of a.
596 This is equivalent to np.nonzero(np.ravel(a))[0].
598 Parameters
599 ----------
600 a : array_like
601 Input data.
603 Returns
604 -------
605 res : ndarray
606 Output array, containing the indices of the elements of `a.ravel()`
607 that are non-zero.
609 See Also
610 --------
611 nonzero : Return the indices of the non-zero elements of the input array.
612 ravel : Return a 1-D array containing the elements of the input array.
614 Examples
615 --------
616 >>> x = np.arange(-2, 3)
617 >>> x
618 array([-2, -1, 0, 1, 2])
619 >>> np.flatnonzero(x)
620 array([0, 1, 3, 4])
622 Use the indices of the non-zero elements as an index array to extract
623 these elements:
625 >>> x.ravel()[np.flatnonzero(x)]
626 array([-2, -1, 1, 2])
628 """
629 return np.nonzero(np.ravel(a))[0]
632_mode_from_name_dict = {'v': 0,
633 's': 1,
634 'f': 2}
637def _mode_from_name(mode):
638 if isinstance(mode, str):
639 return _mode_from_name_dict[mode.lower()[0]]
640 return mode
643def _correlate_dispatcher(a, v, mode=None):
644 return (a, v)
647@array_function_dispatch(_correlate_dispatcher)
648def correlate(a, v, mode='valid'):
649 """
650 Cross-correlation of two 1-dimensional sequences.
652 This function computes the correlation as generally defined in signal
653 processing texts::
655 c_{av}[k] = sum_n a[n+k] * conj(v[n])
657 with a and v sequences being zero-padded where necessary and conj being
658 the conjugate.
660 Parameters
661 ----------
662 a, v : array_like
663 Input sequences.
664 mode : {'valid', 'same', 'full'}, optional
665 Refer to the `convolve` docstring. Note that the default
666 is 'valid', unlike `convolve`, which uses 'full'.
667 old_behavior : bool
668 `old_behavior` was removed in NumPy 1.10. If you need the old
669 behavior, use `multiarray.correlate`.
671 Returns
672 -------
673 out : ndarray
674 Discrete cross-correlation of `a` and `v`.
676 See Also
677 --------
678 convolve : Discrete, linear convolution of two one-dimensional sequences.
679 multiarray.correlate : Old, no conjugate, version of correlate.
681 Notes
682 -----
683 The definition of correlation above is not unique and sometimes correlation
684 may be defined differently. Another common definition is::
686 c'_{av}[k] = sum_n a[n] conj(v[n+k])
688 which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``.
690 Examples
691 --------
692 >>> np.correlate([1, 2, 3], [0, 1, 0.5])
693 array([3.5])
694 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
695 array([2. , 3.5, 3. ])
696 >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
697 array([0.5, 2. , 3.5, 3. , 0. ])
699 Using complex sequences:
701 >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
702 array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
704 Note that you get the time reversed, complex conjugated result
705 when the two input sequences change places, i.e.,
706 ``c_{va}[k] = c^{*}_{av}[-k]``:
708 >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
709 array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
711 """
712 mode = _mode_from_name(mode)
713 return multiarray.correlate2(a, v, mode)
716def _convolve_dispatcher(a, v, mode=None):
717 return (a, v)
720@array_function_dispatch(_convolve_dispatcher)
721def convolve(a, v, mode='full'):
722 """
723 Returns the discrete, linear convolution of two one-dimensional sequences.
725 The convolution operator is often seen in signal processing, where it
726 models the effect of a linear time-invariant system on a signal [1]_. In
727 probability theory, the sum of two independent random variables is
728 distributed according to the convolution of their individual
729 distributions.
731 If `v` is longer than `a`, the arrays are swapped before computation.
733 Parameters
734 ----------
735 a : (N,) array_like
736 First one-dimensional input array.
737 v : (M,) array_like
738 Second one-dimensional input array.
739 mode : {'full', 'valid', 'same'}, optional
740 'full':
741 By default, mode is 'full'. This returns the convolution
742 at each point of overlap, with an output shape of (N+M-1,). At
743 the end-points of the convolution, the signals do not overlap
744 completely, and boundary effects may be seen.
746 'same':
747 Mode 'same' returns output of length ``max(M, N)``. Boundary
748 effects are still visible.
750 'valid':
751 Mode 'valid' returns output of length
752 ``max(M, N) - min(M, N) + 1``. The convolution product is only given
753 for points where the signals overlap completely. Values outside
754 the signal boundary have no effect.
756 Returns
757 -------
758 out : ndarray
759 Discrete, linear convolution of `a` and `v`.
761 See Also
762 --------
763 scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
764 Transform.
765 scipy.linalg.toeplitz : Used to construct the convolution operator.
766 polymul : Polynomial multiplication. Same output as convolve, but also
767 accepts poly1d objects as input.
769 Notes
770 -----
771 The discrete convolution operation is defined as
773 .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m]
775 It can be shown that a convolution :math:`x(t) * y(t)` in time/space
776 is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
777 domain, after appropriate padding (padding is necessary to prevent
778 circular convolution). Since multiplication is more efficient (faster)
779 than convolution, the function `scipy.signal.fftconvolve` exploits the
780 FFT to calculate the convolution of large data-sets.
782 References
783 ----------
784 .. [1] Wikipedia, "Convolution",
785 https://en.wikipedia.org/wiki/Convolution
787 Examples
788 --------
789 Note how the convolution operator flips the second array
790 before "sliding" the two across one another:
792 >>> np.convolve([1, 2, 3], [0, 1, 0.5])
793 array([0. , 1. , 2.5, 4. , 1.5])
795 Only return the middle values of the convolution.
796 Contains boundary effects, where zeros are taken
797 into account:
799 >>> np.convolve([1,2,3],[0,1,0.5], 'same')
800 array([1. , 2.5, 4. ])
802 The two arrays are of the same length, so there
803 is only one position where they completely overlap:
805 >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
806 array([2.5])
808 """
809 a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
810 if (len(v) > len(a)):
811 a, v = v, a
812 if len(a) == 0:
813 raise ValueError('a cannot be empty')
814 if len(v) == 0:
815 raise ValueError('v cannot be empty')
816 mode = _mode_from_name(mode)
817 return multiarray.correlate(a, v[::-1], mode)
820def _outer_dispatcher(a, b, out=None):
821 return (a, b, out)
824@array_function_dispatch(_outer_dispatcher)
825def outer(a, b, out=None):
826 """
827 Compute the outer product of two vectors.
829 Given two vectors, ``a = [a0, a1, ..., aM]`` and
830 ``b = [b0, b1, ..., bN]``,
831 the outer product [1]_ is::
833 [[a0*b0 a0*b1 ... a0*bN ]
834 [a1*b0 .
835 [ ... .
836 [aM*b0 aM*bN ]]
838 Parameters
839 ----------
840 a : (M,) array_like
841 First input vector. Input is flattened if
842 not already 1-dimensional.
843 b : (N,) array_like
844 Second input vector. Input is flattened if
845 not already 1-dimensional.
846 out : (M, N) ndarray, optional
847 A location where the result is stored
849 .. versionadded:: 1.9.0
851 Returns
852 -------
853 out : (M, N) ndarray
854 ``out[i, j] = a[i] * b[j]``
856 See also
857 --------
858 inner
859 einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
860 ufunc.outer : A generalization to dimensions other than 1D and other
861 operations. ``np.multiply.outer(a.ravel(), b.ravel())``
862 is the equivalent.
863 tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
864 is the equivalent.
866 References
867 ----------
868 .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
869 ed., Baltimore, MD, Johns Hopkins University Press, 1996,
870 pg. 8.
872 Examples
873 --------
874 Make a (*very* coarse) grid for computing a Mandelbrot set:
876 >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
877 >>> rl
878 array([[-2., -1., 0., 1., 2.],
879 [-2., -1., 0., 1., 2.],
880 [-2., -1., 0., 1., 2.],
881 [-2., -1., 0., 1., 2.],
882 [-2., -1., 0., 1., 2.]])
883 >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
884 >>> im
885 array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
886 [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
887 [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
888 [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
889 [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
890 >>> grid = rl + im
891 >>> grid
892 array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
893 [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
894 [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
895 [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
896 [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
898 An example using a "vector" of letters:
900 >>> x = np.array(['a', 'b', 'c'], dtype=object)
901 >>> np.outer(x, [1, 2, 3])
902 array([['a', 'aa', 'aaa'],
903 ['b', 'bb', 'bbb'],
904 ['c', 'cc', 'ccc']], dtype=object)
906 """
907 a = asarray(a)
908 b = asarray(b)
909 return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
912def _tensordot_dispatcher(a, b, axes=None):
913 return (a, b)
916@array_function_dispatch(_tensordot_dispatcher)
917def tensordot(a, b, axes=2):
918 """
919 Compute tensor dot product along specified axes.
921 Given two tensors, `a` and `b`, and an array_like object containing
922 two array_like objects, ``(a_axes, b_axes)``, sum the products of
923 `a`'s and `b`'s elements (components) over the axes specified by
924 ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
925 integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
926 of `a` and the first ``N`` dimensions of `b` are summed over.
928 Parameters
929 ----------
930 a, b : array_like
931 Tensors to "dot".
933 axes : int or (2,) array_like
934 * integer_like
935 If an int N, sum over the last N axes of `a` and the first N axes
936 of `b` in order. The sizes of the corresponding axes must match.
937 * (2,) array_like
938 Or, a list of axes to be summed over, first sequence applying to `a`,
939 second to `b`. Both elements array_like must be of the same length.
941 Returns
942 -------
943 output : ndarray
944 The tensor dot product of the input.
946 See Also
947 --------
948 dot, einsum
950 Notes
951 -----
952 Three common use cases are:
953 * ``axes = 0`` : tensor product :math:`a\\otimes b`
954 * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
955 * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
957 When `axes` is integer_like, the sequence for evaluation will be: first
958 the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
959 Nth axis in `b` last.
961 When there is more than one axis to sum over - and they are not the last
962 (first) axes of `a` (`b`) - the argument `axes` should consist of
963 two sequences of the same length, with the first axis to sum over given
964 first in both sequences, the second axis second, and so forth.
966 The shape of the result consists of the non-contracted axes of the
967 first tensor, followed by the non-contracted axes of the second.
969 Examples
970 --------
971 A "traditional" example:
973 >>> a = np.arange(60.).reshape(3,4,5)
974 >>> b = np.arange(24.).reshape(4,3,2)
975 >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
976 >>> c.shape
977 (5, 2)
978 >>> c
979 array([[4400., 4730.],
980 [4532., 4874.],
981 [4664., 5018.],
982 [4796., 5162.],
983 [4928., 5306.]])
984 >>> # A slower but equivalent way of computing the same...
985 >>> d = np.zeros((5,2))
986 >>> for i in range(5):
987 ... for j in range(2):
988 ... for k in range(3):
989 ... for n in range(4):
990 ... d[i,j] += a[k,n,i] * b[n,k,j]
991 >>> c == d
992 array([[ True, True],
993 [ True, True],
994 [ True, True],
995 [ True, True],
996 [ True, True]])
998 An extended example taking advantage of the overloading of + and \\*:
1000 >>> a = np.array(range(1, 9))
1001 >>> a.shape = (2, 2, 2)
1002 >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
1003 >>> A.shape = (2, 2)
1004 >>> a; A
1005 array([[[1, 2],
1006 [3, 4]],
1007 [[5, 6],
1008 [7, 8]]])
1009 array([['a', 'b'],
1010 ['c', 'd']], dtype=object)
1012 >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
1013 array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
1015 >>> np.tensordot(a, A, 1)
1016 array([[['acc', 'bdd'],
1017 ['aaacccc', 'bbbdddd']],
1018 [['aaaaacccccc', 'bbbbbdddddd'],
1019 ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
1021 >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
1022 array([[[[['a', 'b'],
1023 ['c', 'd']],
1024 ...
1026 >>> np.tensordot(a, A, (0, 1))
1027 array([[['abbbbb', 'cddddd'],
1028 ['aabbbbbb', 'ccdddddd']],
1029 [['aaabbbbbbb', 'cccddddddd'],
1030 ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
1032 >>> np.tensordot(a, A, (2, 1))
1033 array([[['abb', 'cdd'],
1034 ['aaabbbb', 'cccdddd']],
1035 [['aaaaabbbbbb', 'cccccdddddd'],
1036 ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
1038 >>> np.tensordot(a, A, ((0, 1), (0, 1)))
1039 array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
1041 >>> np.tensordot(a, A, ((2, 1), (1, 0)))
1042 array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
1044 """
1045 try:
1046 iter(axes)
1047 except Exception:
1048 axes_a = list(range(-axes, 0))
1049 axes_b = list(range(0, axes))
1050 else:
1051 axes_a, axes_b = axes
1052 try:
1053 na = len(axes_a)
1054 axes_a = list(axes_a)
1055 except TypeError:
1056 axes_a = [axes_a]
1057 na = 1
1058 try:
1059 nb = len(axes_b)
1060 axes_b = list(axes_b)
1061 except TypeError:
1062 axes_b = [axes_b]
1063 nb = 1
1065 a, b = asarray(a), asarray(b)
1066 as_ = a.shape
1067 nda = a.ndim
1068 bs = b.shape
1069 ndb = b.ndim
1070 equal = True
1071 if na != nb:
1072 equal = False
1073 else:
1074 for k in range(na):
1075 if as_[axes_a[k]] != bs[axes_b[k]]:
1076 equal = False
1077 break
1078 if axes_a[k] < 0:
1079 axes_a[k] += nda
1080 if axes_b[k] < 0:
1081 axes_b[k] += ndb
1082 if not equal:
1083 raise ValueError("shape-mismatch for sum")
1085 # Move the axes to sum over to the end of "a"
1086 # and to the front of "b"
1087 notin = [k for k in range(nda) if k not in axes_a]
1088 newaxes_a = notin + axes_a
1089 N2 = 1
1090 for axis in axes_a:
1091 N2 *= as_[axis]
1092 newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
1093 olda = [as_[axis] for axis in notin]
1095 notin = [k for k in range(ndb) if k not in axes_b]
1096 newaxes_b = axes_b + notin
1097 N2 = 1
1098 for axis in axes_b:
1099 N2 *= bs[axis]
1100 newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
1101 oldb = [bs[axis] for axis in notin]
1103 at = a.transpose(newaxes_a).reshape(newshape_a)
1104 bt = b.transpose(newaxes_b).reshape(newshape_b)
1105 res = dot(at, bt)
1106 return res.reshape(olda + oldb)
1109def _roll_dispatcher(a, shift, axis=None):
1110 return (a,)
1113@array_function_dispatch(_roll_dispatcher)
1114def roll(a, shift, axis=None):
1115 """
1116 Roll array elements along a given axis.
1118 Elements that roll beyond the last position are re-introduced at
1119 the first.
1121 Parameters
1122 ----------
1123 a : array_like
1124 Input array.
1125 shift : int or tuple of ints
1126 The number of places by which elements are shifted. If a tuple,
1127 then `axis` must be a tuple of the same size, and each of the
1128 given axes is shifted by the corresponding number. If an int
1129 while `axis` is a tuple of ints, then the same value is used for
1130 all given axes.
1131 axis : int or tuple of ints, optional
1132 Axis or axes along which elements are shifted. By default, the
1133 array is flattened before shifting, after which the original
1134 shape is restored.
1136 Returns
1137 -------
1138 res : ndarray
1139 Output array, with the same shape as `a`.
1141 See Also
1142 --------
1143 rollaxis : Roll the specified axis backwards, until it lies in a
1144 given position.
1146 Notes
1147 -----
1148 .. versionadded:: 1.12.0
1150 Supports rolling over multiple dimensions simultaneously.
1152 Examples
1153 --------
1154 >>> x = np.arange(10)
1155 >>> np.roll(x, 2)
1156 array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
1157 >>> np.roll(x, -2)
1158 array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
1160 >>> x2 = np.reshape(x, (2,5))
1161 >>> x2
1162 array([[0, 1, 2, 3, 4],
1163 [5, 6, 7, 8, 9]])
1164 >>> np.roll(x2, 1)
1165 array([[9, 0, 1, 2, 3],
1166 [4, 5, 6, 7, 8]])
1167 >>> np.roll(x2, -1)
1168 array([[1, 2, 3, 4, 5],
1169 [6, 7, 8, 9, 0]])
1170 >>> np.roll(x2, 1, axis=0)
1171 array([[5, 6, 7, 8, 9],
1172 [0, 1, 2, 3, 4]])
1173 >>> np.roll(x2, -1, axis=0)
1174 array([[5, 6, 7, 8, 9],
1175 [0, 1, 2, 3, 4]])
1176 >>> np.roll(x2, 1, axis=1)
1177 array([[4, 0, 1, 2, 3],
1178 [9, 5, 6, 7, 8]])
1179 >>> np.roll(x2, -1, axis=1)
1180 array([[1, 2, 3, 4, 0],
1181 [6, 7, 8, 9, 5]])
1183 """
1184 a = asanyarray(a)
1185 if axis is None:
1186 return roll(a.ravel(), shift, 0).reshape(a.shape)
1188 else:
1189 axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
1190 broadcasted = broadcast(shift, axis)
1191 if broadcasted.ndim > 1:
1192 raise ValueError(
1193 "'shift' and 'axis' should be scalars or 1D sequences")
1194 shifts = {ax: 0 for ax in range(a.ndim)}
1195 for sh, ax in broadcasted:
1196 shifts[ax] += sh
1198 rolls = [((slice(None), slice(None)),)] * a.ndim
1199 for ax, offset in shifts.items():
1200 offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
1201 if offset:
1202 # (original, result), (original, result)
1203 rolls[ax] = ((slice(None, -offset), slice(offset, None)),
1204 (slice(-offset, None), slice(None, offset)))
1206 result = empty_like(a)
1207 for indices in itertools.product(*rolls):
1208 arr_index, res_index = zip(*indices)
1209 result[res_index] = a[arr_index]
1211 return result
1214def _rollaxis_dispatcher(a, axis, start=None):
1215 return (a,)
1218@array_function_dispatch(_rollaxis_dispatcher)
1219def rollaxis(a, axis, start=0):
1220 """
1221 Roll the specified axis backwards, until it lies in a given position.
1223 This function continues to be supported for backward compatibility, but you
1224 should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1225 1.11.
1227 Parameters
1228 ----------
1229 a : ndarray
1230 Input array.
1231 axis : int
1232 The axis to be rolled. The positions of the other axes do not
1233 change relative to one another.
1234 start : int, optional
1235 When ``start <= axis``, the axis is rolled back until it lies in
1236 this position. When ``start > axis``, the axis is rolled until it
1237 lies before this position. The default, 0, results in a "complete"
1238 roll. The following table describes how negative values of ``start``
1239 are interpreted:
1241 .. table::
1242 :align: left
1244 +-------------------+----------------------+
1245 | ``start`` | Normalized ``start`` |
1246 +===================+======================+
1247 | ``-(arr.ndim+1)`` | raise ``AxisError`` |
1248 +-------------------+----------------------+
1249 | ``-arr.ndim`` | 0 |
1250 +-------------------+----------------------+
1251 | |vdots| | |vdots| |
1252 +-------------------+----------------------+
1253 | ``-1`` | ``arr.ndim-1`` |
1254 +-------------------+----------------------+
1255 | ``0`` | ``0`` |
1256 +-------------------+----------------------+
1257 | |vdots| | |vdots| |
1258 +-------------------+----------------------+
1259 | ``arr.ndim`` | ``arr.ndim`` |
1260 +-------------------+----------------------+
1261 | ``arr.ndim + 1`` | raise ``AxisError`` |
1262 +-------------------+----------------------+
1264 .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
1266 Returns
1267 -------
1268 res : ndarray
1269 For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
1270 NumPy versions a view of `a` is returned only if the order of the
1271 axes is changed, otherwise the input array is returned.
1273 See Also
1274 --------
1275 moveaxis : Move array axes to new positions.
1276 roll : Roll the elements of an array by a number of positions along a
1277 given axis.
1279 Examples
1280 --------
1281 >>> a = np.ones((3,4,5,6))
1282 >>> np.rollaxis(a, 3, 1).shape
1283 (3, 6, 4, 5)
1284 >>> np.rollaxis(a, 2).shape
1285 (5, 3, 4, 6)
1286 >>> np.rollaxis(a, 1, 4).shape
1287 (3, 5, 6, 4)
1289 """
1290 n = a.ndim
1291 axis = normalize_axis_index(axis, n)
1292 if start < 0:
1293 start += n
1294 msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
1295 if not (0 <= start < n + 1):
1296 raise AxisError(msg % ('start', -n, 'start', n + 1, start))
1297 if axis < start:
1298 # it's been removed
1299 start -= 1
1300 if axis == start:
1301 return a[...]
1302 axes = list(range(0, n))
1303 axes.remove(axis)
1304 axes.insert(start, axis)
1305 return a.transpose(axes)
1308def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
1309 """
1310 Normalizes an axis argument into a tuple of non-negative integer axes.
1312 This handles shorthands such as ``1`` and converts them to ``(1,)``,
1313 as well as performing the handling of negative indices covered by
1314 `normalize_axis_index`.
1316 By default, this forbids axes from being specified multiple times.
1318 Used internally by multi-axis-checking logic.
1320 .. versionadded:: 1.13.0
1322 Parameters
1323 ----------
1324 axis : int, iterable of int
1325 The un-normalized index or indices of the axis.
1326 ndim : int
1327 The number of dimensions of the array that `axis` should be normalized
1328 against.
1329 argname : str, optional
1330 A prefix to put before the error message, typically the name of the
1331 argument.
1332 allow_duplicate : bool, optional
1333 If False, the default, disallow an axis from being specified twice.
1335 Returns
1336 -------
1337 normalized_axes : tuple of int
1338 The normalized axis index, such that `0 <= normalized_axis < ndim`
1340 Raises
1341 ------
1342 AxisError
1343 If any axis provided is out of range
1344 ValueError
1345 If an axis is repeated
1347 See also
1348 --------
1349 normalize_axis_index : normalizing a single scalar axis
1350 """
1351 # Optimization to speed-up the most common cases.
1352 if type(axis) not in (tuple, list):
1353 try:
1354 axis = [operator.index(axis)]
1355 except TypeError:
1356 pass
1357 # Going via an iterator directly is slower than via list comprehension.
1358 axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
1359 if not allow_duplicate and len(set(axis)) != len(axis):
1360 if argname:
1361 raise ValueError('repeated axis in `{}` argument'.format(argname))
1362 else:
1363 raise ValueError('repeated axis')
1364 return axis
1367def _moveaxis_dispatcher(a, source, destination):
1368 return (a,)
1371@array_function_dispatch(_moveaxis_dispatcher)
1372def moveaxis(a, source, destination):
1373 """
1374 Move axes of an array to new positions.
1376 Other axes remain in their original order.
1378 .. versionadded:: 1.11.0
1380 Parameters
1381 ----------
1382 a : np.ndarray
1383 The array whose axes should be reordered.
1384 source : int or sequence of int
1385 Original positions of the axes to move. These must be unique.
1386 destination : int or sequence of int
1387 Destination positions for each of the original axes. These must also be
1388 unique.
1390 Returns
1391 -------
1392 result : np.ndarray
1393 Array with moved axes. This array is a view of the input array.
1395 See Also
1396 --------
1397 transpose: Permute the dimensions of an array.
1398 swapaxes: Interchange two axes of an array.
1400 Examples
1401 --------
1403 >>> x = np.zeros((3, 4, 5))
1404 >>> np.moveaxis(x, 0, -1).shape
1405 (4, 5, 3)
1406 >>> np.moveaxis(x, -1, 0).shape
1407 (5, 3, 4)
1409 These all achieve the same result:
1411 >>> np.transpose(x).shape
1412 (5, 4, 3)
1413 >>> np.swapaxes(x, 0, -1).shape
1414 (5, 4, 3)
1415 >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
1416 (5, 4, 3)
1417 >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
1418 (5, 4, 3)
1420 """
1421 try:
1422 # allow duck-array types if they define transpose
1423 transpose = a.transpose
1424 except AttributeError:
1425 a = asarray(a)
1426 transpose = a.transpose
1428 source = normalize_axis_tuple(source, a.ndim, 'source')
1429 destination = normalize_axis_tuple(destination, a.ndim, 'destination')
1430 if len(source) != len(destination):
1431 raise ValueError('`source` and `destination` arguments must have '
1432 'the same number of elements')
1434 order = [n for n in range(a.ndim) if n not in source]
1436 for dest, src in sorted(zip(destination, source)):
1437 order.insert(dest, src)
1439 result = transpose(order)
1440 return result
1443# fix hack in scipy which imports this function
1444def _move_axis_to_0(a, axis):
1445 return moveaxis(a, axis, 0)
1448def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
1449 return (a, b)
1452@array_function_dispatch(_cross_dispatcher)
1453def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
1454 """
1455 Return the cross product of two (arrays of) vectors.
1457 The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
1458 to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
1459 are defined by the last axis of `a` and `b` by default, and these axes
1460 can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
1461 2, the third component of the input vector is assumed to be zero and the
1462 cross product calculated accordingly. In cases where both input vectors
1463 have dimension 2, the z-component of the cross product is returned.
1465 Parameters
1466 ----------
1467 a : array_like
1468 Components of the first vector(s).
1469 b : array_like
1470 Components of the second vector(s).
1471 axisa : int, optional
1472 Axis of `a` that defines the vector(s). By default, the last axis.
1473 axisb : int, optional
1474 Axis of `b` that defines the vector(s). By default, the last axis.
1475 axisc : int, optional
1476 Axis of `c` containing the cross product vector(s). Ignored if
1477 both input vectors have dimension 2, as the return is scalar.
1478 By default, the last axis.
1479 axis : int, optional
1480 If defined, the axis of `a`, `b` and `c` that defines the vector(s)
1481 and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
1483 Returns
1484 -------
1485 c : ndarray
1486 Vector cross product(s).
1488 Raises
1489 ------
1490 ValueError
1491 When the dimension of the vector(s) in `a` and/or `b` does not
1492 equal 2 or 3.
1494 See Also
1495 --------
1496 inner : Inner product
1497 outer : Outer product.
1498 ix_ : Construct index arrays.
1500 Notes
1501 -----
1502 .. versionadded:: 1.9.0
1504 Supports full broadcasting of the inputs.
1506 Examples
1507 --------
1508 Vector cross-product.
1510 >>> x = [1, 2, 3]
1511 >>> y = [4, 5, 6]
1512 >>> np.cross(x, y)
1513 array([-3, 6, -3])
1515 One vector with dimension 2.
1517 >>> x = [1, 2]
1518 >>> y = [4, 5, 6]
1519 >>> np.cross(x, y)
1520 array([12, -6, -3])
1522 Equivalently:
1524 >>> x = [1, 2, 0]
1525 >>> y = [4, 5, 6]
1526 >>> np.cross(x, y)
1527 array([12, -6, -3])
1529 Both vectors with dimension 2.
1531 >>> x = [1,2]
1532 >>> y = [4,5]
1533 >>> np.cross(x, y)
1534 array(-3)
1536 Multiple vector cross-products. Note that the direction of the cross
1537 product vector is defined by the `right-hand rule`.
1539 >>> x = np.array([[1,2,3], [4,5,6]])
1540 >>> y = np.array([[4,5,6], [1,2,3]])
1541 >>> np.cross(x, y)
1542 array([[-3, 6, -3],
1543 [ 3, -6, 3]])
1545 The orientation of `c` can be changed using the `axisc` keyword.
1547 >>> np.cross(x, y, axisc=0)
1548 array([[-3, 3],
1549 [ 6, -6],
1550 [-3, 3]])
1552 Change the vector definition of `x` and `y` using `axisa` and `axisb`.
1554 >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
1555 >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
1556 >>> np.cross(x, y)
1557 array([[ -6, 12, -6],
1558 [ 0, 0, 0],
1559 [ 6, -12, 6]])
1560 >>> np.cross(x, y, axisa=0, axisb=0)
1561 array([[-24, 48, -24],
1562 [-30, 60, -30],
1563 [-36, 72, -36]])
1565 """
1566 if axis is not None:
1567 axisa, axisb, axisc = (axis,) * 3
1568 a = asarray(a)
1569 b = asarray(b)
1570 # Check axisa and axisb are within bounds
1571 axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
1572 axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
1574 # Move working axis to the end of the shape
1575 a = moveaxis(a, axisa, -1)
1576 b = moveaxis(b, axisb, -1)
1577 msg = ("incompatible dimensions for cross product\n"
1578 "(dimension must be 2 or 3)")
1579 if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
1580 raise ValueError(msg)
1582 # Create the output array
1583 shape = broadcast(a[..., 0], b[..., 0]).shape
1584 if a.shape[-1] == 3 or b.shape[-1] == 3:
1585 shape += (3,)
1586 # Check axisc is within bounds
1587 axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
1588 dtype = promote_types(a.dtype, b.dtype)
1589 cp = empty(shape, dtype)
1591 # create local aliases for readability
1592 a0 = a[..., 0]
1593 a1 = a[..., 1]
1594 if a.shape[-1] == 3:
1595 a2 = a[..., 2]
1596 b0 = b[..., 0]
1597 b1 = b[..., 1]
1598 if b.shape[-1] == 3:
1599 b2 = b[..., 2]
1600 if cp.ndim != 0 and cp.shape[-1] == 3:
1601 cp0 = cp[..., 0]
1602 cp1 = cp[..., 1]
1603 cp2 = cp[..., 2]
1605 if a.shape[-1] == 2:
1606 if b.shape[-1] == 2:
1607 # a0 * b1 - a1 * b0
1608 multiply(a0, b1, out=cp)
1609 cp -= a1 * b0
1610 return cp
1611 else:
1612 assert b.shape[-1] == 3
1613 # cp0 = a1 * b2 - 0 (a2 = 0)
1614 # cp1 = 0 - a0 * b2 (a2 = 0)
1615 # cp2 = a0 * b1 - a1 * b0
1616 multiply(a1, b2, out=cp0)
1617 multiply(a0, b2, out=cp1)
1618 negative(cp1, out=cp1)
1619 multiply(a0, b1, out=cp2)
1620 cp2 -= a1 * b0
1621 else:
1622 assert a.shape[-1] == 3
1623 if b.shape[-1] == 3:
1624 # cp0 = a1 * b2 - a2 * b1
1625 # cp1 = a2 * b0 - a0 * b2
1626 # cp2 = a0 * b1 - a1 * b0
1627 multiply(a1, b2, out=cp0)
1628 tmp = array(a2 * b1)
1629 cp0 -= tmp
1630 multiply(a2, b0, out=cp1)
1631 multiply(a0, b2, out=tmp)
1632 cp1 -= tmp
1633 multiply(a0, b1, out=cp2)
1634 multiply(a1, b0, out=tmp)
1635 cp2 -= tmp
1636 else:
1637 assert b.shape[-1] == 2
1638 # cp0 = 0 - a2 * b1 (b2 = 0)
1639 # cp1 = a2 * b0 - 0 (b2 = 0)
1640 # cp2 = a0 * b1 - a1 * b0
1641 multiply(a2, b1, out=cp0)
1642 negative(cp0, out=cp0)
1643 multiply(a2, b0, out=cp1)
1644 multiply(a0, b1, out=cp2)
1645 cp2 -= a1 * b0
1647 return moveaxis(cp, -1, axisc)
1650little_endian = (sys.byteorder == 'little')
1653@set_module('numpy')
1654def indices(dimensions, dtype=int, sparse=False):
1655 """
1656 Return an array representing the indices of a grid.
1658 Compute an array where the subarrays contain index values 0, 1, ...
1659 varying only along the corresponding axis.
1661 Parameters
1662 ----------
1663 dimensions : sequence of ints
1664 The shape of the grid.
1665 dtype : dtype, optional
1666 Data type of the result.
1667 sparse : boolean, optional
1668 Return a sparse representation of the grid instead of a dense
1669 representation. Default is False.
1671 .. versionadded:: 1.17
1673 Returns
1674 -------
1675 grid : one ndarray or tuple of ndarrays
1676 If sparse is False:
1677 Returns one array of grid indices,
1678 ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1679 If sparse is True:
1680 Returns a tuple of arrays, with
1681 ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1682 dimensions[i] in the ith place
1684 See Also
1685 --------
1686 mgrid, ogrid, meshgrid
1688 Notes
1689 -----
1690 The output shape in the dense case is obtained by prepending the number
1691 of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
1692 is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
1693 ``(N, r0, ..., rN-1)``.
1695 The subarrays ``grid[k]`` contains the N-D array of indices along the
1696 ``k-th`` axis. Explicitly::
1698 grid[k, i0, i1, ..., iN-1] = ik
1700 Examples
1701 --------
1702 >>> grid = np.indices((2, 3))
1703 >>> grid.shape
1704 (2, 2, 3)
1705 >>> grid[0] # row indices
1706 array([[0, 0, 0],
1707 [1, 1, 1]])
1708 >>> grid[1] # column indices
1709 array([[0, 1, 2],
1710 [0, 1, 2]])
1712 The indices can be used as an index into an array.
1714 >>> x = np.arange(20).reshape(5, 4)
1715 >>> row, col = np.indices((2, 3))
1716 >>> x[row, col]
1717 array([[0, 1, 2],
1718 [4, 5, 6]])
1720 Note that it would be more straightforward in the above example to
1721 extract the required elements directly with ``x[:2, :3]``.
1723 If sparse is set to true, the grid will be returned in a sparse
1724 representation.
1726 >>> i, j = np.indices((2, 3), sparse=True)
1727 >>> i.shape
1728 (2, 1)
1729 >>> j.shape
1730 (1, 3)
1731 >>> i # row indices
1732 array([[0],
1733 [1]])
1734 >>> j # column indices
1735 array([[0, 1, 2]])
1737 """
1738 dimensions = tuple(dimensions)
1739 N = len(dimensions)
1740 shape = (1,)*N
1741 if sparse:
1742 res = tuple()
1743 else:
1744 res = empty((N,)+dimensions, dtype=dtype)
1745 for i, dim in enumerate(dimensions):
1746 idx = arange(dim, dtype=dtype).reshape(
1747 shape[:i] + (dim,) + shape[i+1:]
1748 )
1749 if sparse:
1750 res = res + (idx,)
1751 else:
1752 res[i] = idx
1753 return res
1756@set_module('numpy')
1757def fromfunction(function, shape, *, dtype=float, **kwargs):
1758 """
1759 Construct an array by executing a function over each coordinate.
1761 The resulting array therefore has a value ``fn(x, y, z)`` at
1762 coordinate ``(x, y, z)``.
1764 Parameters
1765 ----------
1766 function : callable
1767 The function is called with N parameters, where N is the rank of
1768 `shape`. Each parameter represents the coordinates of the array
1769 varying along a specific axis. For example, if `shape`
1770 were ``(2, 2)``, then the parameters would be
1771 ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
1772 shape : (N,) tuple of ints
1773 Shape of the output array, which also determines the shape of
1774 the coordinate arrays passed to `function`.
1775 dtype : data-type, optional
1776 Data-type of the coordinate arrays passed to `function`.
1777 By default, `dtype` is float.
1779 Returns
1780 -------
1781 fromfunction : any
1782 The result of the call to `function` is passed back directly.
1783 Therefore the shape of `fromfunction` is completely determined by
1784 `function`. If `function` returns a scalar value, the shape of
1785 `fromfunction` would not match the `shape` parameter.
1787 See Also
1788 --------
1789 indices, meshgrid
1791 Notes
1792 -----
1793 Keywords other than `dtype` are passed to `function`.
1795 Examples
1796 --------
1797 >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
1798 array([[ True, False, False],
1799 [False, True, False],
1800 [False, False, True]])
1802 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
1803 array([[0, 1, 2],
1804 [1, 2, 3],
1805 [2, 3, 4]])
1807 """
1808 args = indices(shape, dtype=dtype)
1809 return function(*args, **kwargs)
1812def _frombuffer(buf, dtype, shape, order):
1813 return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
1816@set_module('numpy')
1817def isscalar(element):
1818 """
1819 Returns True if the type of `element` is a scalar type.
1821 Parameters
1822 ----------
1823 element : any
1824 Input argument, can be of any type and shape.
1826 Returns
1827 -------
1828 val : bool
1829 True if `element` is a scalar type, False if it is not.
1831 See Also
1832 --------
1833 ndim : Get the number of dimensions of an array
1835 Notes
1836 -----
1837 If you need a stricter way to identify a *numerical* scalar, use
1838 ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
1839 non-numerical elements such as strings.
1841 In most cases ``np.ndim(x) == 0`` should be used instead of this function,
1842 as that will also return true for 0d arrays. This is how numpy overloads
1843 functions in the style of the ``dx`` arguments to `gradient` and the ``bins``
1844 argument to `histogram`. Some key differences:
1846 +--------------------------------------+---------------+-------------------+
1847 | x |``isscalar(x)``|``np.ndim(x) == 0``|
1848 +======================================+===============+===================+
1849 | PEP 3141 numeric objects (including | ``True`` | ``True`` |
1850 | builtins) | | |
1851 +--------------------------------------+---------------+-------------------+
1852 | builtin string and buffer objects | ``True`` | ``True`` |
1853 +--------------------------------------+---------------+-------------------+
1854 | other builtin objects, like | ``False`` | ``True`` |
1855 | `pathlib.Path`, `Exception`, | | |
1856 | the result of `re.compile` | | |
1857 +--------------------------------------+---------------+-------------------+
1858 | third-party objects like | ``False`` | ``True`` |
1859 | `matplotlib.figure.Figure` | | |
1860 +--------------------------------------+---------------+-------------------+
1861 | zero-dimensional numpy arrays | ``False`` | ``True`` |
1862 +--------------------------------------+---------------+-------------------+
1863 | other numpy arrays | ``False`` | ``False`` |
1864 +--------------------------------------+---------------+-------------------+
1865 | `list`, `tuple`, and other sequence | ``False`` | ``False`` |
1866 | objects | | |
1867 +--------------------------------------+---------------+-------------------+
1869 Examples
1870 --------
1871 >>> np.isscalar(3.1)
1872 True
1873 >>> np.isscalar(np.array(3.1))
1874 False
1875 >>> np.isscalar([3.1])
1876 False
1877 >>> np.isscalar(False)
1878 True
1879 >>> np.isscalar('numpy')
1880 True
1882 NumPy supports PEP 3141 numbers:
1884 >>> from fractions import Fraction
1885 >>> np.isscalar(Fraction(5, 17))
1886 True
1887 >>> from numbers import Number
1888 >>> np.isscalar(Number())
1889 True
1891 """
1892 return (isinstance(element, generic)
1893 or type(element) in ScalarType
1894 or isinstance(element, numbers.Number))
1897@set_module('numpy')
1898def binary_repr(num, width=None):
1899 """
1900 Return the binary representation of the input number as a string.
1902 For negative numbers, if width is not given, a minus sign is added to the
1903 front. If width is given, the two's complement of the number is
1904 returned, with respect to that width.
1906 In a two's-complement system negative numbers are represented by the two's
1907 complement of the absolute value. This is the most common method of
1908 representing signed integers on computers [1]_. A N-bit two's-complement
1909 system can represent every integer in the range
1910 :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
1912 Parameters
1913 ----------
1914 num : int
1915 Only an integer decimal number can be used.
1916 width : int, optional
1917 The length of the returned string if `num` is positive, or the length
1918 of the two's complement if `num` is negative, provided that `width` is
1919 at least a sufficient number of bits for `num` to be represented in the
1920 designated form.
1922 If the `width` value is insufficient, it will be ignored, and `num` will
1923 be returned in binary (`num` > 0) or two's complement (`num` < 0) form
1924 with its width equal to the minimum number of bits needed to represent
1925 the number in the designated form. This behavior is deprecated and will
1926 later raise an error.
1928 .. deprecated:: 1.12.0
1930 Returns
1931 -------
1932 bin : str
1933 Binary representation of `num` or two's complement of `num`.
1935 See Also
1936 --------
1937 base_repr: Return a string representation of a number in the given base
1938 system.
1939 bin: Python's built-in binary representation generator of an integer.
1941 Notes
1942 -----
1943 `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
1944 faster.
1946 References
1947 ----------
1948 .. [1] Wikipedia, "Two's complement",
1949 https://en.wikipedia.org/wiki/Two's_complement
1951 Examples
1952 --------
1953 >>> np.binary_repr(3)
1954 '11'
1955 >>> np.binary_repr(-3)
1956 '-11'
1957 >>> np.binary_repr(3, width=4)
1958 '0011'
1960 The two's complement is returned when the input number is negative and
1961 width is specified:
1963 >>> np.binary_repr(-3, width=3)
1964 '101'
1965 >>> np.binary_repr(-3, width=5)
1966 '11101'
1968 """
1969 def warn_if_insufficient(width, binwidth):
1970 if width is not None and width < binwidth:
1971 warnings.warn(
1972 "Insufficient bit width provided. This behavior "
1973 "will raise an error in the future.", DeprecationWarning,
1974 stacklevel=3)
1976 # Ensure that num is a Python integer to avoid overflow or unwanted
1977 # casts to floating point.
1978 num = operator.index(num)
1980 if num == 0:
1981 return '0' * (width or 1)
1983 elif num > 0:
1984 binary = bin(num)[2:]
1985 binwidth = len(binary)
1986 outwidth = (binwidth if width is None
1987 else max(binwidth, width))
1988 warn_if_insufficient(width, binwidth)
1989 return binary.zfill(outwidth)
1991 else:
1992 if width is None:
1993 return '-' + bin(-num)[2:]
1995 else:
1996 poswidth = len(bin(-num)[2:])
1998 # See gh-8679: remove extra digit
1999 # for numbers at boundaries.
2000 if 2**(poswidth - 1) == -num:
2001 poswidth -= 1
2003 twocomp = 2**(poswidth + 1) + num
2004 binary = bin(twocomp)[2:]
2005 binwidth = len(binary)
2007 outwidth = max(binwidth, width)
2008 warn_if_insufficient(width, binwidth)
2009 return '1' * (outwidth - binwidth) + binary
2012@set_module('numpy')
2013def base_repr(number, base=2, padding=0):
2014 """
2015 Return a string representation of a number in the given base system.
2017 Parameters
2018 ----------
2019 number : int
2020 The value to convert. Positive and negative values are handled.
2021 base : int, optional
2022 Convert `number` to the `base` number system. The valid range is 2-36,
2023 the default value is 2.
2024 padding : int, optional
2025 Number of zeros padded on the left. Default is 0 (no padding).
2027 Returns
2028 -------
2029 out : str
2030 String representation of `number` in `base` system.
2032 See Also
2033 --------
2034 binary_repr : Faster version of `base_repr` for base 2.
2036 Examples
2037 --------
2038 >>> np.base_repr(5)
2039 '101'
2040 >>> np.base_repr(6, 5)
2041 '11'
2042 >>> np.base_repr(7, base=5, padding=3)
2043 '00012'
2045 >>> np.base_repr(10, base=16)
2046 'A'
2047 >>> np.base_repr(32, base=16)
2048 '20'
2050 """
2051 digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2052 if base > len(digits):
2053 raise ValueError("Bases greater than 36 not handled in base_repr.")
2054 elif base < 2:
2055 raise ValueError("Bases less than 2 not handled in base_repr.")
2057 num = abs(number)
2058 res = []
2059 while num:
2060 res.append(digits[num % base])
2061 num //= base
2062 if padding:
2063 res.append('0' * padding)
2064 if number < 0:
2065 res.append('-')
2066 return ''.join(reversed(res or '0'))
2069# These are all essentially abbreviations
2070# These might wind up in a special abbreviations module
2073def _maketup(descr, val):
2074 dt = dtype(descr)
2075 # Place val in all scalar tuples:
2076 fields = dt.fields
2077 if fields is None:
2078 return val
2079 else:
2080 res = [_maketup(fields[name][0], val) for name in dt.names]
2081 return tuple(res)
2084@set_module('numpy')
2085def identity(n, dtype=None):
2086 """
2087 Return the identity array.
2089 The identity array is a square array with ones on
2090 the main diagonal.
2092 Parameters
2093 ----------
2094 n : int
2095 Number of rows (and columns) in `n` x `n` output.
2096 dtype : data-type, optional
2097 Data-type of the output. Defaults to ``float``.
2099 Returns
2100 -------
2101 out : ndarray
2102 `n` x `n` array with its main diagonal set to one,
2103 and all other elements 0.
2105 Examples
2106 --------
2107 >>> np.identity(3)
2108 array([[1., 0., 0.],
2109 [0., 1., 0.],
2110 [0., 0., 1.]])
2112 """
2113 from numpy import eye
2114 return eye(n, dtype=dtype)
2117def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2118 return (a, b)
2121@array_function_dispatch(_allclose_dispatcher)
2122def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2123 """
2124 Returns True if two arrays are element-wise equal within a tolerance.
2126 The tolerance values are positive, typically very small numbers. The
2127 relative difference (`rtol` * abs(`b`)) and the absolute difference
2128 `atol` are added together to compare against the absolute difference
2129 between `a` and `b`.
2131 NaNs are treated as equal if they are in the same place and if
2132 ``equal_nan=True``. Infs are treated as equal if they are in the same
2133 place and of the same sign in both arrays.
2135 Parameters
2136 ----------
2137 a, b : array_like
2138 Input arrays to compare.
2139 rtol : float
2140 The relative tolerance parameter (see Notes).
2141 atol : float
2142 The absolute tolerance parameter (see Notes).
2143 equal_nan : bool
2144 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2145 considered equal to NaN's in `b` in the output array.
2147 .. versionadded:: 1.10.0
2149 Returns
2150 -------
2151 allclose : bool
2152 Returns True if the two arrays are equal within the given
2153 tolerance; False otherwise.
2155 See Also
2156 --------
2157 isclose, all, any, equal
2159 Notes
2160 -----
2161 If the following equation is element-wise True, then allclose returns
2162 True.
2164 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2166 The above equation is not symmetric in `a` and `b`, so that
2167 ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
2168 some rare cases.
2170 The comparison of `a` and `b` uses standard broadcasting, which
2171 means that `a` and `b` need not have the same shape in order for
2172 ``allclose(a, b)`` to evaluate to True. The same is true for
2173 `equal` but not `array_equal`.
2175 Examples
2176 --------
2177 >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
2178 False
2179 >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
2180 True
2181 >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
2182 False
2183 >>> np.allclose([1.0, np.nan], [1.0, np.nan])
2184 False
2185 >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2186 True
2188 """
2189 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2190 return bool(res)
2193def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
2194 return (a, b)
2197@array_function_dispatch(_isclose_dispatcher)
2198def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
2199 """
2200 Returns a boolean array where two arrays are element-wise equal within a
2201 tolerance.
2203 The tolerance values are positive, typically very small numbers. The
2204 relative difference (`rtol` * abs(`b`)) and the absolute difference
2205 `atol` are added together to compare against the absolute difference
2206 between `a` and `b`.
2208 .. warning:: The default `atol` is not appropriate for comparing numbers
2209 that are much smaller than one (see Notes).
2211 Parameters
2212 ----------
2213 a, b : array_like
2214 Input arrays to compare.
2215 rtol : float
2216 The relative tolerance parameter (see Notes).
2217 atol : float
2218 The absolute tolerance parameter (see Notes).
2219 equal_nan : bool
2220 Whether to compare NaN's as equal. If True, NaN's in `a` will be
2221 considered equal to NaN's in `b` in the output array.
2223 Returns
2224 -------
2225 y : array_like
2226 Returns a boolean array of where `a` and `b` are equal within the
2227 given tolerance. If both `a` and `b` are scalars, returns a single
2228 boolean value.
2230 See Also
2231 --------
2232 allclose
2234 Notes
2235 -----
2236 .. versionadded:: 1.7.0
2238 For finite values, isclose uses the following equation to test whether
2239 two floating point values are equivalent.
2241 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
2243 Unlike the built-in `math.isclose`, the above equation is not symmetric
2244 in `a` and `b` -- it assumes `b` is the reference value -- so that
2245 `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
2246 the default value of atol is not zero, and is used to determine what
2247 small values should be considered close to zero. The default value is
2248 appropriate for expected values of order unity: if the expected values
2249 are significantly smaller than one, it can result in false positives.
2250 `atol` should be carefully selected for the use case at hand. A zero value
2251 for `atol` will result in `False` if either `a` or `b` is zero.
2253 Examples
2254 --------
2255 >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
2256 array([ True, False])
2257 >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
2258 array([ True, True])
2259 >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
2260 array([False, True])
2261 >>> np.isclose([1.0, np.nan], [1.0, np.nan])
2262 array([ True, False])
2263 >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
2264 array([ True, True])
2265 >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
2266 array([ True, False])
2267 >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
2268 array([False, False])
2269 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
2270 array([ True, True])
2271 >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
2272 array([False, True])
2273 """
2274 def within_tol(x, y, atol, rtol):
2275 with errstate(invalid='ignore'):
2276 return less_equal(abs(x-y), atol + rtol * abs(y))
2278 x = asanyarray(a)
2279 y = asanyarray(b)
2281 # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
2282 # This will cause casting of x later. Also, make sure to allow subclasses
2283 # (e.g., for numpy.ma).
2284 dt = multiarray.result_type(y, 1.)
2285 y = array(y, dtype=dt, copy=False, subok=True)
2287 xfin = isfinite(x)
2288 yfin = isfinite(y)
2289 if all(xfin) and all(yfin):
2290 return within_tol(x, y, atol, rtol)
2291 else:
2292 finite = xfin & yfin
2293 cond = zeros_like(finite, subok=True)
2294 # Because we're using boolean indexing, x & y must be the same shape.
2295 # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
2296 # lib.stride_tricks, though, so we can't import it here.
2297 x = x * ones_like(cond)
2298 y = y * ones_like(cond)
2299 # Avoid subtraction with infinite/nan values...
2300 cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
2301 # Check for equality of infinite values...
2302 cond[~finite] = (x[~finite] == y[~finite])
2303 if equal_nan:
2304 # Make NaN == NaN
2305 both_nan = isnan(x) & isnan(y)
2307 # Needed to treat masked arrays correctly. = True would not work.
2308 cond[both_nan] = both_nan[both_nan]
2310 return cond[()] # Flatten 0d arrays to scalars
2313def _array_equal_dispatcher(a1, a2, equal_nan=None):
2314 return (a1, a2)
2317@array_function_dispatch(_array_equal_dispatcher)
2318def array_equal(a1, a2, equal_nan=False):
2319 """
2320 True if two arrays have the same shape and elements, False otherwise.
2322 Parameters
2323 ----------
2324 a1, a2 : array_like
2325 Input arrays.
2326 equal_nan : bool
2327 Whether to compare NaN's as equal. If the dtype of a1 and a2 is
2328 complex, values will be considered equal if either the real or the
2329 imaginary component of a given value is ``nan``.
2331 .. versionadded:: 1.19.0
2333 Returns
2334 -------
2335 b : bool
2336 Returns True if the arrays are equal.
2338 See Also
2339 --------
2340 allclose: Returns True if two arrays are element-wise equal within a
2341 tolerance.
2342 array_equiv: Returns True if input arrays are shape consistent and all
2343 elements equal.
2345 Examples
2346 --------
2347 >>> np.array_equal([1, 2], [1, 2])
2348 True
2349 >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
2350 True
2351 >>> np.array_equal([1, 2], [1, 2, 3])
2352 False
2353 >>> np.array_equal([1, 2], [1, 4])
2354 False
2355 >>> a = np.array([1, np.nan])
2356 >>> np.array_equal(a, a)
2357 False
2358 >>> np.array_equal(a, a, equal_nan=True)
2359 True
2361 When ``equal_nan`` is True, complex values with nan components are
2362 considered equal if either the real *or* the imaginary components are nan.
2364 >>> a = np.array([1 + 1j])
2365 >>> b = a.copy()
2366 >>> a.real = np.nan
2367 >>> b.imag = np.nan
2368 >>> np.array_equal(a, b, equal_nan=True)
2369 True
2370 """
2371 try:
2372 a1, a2 = asarray(a1), asarray(a2)
2373 except Exception:
2374 return False
2375 if a1.shape != a2.shape:
2376 return False
2377 if not equal_nan:
2378 return bool(asarray(a1 == a2).all())
2379 # Handling NaN values if equal_nan is True
2380 a1nan, a2nan = isnan(a1), isnan(a2)
2381 # NaN's occur at different locations
2382 if not (a1nan == a2nan).all():
2383 return False
2384 # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
2385 return bool(asarray(a1[~a1nan] == a2[~a1nan]).all())
2388def _array_equiv_dispatcher(a1, a2):
2389 return (a1, a2)
2392@array_function_dispatch(_array_equiv_dispatcher)
2393def array_equiv(a1, a2):
2394 """
2395 Returns True if input arrays are shape consistent and all elements equal.
2397 Shape consistent means they are either the same shape, or one input array
2398 can be broadcasted to create the same shape as the other one.
2400 Parameters
2401 ----------
2402 a1, a2 : array_like
2403 Input arrays.
2405 Returns
2406 -------
2407 out : bool
2408 True if equivalent, False otherwise.
2410 Examples
2411 --------
2412 >>> np.array_equiv([1, 2], [1, 2])
2413 True
2414 >>> np.array_equiv([1, 2], [1, 3])
2415 False
2417 Showing the shape equivalence:
2419 >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
2420 True
2421 >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
2422 False
2424 >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
2425 False
2427 """
2428 try:
2429 a1, a2 = asarray(a1), asarray(a2)
2430 except Exception:
2431 return False
2432 try:
2433 multiarray.broadcast(a1, a2)
2434 except Exception:
2435 return False
2437 return bool(asarray(a1 == a2).all())
2440Inf = inf = infty = Infinity = PINF
2441nan = NaN = NAN
2442False_ = bool_(False)
2443True_ = bool_(True)
2446def extend_all(module):
2447 existing = set(__all__)
2448 mall = getattr(module, '__all__')
2449 for a in mall:
2450 if a not in existing:
2451 __all__.append(a)
2454from .umath import *
2455from .numerictypes import *
2456from . import fromnumeric
2457from .fromnumeric import *
2458from . import arrayprint
2459from .arrayprint import *
2460from . import _asarray
2461from ._asarray import *
2462from . import _ufunc_config
2463from ._ufunc_config import *
2464extend_all(fromnumeric)
2465extend_all(umath)
2466extend_all(numerictypes)
2467extend_all(arrayprint)
2468extend_all(_asarray)
2469extend_all(_ufunc_config)