m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2537 lines
75 KiB

6 months ago
  1. import functools
  2. import itertools
  3. import operator
  4. import sys
  5. import warnings
  6. import numbers
  7. import numpy as np
  8. from . import multiarray
  9. from .multiarray import (
  10. _fastCopyAndTranspose as fastCopyAndTranspose, ALLOW_THREADS,
  11. BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE,
  12. WRAP, arange, array, asarray, asanyarray, ascontiguousarray,
  13. asfortranarray, 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)
  20. from . import overrides
  21. from . import umath
  22. from . import shape_base
  23. from .overrides import set_array_function_like_doc, set_module
  24. from .umath import (multiply, invert, sin, PINF, NAN)
  25. from . import numerictypes
  26. from .numerictypes import longlong, intc, int_, float_, complex_, bool_
  27. from ._exceptions import TooHardError, AxisError
  28. from ._ufunc_config import errstate
  29. bitwise_not = invert
  30. ufunc = type(sin)
  31. newaxis = None
  32. array_function_dispatch = functools.partial(
  33. overrides.array_function_dispatch, module='numpy')
  34. __all__ = [
  35. 'newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc',
  36. 'arange', 'array', 'asarray', 'asanyarray', 'ascontiguousarray',
  37. 'asfortranarray', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype',
  38. 'fromstring', 'fromfile', 'frombuffer', 'where',
  39. 'argwhere', 'copyto', 'concatenate', 'fastCopyAndTranspose', 'lexsort',
  40. 'set_numeric_ops', 'can_cast', 'promote_types', 'min_scalar_type',
  41. 'result_type', 'isfortran', 'empty_like', 'zeros_like', 'ones_like',
  42. 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', 'roll',
  43. 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian',
  44. 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction',
  45. 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones',
  46. 'identity', 'allclose', 'compare_chararrays', 'putmask',
  47. 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN',
  48. 'False_', 'True_', 'bitwise_not', 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS',
  49. 'BUFSIZE', 'ALLOW_THREADS', 'ComplexWarning', 'full', 'full_like',
  50. 'matmul', 'shares_memory', 'may_share_memory', 'MAY_SHARE_BOUNDS',
  51. 'MAY_SHARE_EXACT', 'TooHardError', 'AxisError']
  52. @set_module('numpy')
  53. class ComplexWarning(RuntimeWarning):
  54. """
  55. The warning raised when casting a complex dtype to a real dtype.
  56. As implemented, casting a complex number to a real discards its imaginary
  57. part, but this behavior may not be what the user actually wants.
  58. """
  59. pass
  60. def _zeros_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
  61. return (a,)
  62. @array_function_dispatch(_zeros_like_dispatcher)
  63. def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
  64. """
  65. Return an array of zeros with the same shape and type as a given array.
  66. Parameters
  67. ----------
  68. a : array_like
  69. The shape and data-type of `a` define these same attributes of
  70. the returned array.
  71. dtype : data-type, optional
  72. Overrides the data type of the result.
  73. .. versionadded:: 1.6.0
  74. order : {'C', 'F', 'A', or 'K'}, optional
  75. Overrides the memory layout of the result. 'C' means C-order,
  76. 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
  77. 'C' otherwise. 'K' means match the layout of `a` as closely
  78. as possible.
  79. .. versionadded:: 1.6.0
  80. subok : bool, optional.
  81. If True, then the newly created array will use the sub-class
  82. type of `a`, otherwise it will be a base-class array. Defaults
  83. to True.
  84. shape : int or sequence of ints, optional.
  85. Overrides the shape of the result. If order='K' and the number of
  86. dimensions is unchanged, will try to keep order, otherwise,
  87. order='C' is implied.
  88. .. versionadded:: 1.17.0
  89. Returns
  90. -------
  91. out : ndarray
  92. Array of zeros with the same shape and type as `a`.
  93. See Also
  94. --------
  95. empty_like : Return an empty array with shape and type of input.
  96. ones_like : Return an array of ones with shape and type of input.
  97. full_like : Return a new array with shape of input filled with value.
  98. zeros : Return a new array setting values to zero.
  99. Examples
  100. --------
  101. >>> x = np.arange(6)
  102. >>> x = x.reshape((2, 3))
  103. >>> x
  104. array([[0, 1, 2],
  105. [3, 4, 5]])
  106. >>> np.zeros_like(x)
  107. array([[0, 0, 0],
  108. [0, 0, 0]])
  109. >>> y = np.arange(3, dtype=float)
  110. >>> y
  111. array([0., 1., 2.])
  112. >>> np.zeros_like(y)
  113. array([0., 0., 0.])
  114. """
  115. res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
  116. # needed instead of a 0 to get same result as zeros for for string dtypes
  117. z = zeros(1, dtype=res.dtype)
  118. multiarray.copyto(res, z, casting='unsafe')
  119. return res
  120. def _ones_dispatcher(shape, dtype=None, order=None, *, like=None):
  121. return(like,)
  122. @set_array_function_like_doc
  123. @set_module('numpy')
  124. def ones(shape, dtype=None, order='C', *, like=None):
  125. """
  126. Return a new array of given shape and type, filled with ones.
  127. Parameters
  128. ----------
  129. shape : int or sequence of ints
  130. Shape of the new array, e.g., ``(2, 3)`` or ``2``.
  131. dtype : data-type, optional
  132. The desired data-type for the array, e.g., `numpy.int8`. Default is
  133. `numpy.float64`.
  134. order : {'C', 'F'}, optional, default: C
  135. Whether to store multi-dimensional data in row-major
  136. (C-style) or column-major (Fortran-style) order in
  137. memory.
  138. ${ARRAY_FUNCTION_LIKE}
  139. .. versionadded:: 1.20.0
  140. Returns
  141. -------
  142. out : ndarray
  143. Array of ones with the given shape, dtype, and order.
  144. See Also
  145. --------
  146. ones_like : Return an array of ones with shape and type of input.
  147. empty : Return a new uninitialized array.
  148. zeros : Return a new array setting values to zero.
  149. full : Return a new array of given shape filled with value.
  150. Examples
  151. --------
  152. >>> np.ones(5)
  153. array([1., 1., 1., 1., 1.])
  154. >>> np.ones((5,), dtype=int)
  155. array([1, 1, 1, 1, 1])
  156. >>> np.ones((2, 1))
  157. array([[1.],
  158. [1.]])
  159. >>> s = (2,2)
  160. >>> np.ones(s)
  161. array([[1., 1.],
  162. [1., 1.]])
  163. """
  164. if like is not None:
  165. return _ones_with_like(shape, dtype=dtype, order=order, like=like)
  166. a = empty(shape, dtype, order)
  167. multiarray.copyto(a, 1, casting='unsafe')
  168. return a
  169. _ones_with_like = array_function_dispatch(
  170. _ones_dispatcher
  171. )(ones)
  172. def _ones_like_dispatcher(a, dtype=None, order=None, subok=None, shape=None):
  173. return (a,)
  174. @array_function_dispatch(_ones_like_dispatcher)
  175. def ones_like(a, dtype=None, order='K', subok=True, shape=None):
  176. """
  177. Return an array of ones with the same shape and type as a given array.
  178. Parameters
  179. ----------
  180. a : array_like
  181. The shape and data-type of `a` define these same attributes of
  182. the returned array.
  183. dtype : data-type, optional
  184. Overrides the data type of the result.
  185. .. versionadded:: 1.6.0
  186. order : {'C', 'F', 'A', or 'K'}, optional
  187. Overrides the memory layout of the result. 'C' means C-order,
  188. 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
  189. 'C' otherwise. 'K' means match the layout of `a` as closely
  190. as possible.
  191. .. versionadded:: 1.6.0
  192. subok : bool, optional.
  193. If True, then the newly created array will use the sub-class
  194. type of `a`, otherwise it will be a base-class array. Defaults
  195. to True.
  196. shape : int or sequence of ints, optional.
  197. Overrides the shape of the result. If order='K' and the number of
  198. dimensions is unchanged, will try to keep order, otherwise,
  199. order='C' is implied.
  200. .. versionadded:: 1.17.0
  201. Returns
  202. -------
  203. out : ndarray
  204. Array of ones with the same shape and type as `a`.
  205. See Also
  206. --------
  207. empty_like : Return an empty array with shape and type of input.
  208. zeros_like : Return an array of zeros with shape and type of input.
  209. full_like : Return a new array with shape of input filled with value.
  210. ones : Return a new array setting values to one.
  211. Examples
  212. --------
  213. >>> x = np.arange(6)
  214. >>> x = x.reshape((2, 3))
  215. >>> x
  216. array([[0, 1, 2],
  217. [3, 4, 5]])
  218. >>> np.ones_like(x)
  219. array([[1, 1, 1],
  220. [1, 1, 1]])
  221. >>> y = np.arange(3, dtype=float)
  222. >>> y
  223. array([0., 1., 2.])
  224. >>> np.ones_like(y)
  225. array([1., 1., 1.])
  226. """
  227. res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
  228. multiarray.copyto(res, 1, casting='unsafe')
  229. return res
  230. def _full_dispatcher(shape, fill_value, dtype=None, order=None, *, like=None):
  231. return(like,)
  232. @set_array_function_like_doc
  233. @set_module('numpy')
  234. def full(shape, fill_value, dtype=None, order='C', *, like=None):
  235. """
  236. Return a new array of given shape and type, filled with `fill_value`.
  237. Parameters
  238. ----------
  239. shape : int or sequence of ints
  240. Shape of the new array, e.g., ``(2, 3)`` or ``2``.
  241. fill_value : scalar or array_like
  242. Fill value.
  243. dtype : data-type, optional
  244. The desired data-type for the array The default, None, means
  245. ``np.array(fill_value).dtype``.
  246. order : {'C', 'F'}, optional
  247. Whether to store multidimensional data in C- or Fortran-contiguous
  248. (row- or column-wise) order in memory.
  249. ${ARRAY_FUNCTION_LIKE}
  250. .. versionadded:: 1.20.0
  251. Returns
  252. -------
  253. out : ndarray
  254. Array of `fill_value` with the given shape, dtype, and order.
  255. See Also
  256. --------
  257. full_like : Return a new array with shape of input filled with value.
  258. empty : Return a new uninitialized array.
  259. ones : Return a new array setting values to one.
  260. zeros : Return a new array setting values to zero.
  261. Examples
  262. --------
  263. >>> np.full((2, 2), np.inf)
  264. array([[inf, inf],
  265. [inf, inf]])
  266. >>> np.full((2, 2), 10)
  267. array([[10, 10],
  268. [10, 10]])
  269. >>> np.full((2, 2), [1, 2])
  270. array([[1, 2],
  271. [1, 2]])
  272. """
  273. if like is not None:
  274. return _full_with_like(shape, fill_value, dtype=dtype, order=order, like=like)
  275. if dtype is None:
  276. fill_value = asarray(fill_value)
  277. dtype = fill_value.dtype
  278. a = empty(shape, dtype, order)
  279. multiarray.copyto(a, fill_value, casting='unsafe')
  280. return a
  281. _full_with_like = array_function_dispatch(
  282. _full_dispatcher
  283. )(full)
  284. def _full_like_dispatcher(a, fill_value, dtype=None, order=None, subok=None, shape=None):
  285. return (a,)
  286. @array_function_dispatch(_full_like_dispatcher)
  287. def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
  288. """
  289. Return a full array with the same shape and type as a given array.
  290. Parameters
  291. ----------
  292. a : array_like
  293. The shape and data-type of `a` define these same attributes of
  294. the returned array.
  295. fill_value : scalar
  296. Fill value.
  297. dtype : data-type, optional
  298. Overrides the data type of the result.
  299. order : {'C', 'F', 'A', or 'K'}, optional
  300. Overrides the memory layout of the result. 'C' means C-order,
  301. 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
  302. 'C' otherwise. 'K' means match the layout of `a` as closely
  303. as possible.
  304. subok : bool, optional.
  305. If True, then the newly created array will use the sub-class
  306. type of `a`, otherwise it will be a base-class array. Defaults
  307. to True.
  308. shape : int or sequence of ints, optional.
  309. Overrides the shape of the result. If order='K' and the number of
  310. dimensions is unchanged, will try to keep order, otherwise,
  311. order='C' is implied.
  312. .. versionadded:: 1.17.0
  313. Returns
  314. -------
  315. out : ndarray
  316. Array of `fill_value` with the same shape and type as `a`.
  317. See Also
  318. --------
  319. empty_like : Return an empty array with shape and type of input.
  320. ones_like : Return an array of ones with shape and type of input.
  321. zeros_like : Return an array of zeros with shape and type of input.
  322. full : Return a new array of given shape filled with value.
  323. Examples
  324. --------
  325. >>> x = np.arange(6, dtype=int)
  326. >>> np.full_like(x, 1)
  327. array([1, 1, 1, 1, 1, 1])
  328. >>> np.full_like(x, 0.1)
  329. array([0, 0, 0, 0, 0, 0])
  330. >>> np.full_like(x, 0.1, dtype=np.double)
  331. array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
  332. >>> np.full_like(x, np.nan, dtype=np.double)
  333. array([nan, nan, nan, nan, nan, nan])
  334. >>> y = np.arange(6, dtype=np.double)
  335. >>> np.full_like(y, 0.1)
  336. array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
  337. """
  338. res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
  339. multiarray.copyto(res, fill_value, casting='unsafe')
  340. return res
  341. def _count_nonzero_dispatcher(a, axis=None, *, keepdims=None):
  342. return (a,)
  343. @array_function_dispatch(_count_nonzero_dispatcher)
  344. def count_nonzero(a, axis=None, *, keepdims=False):
  345. """
  346. Counts the number of non-zero values in the array ``a``.
  347. The word "non-zero" is in reference to the Python 2.x
  348. built-in method ``__nonzero__()`` (renamed ``__bool__()``
  349. in Python 3.x) of Python objects that tests an object's
  350. "truthfulness". For example, any number is considered
  351. truthful if it is nonzero, whereas any string is considered
  352. truthful if it is not the empty string. Thus, this function
  353. (recursively) counts how many elements in ``a`` (and in
  354. sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
  355. method evaluated to ``True``.
  356. Parameters
  357. ----------
  358. a : array_like
  359. The array for which to count non-zeros.
  360. axis : int or tuple, optional
  361. Axis or tuple of axes along which to count non-zeros.
  362. Default is None, meaning that non-zeros will be counted
  363. along a flattened version of ``a``.
  364. .. versionadded:: 1.12.0
  365. keepdims : bool, optional
  366. If this is set to True, the axes that are counted are left
  367. in the result as dimensions with size one. With this option,
  368. the result will broadcast correctly against the input array.
  369. .. versionadded:: 1.19.0
  370. Returns
  371. -------
  372. count : int or array of int
  373. Number of non-zero values in the array along a given axis.
  374. Otherwise, the total number of non-zero values in the array
  375. is returned.
  376. See Also
  377. --------
  378. nonzero : Return the coordinates of all the non-zero values.
  379. Examples
  380. --------
  381. >>> np.count_nonzero(np.eye(4))
  382. 4
  383. >>> a = np.array([[0, 1, 7, 0],
  384. ... [3, 0, 2, 19]])
  385. >>> np.count_nonzero(a)
  386. 5
  387. >>> np.count_nonzero(a, axis=0)
  388. array([1, 1, 2, 1])
  389. >>> np.count_nonzero(a, axis=1)
  390. array([2, 3])
  391. >>> np.count_nonzero(a, axis=1, keepdims=True)
  392. array([[2],
  393. [3]])
  394. """
  395. if axis is None and not keepdims:
  396. return multiarray.count_nonzero(a)
  397. a = asanyarray(a)
  398. # TODO: this works around .astype(bool) not working properly (gh-9847)
  399. if np.issubdtype(a.dtype, np.character):
  400. a_bool = a != a.dtype.type()
  401. else:
  402. a_bool = a.astype(np.bool_, copy=False)
  403. return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)
  404. @set_module('numpy')
  405. def isfortran(a):
  406. """
  407. Check if the array is Fortran contiguous but *not* C contiguous.
  408. This function is obsolete and, because of changes due to relaxed stride
  409. checking, its return value for the same array may differ for versions
  410. of NumPy >= 1.10.0 and previous versions. If you only want to check if an
  411. array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
  412. Parameters
  413. ----------
  414. a : ndarray
  415. Input array.
  416. Returns
  417. -------
  418. isfortran : bool
  419. Returns True if the array is Fortran contiguous but *not* C contiguous.
  420. Examples
  421. --------
  422. np.array allows to specify whether the array is written in C-contiguous
  423. order (last index varies the fastest), or FORTRAN-contiguous order in
  424. memory (first index varies the fastest).
  425. >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
  426. >>> a
  427. array([[1, 2, 3],
  428. [4, 5, 6]])
  429. >>> np.isfortran(a)
  430. False
  431. >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
  432. >>> b
  433. array([[1, 2, 3],
  434. [4, 5, 6]])
  435. >>> np.isfortran(b)
  436. True
  437. The transpose of a C-ordered array is a FORTRAN-ordered array.
  438. >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
  439. >>> a
  440. array([[1, 2, 3],
  441. [4, 5, 6]])
  442. >>> np.isfortran(a)
  443. False
  444. >>> b = a.T
  445. >>> b
  446. array([[1, 4],
  447. [2, 5],
  448. [3, 6]])
  449. >>> np.isfortran(b)
  450. True
  451. C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
  452. >>> np.isfortran(np.array([1, 2], order='F'))
  453. False
  454. """
  455. return a.flags.fnc
  456. def _argwhere_dispatcher(a):
  457. return (a,)
  458. @array_function_dispatch(_argwhere_dispatcher)
  459. def argwhere(a):
  460. """
  461. Find the indices of array elements that are non-zero, grouped by element.
  462. Parameters
  463. ----------
  464. a : array_like
  465. Input data.
  466. Returns
  467. -------
  468. index_array : (N, a.ndim) ndarray
  469. Indices of elements that are non-zero. Indices are grouped by element.
  470. This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
  471. non-zero items.
  472. See Also
  473. --------
  474. where, nonzero
  475. Notes
  476. -----
  477. ``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
  478. but produces a result of the correct shape for a 0D array.
  479. The output of ``argwhere`` is not suitable for indexing arrays.
  480. For this purpose use ``nonzero(a)`` instead.
  481. Examples
  482. --------
  483. >>> x = np.arange(6).reshape(2,3)
  484. >>> x
  485. array([[0, 1, 2],
  486. [3, 4, 5]])
  487. >>> np.argwhere(x>1)
  488. array([[0, 2],
  489. [1, 0],
  490. [1, 1],
  491. [1, 2]])
  492. """
  493. # nonzero does not behave well on 0d, so promote to 1d
  494. if np.ndim(a) == 0:
  495. a = shape_base.atleast_1d(a)
  496. # then remove the added dimension
  497. return argwhere(a)[:,:0]
  498. return transpose(nonzero(a))
  499. def _flatnonzero_dispatcher(a):
  500. return (a,)
  501. @array_function_dispatch(_flatnonzero_dispatcher)
  502. def flatnonzero(a):
  503. """
  504. Return indices that are non-zero in the flattened version of a.
  505. This is equivalent to np.nonzero(np.ravel(a))[0].
  506. Parameters
  507. ----------
  508. a : array_like
  509. Input data.
  510. Returns
  511. -------
  512. res : ndarray
  513. Output array, containing the indices of the elements of `a.ravel()`
  514. that are non-zero.
  515. See Also
  516. --------
  517. nonzero : Return the indices of the non-zero elements of the input array.
  518. ravel : Return a 1-D array containing the elements of the input array.
  519. Examples
  520. --------
  521. >>> x = np.arange(-2, 3)
  522. >>> x
  523. array([-2, -1, 0, 1, 2])
  524. >>> np.flatnonzero(x)
  525. array([0, 1, 3, 4])
  526. Use the indices of the non-zero elements as an index array to extract
  527. these elements:
  528. >>> x.ravel()[np.flatnonzero(x)]
  529. array([-2, -1, 1, 2])
  530. """
  531. return np.nonzero(np.ravel(a))[0]
  532. def _correlate_dispatcher(a, v, mode=None):
  533. return (a, v)
  534. @array_function_dispatch(_correlate_dispatcher)
  535. def correlate(a, v, mode='valid'):
  536. """
  537. Cross-correlation of two 1-dimensional sequences.
  538. This function computes the correlation as generally defined in signal
  539. processing texts::
  540. c_{av}[k] = sum_n a[n+k] * conj(v[n])
  541. with a and v sequences being zero-padded where necessary and conj being
  542. the conjugate.
  543. Parameters
  544. ----------
  545. a, v : array_like
  546. Input sequences.
  547. mode : {'valid', 'same', 'full'}, optional
  548. Refer to the `convolve` docstring. Note that the default
  549. is 'valid', unlike `convolve`, which uses 'full'.
  550. old_behavior : bool
  551. `old_behavior` was removed in NumPy 1.10. If you need the old
  552. behavior, use `multiarray.correlate`.
  553. Returns
  554. -------
  555. out : ndarray
  556. Discrete cross-correlation of `a` and `v`.
  557. See Also
  558. --------
  559. convolve : Discrete, linear convolution of two one-dimensional sequences.
  560. multiarray.correlate : Old, no conjugate, version of correlate.
  561. scipy.signal.correlate : uses FFT which has superior performance on large arrays.
  562. Notes
  563. -----
  564. The definition of correlation above is not unique and sometimes correlation
  565. may be defined differently. Another common definition is::
  566. c'_{av}[k] = sum_n a[n] conj(v[n+k])
  567. which is related to ``c_{av}[k]`` by ``c'_{av}[k] = c_{av}[-k]``.
  568. `numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5) because it does
  569. not use the FFT to compute the convolution; in that case, `scipy.signal.correlate` might
  570. be preferable.
  571. Examples
  572. --------
  573. >>> np.correlate([1, 2, 3], [0, 1, 0.5])
  574. array([3.5])
  575. >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
  576. array([2. , 3.5, 3. ])
  577. >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
  578. array([0.5, 2. , 3.5, 3. , 0. ])
  579. Using complex sequences:
  580. >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
  581. array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
  582. Note that you get the time reversed, complex conjugated result
  583. when the two input sequences change places, i.e.,
  584. ``c_{va}[k] = c^{*}_{av}[-k]``:
  585. >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
  586. array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
  587. """
  588. return multiarray.correlate2(a, v, mode)
  589. def _convolve_dispatcher(a, v, mode=None):
  590. return (a, v)
  591. @array_function_dispatch(_convolve_dispatcher)
  592. def convolve(a, v, mode='full'):
  593. """
  594. Returns the discrete, linear convolution of two one-dimensional sequences.
  595. The convolution operator is often seen in signal processing, where it
  596. models the effect of a linear time-invariant system on a signal [1]_. In
  597. probability theory, the sum of two independent random variables is
  598. distributed according to the convolution of their individual
  599. distributions.
  600. If `v` is longer than `a`, the arrays are swapped before computation.
  601. Parameters
  602. ----------
  603. a : (N,) array_like
  604. First one-dimensional input array.
  605. v : (M,) array_like
  606. Second one-dimensional input array.
  607. mode : {'full', 'valid', 'same'}, optional
  608. 'full':
  609. By default, mode is 'full'. This returns the convolution
  610. at each point of overlap, with an output shape of (N+M-1,). At
  611. the end-points of the convolution, the signals do not overlap
  612. completely, and boundary effects may be seen.
  613. 'same':
  614. Mode 'same' returns output of length ``max(M, N)``. Boundary
  615. effects are still visible.
  616. 'valid':
  617. Mode 'valid' returns output of length
  618. ``max(M, N) - min(M, N) + 1``. The convolution product is only given
  619. for points where the signals overlap completely. Values outside
  620. the signal boundary have no effect.
  621. Returns
  622. -------
  623. out : ndarray
  624. Discrete, linear convolution of `a` and `v`.
  625. See Also
  626. --------
  627. scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
  628. Transform.
  629. scipy.linalg.toeplitz : Used to construct the convolution operator.
  630. polymul : Polynomial multiplication. Same output as convolve, but also
  631. accepts poly1d objects as input.
  632. Notes
  633. -----
  634. The discrete convolution operation is defined as
  635. .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m]
  636. It can be shown that a convolution :math:`x(t) * y(t)` in time/space
  637. is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
  638. domain, after appropriate padding (padding is necessary to prevent
  639. circular convolution). Since multiplication is more efficient (faster)
  640. than convolution, the function `scipy.signal.fftconvolve` exploits the
  641. FFT to calculate the convolution of large data-sets.
  642. References
  643. ----------
  644. .. [1] Wikipedia, "Convolution",
  645. https://en.wikipedia.org/wiki/Convolution
  646. Examples
  647. --------
  648. Note how the convolution operator flips the second array
  649. before "sliding" the two across one another:
  650. >>> np.convolve([1, 2, 3], [0, 1, 0.5])
  651. array([0. , 1. , 2.5, 4. , 1.5])
  652. Only return the middle values of the convolution.
  653. Contains boundary effects, where zeros are taken
  654. into account:
  655. >>> np.convolve([1,2,3],[0,1,0.5], 'same')
  656. array([1. , 2.5, 4. ])
  657. The two arrays are of the same length, so there
  658. is only one position where they completely overlap:
  659. >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
  660. array([2.5])
  661. """
  662. a, v = array(a, copy=False, ndmin=1), array(v, copy=False, ndmin=1)
  663. if (len(v) > len(a)):
  664. a, v = v, a
  665. if len(a) == 0:
  666. raise ValueError('a cannot be empty')
  667. if len(v) == 0:
  668. raise ValueError('v cannot be empty')
  669. return multiarray.correlate(a, v[::-1], mode)
  670. def _outer_dispatcher(a, b, out=None):
  671. return (a, b, out)
  672. @array_function_dispatch(_outer_dispatcher)
  673. def outer(a, b, out=None):
  674. """
  675. Compute the outer product of two vectors.
  676. Given two vectors, ``a = [a0, a1, ..., aM]`` and
  677. ``b = [b0, b1, ..., bN]``,
  678. the outer product [1]_ is::
  679. [[a0*b0 a0*b1 ... a0*bN ]
  680. [a1*b0 .
  681. [ ... .
  682. [aM*b0 aM*bN ]]
  683. Parameters
  684. ----------
  685. a : (M,) array_like
  686. First input vector. Input is flattened if
  687. not already 1-dimensional.
  688. b : (N,) array_like
  689. Second input vector. Input is flattened if
  690. not already 1-dimensional.
  691. out : (M, N) ndarray, optional
  692. A location where the result is stored
  693. .. versionadded:: 1.9.0
  694. Returns
  695. -------
  696. out : (M, N) ndarray
  697. ``out[i, j] = a[i] * b[j]``
  698. See also
  699. --------
  700. inner
  701. einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
  702. ufunc.outer : A generalization to dimensions other than 1D and other
  703. operations. ``np.multiply.outer(a.ravel(), b.ravel())``
  704. is the equivalent.
  705. tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
  706. is the equivalent.
  707. References
  708. ----------
  709. .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd
  710. ed., Baltimore, MD, Johns Hopkins University Press, 1996,
  711. pg. 8.
  712. Examples
  713. --------
  714. Make a (*very* coarse) grid for computing a Mandelbrot set:
  715. >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
  716. >>> rl
  717. array([[-2., -1., 0., 1., 2.],
  718. [-2., -1., 0., 1., 2.],
  719. [-2., -1., 0., 1., 2.],
  720. [-2., -1., 0., 1., 2.],
  721. [-2., -1., 0., 1., 2.]])
  722. >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
  723. >>> im
  724. array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
  725. [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
  726. [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
  727. [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
  728. [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
  729. >>> grid = rl + im
  730. >>> grid
  731. array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
  732. [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
  733. [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
  734. [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
  735. [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
  736. An example using a "vector" of letters:
  737. >>> x = np.array(['a', 'b', 'c'], dtype=object)
  738. >>> np.outer(x, [1, 2, 3])
  739. array([['a', 'aa', 'aaa'],
  740. ['b', 'bb', 'bbb'],
  741. ['c', 'cc', 'ccc']], dtype=object)
  742. """
  743. a = asarray(a)
  744. b = asarray(b)
  745. return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis, :], out)
  746. def _tensordot_dispatcher(a, b, axes=None):
  747. return (a, b)
  748. @array_function_dispatch(_tensordot_dispatcher)
  749. def tensordot(a, b, axes=2):
  750. """
  751. Compute tensor dot product along specified axes.
  752. Given two tensors, `a` and `b`, and an array_like object containing
  753. two array_like objects, ``(a_axes, b_axes)``, sum the products of
  754. `a`'s and `b`'s elements (components) over the axes specified by
  755. ``a_axes`` and ``b_axes``. The third argument can be a single non-negative
  756. integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
  757. of `a` and the first ``N`` dimensions of `b` are summed over.
  758. Parameters
  759. ----------
  760. a, b : array_like
  761. Tensors to "dot".
  762. axes : int or (2,) array_like
  763. * integer_like
  764. If an int N, sum over the last N axes of `a` and the first N axes
  765. of `b` in order. The sizes of the corresponding axes must match.
  766. * (2,) array_like
  767. Or, a list of axes to be summed over, first sequence applying to `a`,
  768. second to `b`. Both elements array_like must be of the same length.
  769. Returns
  770. -------
  771. output : ndarray
  772. The tensor dot product of the input.
  773. See Also
  774. --------
  775. dot, einsum
  776. Notes
  777. -----
  778. Three common use cases are:
  779. * ``axes = 0`` : tensor product :math:`a\\otimes b`
  780. * ``axes = 1`` : tensor dot product :math:`a\\cdot b`
  781. * ``axes = 2`` : (default) tensor double contraction :math:`a:b`
  782. When `axes` is integer_like, the sequence for evaluation will be: first
  783. the -Nth axis in `a` and 0th axis in `b`, and the -1th axis in `a` and
  784. Nth axis in `b` last.
  785. When there is more than one axis to sum over - and they are not the last
  786. (first) axes of `a` (`b`) - the argument `axes` should consist of
  787. two sequences of the same length, with the first axis to sum over given
  788. first in both sequences, the second axis second, and so forth.
  789. The shape of the result consists of the non-contracted axes of the
  790. first tensor, followed by the non-contracted axes of the second.
  791. Examples
  792. --------
  793. A "traditional" example:
  794. >>> a = np.arange(60.).reshape(3,4,5)
  795. >>> b = np.arange(24.).reshape(4,3,2)
  796. >>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
  797. >>> c.shape
  798. (5, 2)
  799. >>> c
  800. array([[4400., 4730.],
  801. [4532., 4874.],
  802. [4664., 5018.],
  803. [4796., 5162.],
  804. [4928., 5306.]])
  805. >>> # A slower but equivalent way of computing the same...
  806. >>> d = np.zeros((5,2))
  807. >>> for i in range(5):
  808. ... for j in range(2):
  809. ... for k in range(3):
  810. ... for n in range(4):
  811. ... d[i,j] += a[k,n,i] * b[n,k,j]
  812. >>> c == d
  813. array([[ True, True],
  814. [ True, True],
  815. [ True, True],
  816. [ True, True],
  817. [ True, True]])
  818. An extended example taking advantage of the overloading of + and \\*:
  819. >>> a = np.array(range(1, 9))
  820. >>> a.shape = (2, 2, 2)
  821. >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
  822. >>> A.shape = (2, 2)
  823. >>> a; A
  824. array([[[1, 2],
  825. [3, 4]],
  826. [[5, 6],
  827. [7, 8]]])
  828. array([['a', 'b'],
  829. ['c', 'd']], dtype=object)
  830. >>> np.tensordot(a, A) # third argument default is 2 for double-contraction
  831. array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
  832. >>> np.tensordot(a, A, 1)
  833. array([[['acc', 'bdd'],
  834. ['aaacccc', 'bbbdddd']],
  835. [['aaaaacccccc', 'bbbbbdddddd'],
  836. ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
  837. >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
  838. array([[[[['a', 'b'],
  839. ['c', 'd']],
  840. ...
  841. >>> np.tensordot(a, A, (0, 1))
  842. array([[['abbbbb', 'cddddd'],
  843. ['aabbbbbb', 'ccdddddd']],
  844. [['aaabbbbbbb', 'cccddddddd'],
  845. ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
  846. >>> np.tensordot(a, A, (2, 1))
  847. array([[['abb', 'cdd'],
  848. ['aaabbbb', 'cccdddd']],
  849. [['aaaaabbbbbb', 'cccccdddddd'],
  850. ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
  851. >>> np.tensordot(a, A, ((0, 1), (0, 1)))
  852. array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
  853. >>> np.tensordot(a, A, ((2, 1), (1, 0)))
  854. array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
  855. """
  856. try:
  857. iter(axes)
  858. except Exception:
  859. axes_a = list(range(-axes, 0))
  860. axes_b = list(range(0, axes))
  861. else:
  862. axes_a, axes_b = axes
  863. try:
  864. na = len(axes_a)
  865. axes_a = list(axes_a)
  866. except TypeError:
  867. axes_a = [axes_a]
  868. na = 1
  869. try:
  870. nb = len(axes_b)
  871. axes_b = list(axes_b)
  872. except TypeError:
  873. axes_b = [axes_b]
  874. nb = 1
  875. a, b = asarray(a), asarray(b)
  876. as_ = a.shape
  877. nda = a.ndim
  878. bs = b.shape
  879. ndb = b.ndim
  880. equal = True
  881. if na != nb:
  882. equal = False
  883. else:
  884. for k in range(na):
  885. if as_[axes_a[k]] != bs[axes_b[k]]:
  886. equal = False
  887. break
  888. if axes_a[k] < 0:
  889. axes_a[k] += nda
  890. if axes_b[k] < 0:
  891. axes_b[k] += ndb
  892. if not equal:
  893. raise ValueError("shape-mismatch for sum")
  894. # Move the axes to sum over to the end of "a"
  895. # and to the front of "b"
  896. notin = [k for k in range(nda) if k not in axes_a]
  897. newaxes_a = notin + axes_a
  898. N2 = 1
  899. for axis in axes_a:
  900. N2 *= as_[axis]
  901. newshape_a = (int(multiply.reduce([as_[ax] for ax in notin])), N2)
  902. olda = [as_[axis] for axis in notin]
  903. notin = [k for k in range(ndb) if k not in axes_b]
  904. newaxes_b = axes_b + notin
  905. N2 = 1
  906. for axis in axes_b:
  907. N2 *= bs[axis]
  908. newshape_b = (N2, int(multiply.reduce([bs[ax] for ax in notin])))
  909. oldb = [bs[axis] for axis in notin]
  910. at = a.transpose(newaxes_a).reshape(newshape_a)
  911. bt = b.transpose(newaxes_b).reshape(newshape_b)
  912. res = dot(at, bt)
  913. return res.reshape(olda + oldb)
  914. def _roll_dispatcher(a, shift, axis=None):
  915. return (a,)
  916. @array_function_dispatch(_roll_dispatcher)
  917. def roll(a, shift, axis=None):
  918. """
  919. Roll array elements along a given axis.
  920. Elements that roll beyond the last position are re-introduced at
  921. the first.
  922. Parameters
  923. ----------
  924. a : array_like
  925. Input array.
  926. shift : int or tuple of ints
  927. The number of places by which elements are shifted. If a tuple,
  928. then `axis` must be a tuple of the same size, and each of the
  929. given axes is shifted by the corresponding number. If an int
  930. while `axis` is a tuple of ints, then the same value is used for
  931. all given axes.
  932. axis : int or tuple of ints, optional
  933. Axis or axes along which elements are shifted. By default, the
  934. array is flattened before shifting, after which the original
  935. shape is restored.
  936. Returns
  937. -------
  938. res : ndarray
  939. Output array, with the same shape as `a`.
  940. See Also
  941. --------
  942. rollaxis : Roll the specified axis backwards, until it lies in a
  943. given position.
  944. Notes
  945. -----
  946. .. versionadded:: 1.12.0
  947. Supports rolling over multiple dimensions simultaneously.
  948. Examples
  949. --------
  950. >>> x = np.arange(10)
  951. >>> np.roll(x, 2)
  952. array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
  953. >>> np.roll(x, -2)
  954. array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
  955. >>> x2 = np.reshape(x, (2,5))
  956. >>> x2
  957. array([[0, 1, 2, 3, 4],
  958. [5, 6, 7, 8, 9]])
  959. >>> np.roll(x2, 1)
  960. array([[9, 0, 1, 2, 3],
  961. [4, 5, 6, 7, 8]])
  962. >>> np.roll(x2, -1)
  963. array([[1, 2, 3, 4, 5],
  964. [6, 7, 8, 9, 0]])
  965. >>> np.roll(x2, 1, axis=0)
  966. array([[5, 6, 7, 8, 9],
  967. [0, 1, 2, 3, 4]])
  968. >>> np.roll(x2, -1, axis=0)
  969. array([[5, 6, 7, 8, 9],
  970. [0, 1, 2, 3, 4]])
  971. >>> np.roll(x2, 1, axis=1)
  972. array([[4, 0, 1, 2, 3],
  973. [9, 5, 6, 7, 8]])
  974. >>> np.roll(x2, -1, axis=1)
  975. array([[1, 2, 3, 4, 0],
  976. [6, 7, 8, 9, 5]])
  977. """
  978. a = asanyarray(a)
  979. if axis is None:
  980. return roll(a.ravel(), shift, 0).reshape(a.shape)
  981. else:
  982. axis = normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
  983. broadcasted = broadcast(shift, axis)
  984. if broadcasted.ndim > 1:
  985. raise ValueError(
  986. "'shift' and 'axis' should be scalars or 1D sequences")
  987. shifts = {ax: 0 for ax in range(a.ndim)}
  988. for sh, ax in broadcasted:
  989. shifts[ax] += sh
  990. rolls = [((slice(None), slice(None)),)] * a.ndim
  991. for ax, offset in shifts.items():
  992. offset %= a.shape[ax] or 1 # If `a` is empty, nothing matters.
  993. if offset:
  994. # (original, result), (original, result)
  995. rolls[ax] = ((slice(None, -offset), slice(offset, None)),
  996. (slice(-offset, None), slice(None, offset)))
  997. result = empty_like(a)
  998. for indices in itertools.product(*rolls):
  999. arr_index, res_index = zip(*indices)
  1000. result[res_index] = a[arr_index]
  1001. return result
  1002. def _rollaxis_dispatcher(a, axis, start=None):
  1003. return (a,)
  1004. @array_function_dispatch(_rollaxis_dispatcher)
  1005. def rollaxis(a, axis, start=0):
  1006. """
  1007. Roll the specified axis backwards, until it lies in a given position.
  1008. This function continues to be supported for backward compatibility, but you
  1009. should prefer `moveaxis`. The `moveaxis` function was added in NumPy
  1010. 1.11.
  1011. Parameters
  1012. ----------
  1013. a : ndarray
  1014. Input array.
  1015. axis : int
  1016. The axis to be rolled. The positions of the other axes do not
  1017. change relative to one another.
  1018. start : int, optional
  1019. When ``start <= axis``, the axis is rolled back until it lies in
  1020. this position. When ``start > axis``, the axis is rolled until it
  1021. lies before this position. The default, 0, results in a "complete"
  1022. roll. The following table describes how negative values of ``start``
  1023. are interpreted:
  1024. .. table::
  1025. :align: left
  1026. +-------------------+----------------------+
  1027. | ``start`` | Normalized ``start`` |
  1028. +===================+======================+
  1029. | ``-(arr.ndim+1)`` | raise ``AxisError`` |
  1030. +-------------------+----------------------+
  1031. | ``-arr.ndim`` | 0 |
  1032. +-------------------+----------------------+
  1033. | |vdots| | |vdots| |
  1034. +-------------------+----------------------+
  1035. | ``-1`` | ``arr.ndim-1`` |
  1036. +-------------------+----------------------+
  1037. | ``0`` | ``0`` |
  1038. +-------------------+----------------------+
  1039. | |vdots| | |vdots| |
  1040. +-------------------+----------------------+
  1041. | ``arr.ndim`` | ``arr.ndim`` |
  1042. +-------------------+----------------------+
  1043. | ``arr.ndim + 1`` | raise ``AxisError`` |
  1044. +-------------------+----------------------+
  1045. .. |vdots| unicode:: U+22EE .. Vertical Ellipsis
  1046. Returns
  1047. -------
  1048. res : ndarray
  1049. For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
  1050. NumPy versions a view of `a` is returned only if the order of the
  1051. axes is changed, otherwise the input array is returned.
  1052. See Also
  1053. --------
  1054. moveaxis : Move array axes to new positions.
  1055. roll : Roll the elements of an array by a number of positions along a
  1056. given axis.
  1057. Examples
  1058. --------
  1059. >>> a = np.ones((3,4,5,6))
  1060. >>> np.rollaxis(a, 3, 1).shape
  1061. (3, 6, 4, 5)
  1062. >>> np.rollaxis(a, 2).shape
  1063. (5, 3, 4, 6)
  1064. >>> np.rollaxis(a, 1, 4).shape
  1065. (3, 5, 6, 4)
  1066. """
  1067. n = a.ndim
  1068. axis = normalize_axis_index(axis, n)
  1069. if start < 0:
  1070. start += n
  1071. msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
  1072. if not (0 <= start < n + 1):
  1073. raise AxisError(msg % ('start', -n, 'start', n + 1, start))
  1074. if axis < start:
  1075. # it's been removed
  1076. start -= 1
  1077. if axis == start:
  1078. return a[...]
  1079. axes = list(range(0, n))
  1080. axes.remove(axis)
  1081. axes.insert(start, axis)
  1082. return a.transpose(axes)
  1083. def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
  1084. """
  1085. Normalizes an axis argument into a tuple of non-negative integer axes.
  1086. This handles shorthands such as ``1`` and converts them to ``(1,)``,
  1087. as well as performing the handling of negative indices covered by
  1088. `normalize_axis_index`.
  1089. By default, this forbids axes from being specified multiple times.
  1090. Used internally by multi-axis-checking logic.
  1091. .. versionadded:: 1.13.0
  1092. Parameters
  1093. ----------
  1094. axis : int, iterable of int
  1095. The un-normalized index or indices of the axis.
  1096. ndim : int
  1097. The number of dimensions of the array that `axis` should be normalized
  1098. against.
  1099. argname : str, optional
  1100. A prefix to put before the error message, typically the name of the
  1101. argument.
  1102. allow_duplicate : bool, optional
  1103. If False, the default, disallow an axis from being specified twice.
  1104. Returns
  1105. -------
  1106. normalized_axes : tuple of int
  1107. The normalized axis index, such that `0 <= normalized_axis < ndim`
  1108. Raises
  1109. ------
  1110. AxisError
  1111. If any axis provided is out of range
  1112. ValueError
  1113. If an axis is repeated
  1114. See also
  1115. --------
  1116. normalize_axis_index : normalizing a single scalar axis
  1117. """
  1118. # Optimization to speed-up the most common cases.
  1119. if type(axis) not in (tuple, list):
  1120. try:
  1121. axis = [operator.index(axis)]
  1122. except TypeError:
  1123. pass
  1124. # Going via an iterator directly is slower than via list comprehension.
  1125. axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
  1126. if not allow_duplicate and len(set(axis)) != len(axis):
  1127. if argname:
  1128. raise ValueError('repeated axis in `{}` argument'.format(argname))
  1129. else:
  1130. raise ValueError('repeated axis')
  1131. return axis
  1132. def _moveaxis_dispatcher(a, source, destination):
  1133. return (a,)
  1134. @array_function_dispatch(_moveaxis_dispatcher)
  1135. def moveaxis(a, source, destination):
  1136. """
  1137. Move axes of an array to new positions.
  1138. Other axes remain in their original order.
  1139. .. versionadded:: 1.11.0
  1140. Parameters
  1141. ----------
  1142. a : np.ndarray
  1143. The array whose axes should be reordered.
  1144. source : int or sequence of int
  1145. Original positions of the axes to move. These must be unique.
  1146. destination : int or sequence of int
  1147. Destination positions for each of the original axes. These must also be
  1148. unique.
  1149. Returns
  1150. -------
  1151. result : np.ndarray
  1152. Array with moved axes. This array is a view of the input array.
  1153. See Also
  1154. --------
  1155. transpose : Permute the dimensions of an array.
  1156. swapaxes : Interchange two axes of an array.
  1157. Examples
  1158. --------
  1159. >>> x = np.zeros((3, 4, 5))
  1160. >>> np.moveaxis(x, 0, -1).shape
  1161. (4, 5, 3)
  1162. >>> np.moveaxis(x, -1, 0).shape
  1163. (5, 3, 4)
  1164. These all achieve the same result:
  1165. >>> np.transpose(x).shape
  1166. (5, 4, 3)
  1167. >>> np.swapaxes(x, 0, -1).shape
  1168. (5, 4, 3)
  1169. >>> np.moveaxis(x, [0, 1], [-1, -2]).shape
  1170. (5, 4, 3)
  1171. >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
  1172. (5, 4, 3)
  1173. """
  1174. try:
  1175. # allow duck-array types if they define transpose
  1176. transpose = a.transpose
  1177. except AttributeError:
  1178. a = asarray(a)
  1179. transpose = a.transpose
  1180. source = normalize_axis_tuple(source, a.ndim, 'source')
  1181. destination = normalize_axis_tuple(destination, a.ndim, 'destination')
  1182. if len(source) != len(destination):
  1183. raise ValueError('`source` and `destination` arguments must have '
  1184. 'the same number of elements')
  1185. order = [n for n in range(a.ndim) if n not in source]
  1186. for dest, src in sorted(zip(destination, source)):
  1187. order.insert(dest, src)
  1188. result = transpose(order)
  1189. return result
  1190. # fix hack in scipy which imports this function
  1191. def _move_axis_to_0(a, axis):
  1192. return moveaxis(a, axis, 0)
  1193. def _cross_dispatcher(a, b, axisa=None, axisb=None, axisc=None, axis=None):
  1194. return (a, b)
  1195. @array_function_dispatch(_cross_dispatcher)
  1196. def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
  1197. """
  1198. Return the cross product of two (arrays of) vectors.
  1199. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
  1200. to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
  1201. are defined by the last axis of `a` and `b` by default, and these axes
  1202. can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
  1203. 2, the third component of the input vector is assumed to be zero and the
  1204. cross product calculated accordingly. In cases where both input vectors
  1205. have dimension 2, the z-component of the cross product is returned.
  1206. Parameters
  1207. ----------
  1208. a : array_like
  1209. Components of the first vector(s).
  1210. b : array_like
  1211. Components of the second vector(s).
  1212. axisa : int, optional
  1213. Axis of `a` that defines the vector(s). By default, the last axis.
  1214. axisb : int, optional
  1215. Axis of `b` that defines the vector(s). By default, the last axis.
  1216. axisc : int, optional
  1217. Axis of `c` containing the cross product vector(s). Ignored if
  1218. both input vectors have dimension 2, as the return is scalar.
  1219. By default, the last axis.
  1220. axis : int, optional
  1221. If defined, the axis of `a`, `b` and `c` that defines the vector(s)
  1222. and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
  1223. Returns
  1224. -------
  1225. c : ndarray
  1226. Vector cross product(s).
  1227. Raises
  1228. ------
  1229. ValueError
  1230. When the dimension of the vector(s) in `a` and/or `b` does not
  1231. equal 2 or 3.
  1232. See Also
  1233. --------
  1234. inner : Inner product
  1235. outer : Outer product.
  1236. ix_ : Construct index arrays.
  1237. Notes
  1238. -----
  1239. .. versionadded:: 1.9.0
  1240. Supports full broadcasting of the inputs.
  1241. Examples
  1242. --------
  1243. Vector cross-product.
  1244. >>> x = [1, 2, 3]
  1245. >>> y = [4, 5, 6]
  1246. >>> np.cross(x, y)
  1247. array([-3, 6, -3])
  1248. One vector with dimension 2.
  1249. >>> x = [1, 2]
  1250. >>> y = [4, 5, 6]
  1251. >>> np.cross(x, y)
  1252. array([12, -6, -3])
  1253. Equivalently:
  1254. >>> x = [1, 2, 0]
  1255. >>> y = [4, 5, 6]
  1256. >>> np.cross(x, y)
  1257. array([12, -6, -3])
  1258. Both vectors with dimension 2.
  1259. >>> x = [1,2]
  1260. >>> y = [4,5]
  1261. >>> np.cross(x, y)
  1262. array(-3)
  1263. Multiple vector cross-products. Note that the direction of the cross
  1264. product vector is defined by the `right-hand rule`.
  1265. >>> x = np.array([[1,2,3], [4,5,6]])
  1266. >>> y = np.array([[4,5,6], [1,2,3]])
  1267. >>> np.cross(x, y)
  1268. array([[-3, 6, -3],
  1269. [ 3, -6, 3]])
  1270. The orientation of `c` can be changed using the `axisc` keyword.
  1271. >>> np.cross(x, y, axisc=0)
  1272. array([[-3, 3],
  1273. [ 6, -6],
  1274. [-3, 3]])
  1275. Change the vector definition of `x` and `y` using `axisa` and `axisb`.
  1276. >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
  1277. >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
  1278. >>> np.cross(x, y)
  1279. array([[ -6, 12, -6],
  1280. [ 0, 0, 0],
  1281. [ 6, -12, 6]])
  1282. >>> np.cross(x, y, axisa=0, axisb=0)
  1283. array([[-24, 48, -24],
  1284. [-30, 60, -30],
  1285. [-36, 72, -36]])
  1286. """
  1287. if axis is not None:
  1288. axisa, axisb, axisc = (axis,) * 3
  1289. a = asarray(a)
  1290. b = asarray(b)
  1291. # Check axisa and axisb are within bounds
  1292. axisa = normalize_axis_index(axisa, a.ndim, msg_prefix='axisa')
  1293. axisb = normalize_axis_index(axisb, b.ndim, msg_prefix='axisb')
  1294. # Move working axis to the end of the shape
  1295. a = moveaxis(a, axisa, -1)
  1296. b = moveaxis(b, axisb, -1)
  1297. msg = ("incompatible dimensions for cross product\n"
  1298. "(dimension must be 2 or 3)")
  1299. if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
  1300. raise ValueError(msg)
  1301. # Create the output array
  1302. shape = broadcast(a[..., 0], b[..., 0]).shape
  1303. if a.shape[-1] == 3 or b.shape[-1] == 3:
  1304. shape += (3,)
  1305. # Check axisc is within bounds
  1306. axisc = normalize_axis_index(axisc, len(shape), msg_prefix='axisc')
  1307. dtype = promote_types(a.dtype, b.dtype)
  1308. cp = empty(shape, dtype)
  1309. # create local aliases for readability
  1310. a0 = a[..., 0]
  1311. a1 = a[..., 1]
  1312. if a.shape[-1] == 3:
  1313. a2 = a[..., 2]
  1314. b0 = b[..., 0]
  1315. b1 = b[..., 1]
  1316. if b.shape[-1] == 3:
  1317. b2 = b[..., 2]
  1318. if cp.ndim != 0 and cp.shape[-1] == 3:
  1319. cp0 = cp[..., 0]
  1320. cp1 = cp[..., 1]
  1321. cp2 = cp[..., 2]
  1322. if a.shape[-1] == 2:
  1323. if b.shape[-1] == 2:
  1324. # a0 * b1 - a1 * b0
  1325. multiply(a0, b1, out=cp)
  1326. cp -= a1 * b0
  1327. return cp
  1328. else:
  1329. assert b.shape[-1] == 3
  1330. # cp0 = a1 * b2 - 0 (a2 = 0)
  1331. # cp1 = 0 - a0 * b2 (a2 = 0)
  1332. # cp2 = a0 * b1 - a1 * b0
  1333. multiply(a1, b2, out=cp0)
  1334. multiply(a0, b2, out=cp1)
  1335. negative(cp1, out=cp1)
  1336. multiply(a0, b1, out=cp2)
  1337. cp2 -= a1 * b0
  1338. else:
  1339. assert a.shape[-1] == 3
  1340. if b.shape[-1] == 3:
  1341. # cp0 = a1 * b2 - a2 * b1
  1342. # cp1 = a2 * b0 - a0 * b2
  1343. # cp2 = a0 * b1 - a1 * b0
  1344. multiply(a1, b2, out=cp0)
  1345. tmp = array(a2 * b1)
  1346. cp0 -= tmp
  1347. multiply(a2, b0, out=cp1)
  1348. multiply(a0, b2, out=tmp)
  1349. cp1 -= tmp
  1350. multiply(a0, b1, out=cp2)
  1351. multiply(a1, b0, out=tmp)
  1352. cp2 -= tmp
  1353. else:
  1354. assert b.shape[-1] == 2
  1355. # cp0 = 0 - a2 * b1 (b2 = 0)
  1356. # cp1 = a2 * b0 - 0 (b2 = 0)
  1357. # cp2 = a0 * b1 - a1 * b0
  1358. multiply(a2, b1, out=cp0)
  1359. negative(cp0, out=cp0)
  1360. multiply(a2, b0, out=cp1)
  1361. multiply(a0, b1, out=cp2)
  1362. cp2 -= a1 * b0
  1363. return moveaxis(cp, -1, axisc)
  1364. little_endian = (sys.byteorder == 'little')
  1365. @set_module('numpy')
  1366. def indices(dimensions, dtype=int, sparse=False):
  1367. """
  1368. Return an array representing the indices of a grid.
  1369. Compute an array where the subarrays contain index values 0, 1, ...
  1370. varying only along the corresponding axis.
  1371. Parameters
  1372. ----------
  1373. dimensions : sequence of ints
  1374. The shape of the grid.
  1375. dtype : dtype, optional
  1376. Data type of the result.
  1377. sparse : boolean, optional
  1378. Return a sparse representation of the grid instead of a dense
  1379. representation. Default is False.
  1380. .. versionadded:: 1.17
  1381. Returns
  1382. -------
  1383. grid : one ndarray or tuple of ndarrays
  1384. If sparse is False:
  1385. Returns one array of grid indices,
  1386. ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
  1387. If sparse is True:
  1388. Returns a tuple of arrays, with
  1389. ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
  1390. dimensions[i] in the ith place
  1391. See Also
  1392. --------
  1393. mgrid, ogrid, meshgrid
  1394. Notes
  1395. -----
  1396. The output shape in the dense case is obtained by prepending the number
  1397. of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
  1398. is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
  1399. ``(N, r0, ..., rN-1)``.
  1400. The subarrays ``grid[k]`` contains the N-D array of indices along the
  1401. ``k-th`` axis. Explicitly::
  1402. grid[k, i0, i1, ..., iN-1] = ik
  1403. Examples
  1404. --------
  1405. >>> grid = np.indices((2, 3))
  1406. >>> grid.shape
  1407. (2, 2, 3)
  1408. >>> grid[0] # row indices
  1409. array([[0, 0, 0],
  1410. [1, 1, 1]])
  1411. >>> grid[1] # column indices
  1412. array([[0, 1, 2],
  1413. [0, 1, 2]])
  1414. The indices can be used as an index into an array.
  1415. >>> x = np.arange(20).reshape(5, 4)
  1416. >>> row, col = np.indices((2, 3))
  1417. >>> x[row, col]
  1418. array([[0, 1, 2],
  1419. [4, 5, 6]])
  1420. Note that it would be more straightforward in the above example to
  1421. extract the required elements directly with ``x[:2, :3]``.
  1422. If sparse is set to true, the grid will be returned in a sparse
  1423. representation.
  1424. >>> i, j = np.indices((2, 3), sparse=True)
  1425. >>> i.shape
  1426. (2, 1)
  1427. >>> j.shape
  1428. (1, 3)
  1429. >>> i # row indices
  1430. array([[0],
  1431. [1]])
  1432. >>> j # column indices
  1433. array([[0, 1, 2]])
  1434. """
  1435. dimensions = tuple(dimensions)
  1436. N = len(dimensions)
  1437. shape = (1,)*N
  1438. if sparse:
  1439. res = tuple()
  1440. else:
  1441. res = empty((N,)+dimensions, dtype=dtype)
  1442. for i, dim in enumerate(dimensions):
  1443. idx = arange(dim, dtype=dtype).reshape(
  1444. shape[:i] + (dim,) + shape[i+1:]
  1445. )
  1446. if sparse:
  1447. res = res + (idx,)
  1448. else:
  1449. res[i] = idx
  1450. return res
  1451. def _fromfunction_dispatcher(function, shape, *, dtype=None, like=None, **kwargs):
  1452. return (like,)
  1453. @set_array_function_like_doc
  1454. @set_module('numpy')
  1455. def fromfunction(function, shape, *, dtype=float, like=None, **kwargs):
  1456. """
  1457. Construct an array by executing a function over each coordinate.
  1458. The resulting array therefore has a value ``fn(x, y, z)`` at
  1459. coordinate ``(x, y, z)``.
  1460. Parameters
  1461. ----------
  1462. function : callable
  1463. The function is called with N parameters, where N is the rank of
  1464. `shape`. Each parameter represents the coordinates of the array
  1465. varying along a specific axis. For example, if `shape`
  1466. were ``(2, 2)``, then the parameters would be
  1467. ``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
  1468. shape : (N,) tuple of ints
  1469. Shape of the output array, which also determines the shape of
  1470. the coordinate arrays passed to `function`.
  1471. dtype : data-type, optional
  1472. Data-type of the coordinate arrays passed to `function`.
  1473. By default, `dtype` is float.
  1474. ${ARRAY_FUNCTION_LIKE}
  1475. .. versionadded:: 1.20.0
  1476. Returns
  1477. -------
  1478. fromfunction : any
  1479. The result of the call to `function` is passed back directly.
  1480. Therefore the shape of `fromfunction` is completely determined by
  1481. `function`. If `function` returns a scalar value, the shape of
  1482. `fromfunction` would not match the `shape` parameter.
  1483. See Also
  1484. --------
  1485. indices, meshgrid
  1486. Notes
  1487. -----
  1488. Keywords other than `dtype` are passed to `function`.
  1489. Examples
  1490. --------
  1491. >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
  1492. array([[ True, False, False],
  1493. [False, True, False],
  1494. [False, False, True]])
  1495. >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
  1496. array([[0, 1, 2],
  1497. [1, 2, 3],
  1498. [2, 3, 4]])
  1499. """
  1500. if like is not None:
  1501. return _fromfunction_with_like(function, shape, dtype=dtype, like=like, **kwargs)
  1502. args = indices(shape, dtype=dtype)
  1503. return function(*args, **kwargs)
  1504. _fromfunction_with_like = array_function_dispatch(
  1505. _fromfunction_dispatcher
  1506. )(fromfunction)
  1507. def _frombuffer(buf, dtype, shape, order):
  1508. return frombuffer(buf, dtype=dtype).reshape(shape, order=order)
  1509. @set_module('numpy')
  1510. def isscalar(element):
  1511. """
  1512. Returns True if the type of `element` is a scalar type.
  1513. Parameters
  1514. ----------
  1515. element : any
  1516. Input argument, can be of any type and shape.
  1517. Returns
  1518. -------
  1519. val : bool
  1520. True if `element` is a scalar type, False if it is not.
  1521. See Also
  1522. --------
  1523. ndim : Get the number of dimensions of an array
  1524. Notes
  1525. -----
  1526. If you need a stricter way to identify a *numerical* scalar, use
  1527. ``isinstance(x, numbers.Number)``, as that returns ``False`` for most
  1528. non-numerical elements such as strings.
  1529. In most cases ``np.ndim(x) == 0`` should be used instead of this function,
  1530. as that will also return true for 0d arrays. This is how numpy overloads
  1531. functions in the style of the ``dx`` arguments to `gradient` and the ``bins``
  1532. argument to `histogram`. Some key differences:
  1533. +--------------------------------------+---------------+-------------------+
  1534. | x |``isscalar(x)``|``np.ndim(x) == 0``|
  1535. +======================================+===============+===================+
  1536. | PEP 3141 numeric objects (including | ``True`` | ``True`` |
  1537. | builtins) | | |
  1538. +--------------------------------------+---------------+-------------------+
  1539. | builtin string and buffer objects | ``True`` | ``True`` |
  1540. +--------------------------------------+---------------+-------------------+
  1541. | other builtin objects, like | ``False`` | ``True`` |
  1542. | `pathlib.Path`, `Exception`, | | |
  1543. | the result of `re.compile` | | |
  1544. +--------------------------------------+---------------+-------------------+
  1545. | third-party objects like | ``False`` | ``True`` |
  1546. | `matplotlib.figure.Figure` | | |
  1547. +--------------------------------------+---------------+-------------------+
  1548. | zero-dimensional numpy arrays | ``False`` | ``True`` |
  1549. +--------------------------------------+---------------+-------------------+
  1550. | other numpy arrays | ``False`` | ``False`` |
  1551. +--------------------------------------+---------------+-------------------+
  1552. | `list`, `tuple`, and other sequence | ``False`` | ``False`` |
  1553. | objects | | |
  1554. +--------------------------------------+---------------+-------------------+
  1555. Examples
  1556. --------
  1557. >>> np.isscalar(3.1)
  1558. True
  1559. >>> np.isscalar(np.array(3.1))
  1560. False
  1561. >>> np.isscalar([3.1])
  1562. False
  1563. >>> np.isscalar(False)
  1564. True
  1565. >>> np.isscalar('numpy')
  1566. True
  1567. NumPy supports PEP 3141 numbers:
  1568. >>> from fractions import Fraction
  1569. >>> np.isscalar(Fraction(5, 17))
  1570. True
  1571. >>> from numbers import Number
  1572. >>> np.isscalar(Number())
  1573. True
  1574. """
  1575. return (isinstance(element, generic)
  1576. or type(element) in ScalarType
  1577. or isinstance(element, numbers.Number))
  1578. @set_module('numpy')
  1579. def binary_repr(num, width=None):
  1580. """
  1581. Return the binary representation of the input number as a string.
  1582. For negative numbers, if width is not given, a minus sign is added to the
  1583. front. If width is given, the two's complement of the number is
  1584. returned, with respect to that width.
  1585. In a two's-complement system negative numbers are represented by the two's
  1586. complement of the absolute value. This is the most common method of
  1587. representing signed integers on computers [1]_. A N-bit two's-complement
  1588. system can represent every integer in the range
  1589. :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
  1590. Parameters
  1591. ----------
  1592. num : int
  1593. Only an integer decimal number can be used.
  1594. width : int, optional
  1595. The length of the returned string if `num` is positive, or the length
  1596. of the two's complement if `num` is negative, provided that `width` is
  1597. at least a sufficient number of bits for `num` to be represented in the
  1598. designated form.
  1599. If the `width` value is insufficient, it will be ignored, and `num` will
  1600. be returned in binary (`num` > 0) or two's complement (`num` < 0) form
  1601. with its width equal to the minimum number of bits needed to represent
  1602. the number in the designated form. This behavior is deprecated and will
  1603. later raise an error.
  1604. .. deprecated:: 1.12.0
  1605. Returns
  1606. -------
  1607. bin : str
  1608. Binary representation of `num` or two's complement of `num`.
  1609. See Also
  1610. --------
  1611. base_repr: Return a string representation of a number in the given base
  1612. system.
  1613. bin: Python's built-in binary representation generator of an integer.
  1614. Notes
  1615. -----
  1616. `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
  1617. faster.
  1618. References
  1619. ----------
  1620. .. [1] Wikipedia, "Two's complement",
  1621. https://en.wikipedia.org/wiki/Two's_complement
  1622. Examples
  1623. --------
  1624. >>> np.binary_repr(3)
  1625. '11'
  1626. >>> np.binary_repr(-3)
  1627. '-11'
  1628. >>> np.binary_repr(3, width=4)
  1629. '0011'
  1630. The two's complement is returned when the input number is negative and
  1631. width is specified:
  1632. >>> np.binary_repr(-3, width=3)
  1633. '101'
  1634. >>> np.binary_repr(-3, width=5)
  1635. '11101'
  1636. """
  1637. def warn_if_insufficient(width, binwidth):
  1638. if width is not None and width < binwidth:
  1639. warnings.warn(
  1640. "Insufficient bit width provided. This behavior "
  1641. "will raise an error in the future.", DeprecationWarning,
  1642. stacklevel=3)
  1643. # Ensure that num is a Python integer to avoid overflow or unwanted
  1644. # casts to floating point.
  1645. num = operator.index(num)
  1646. if num == 0:
  1647. return '0' * (width or 1)
  1648. elif num > 0:
  1649. binary = bin(num)[2:]
  1650. binwidth = len(binary)
  1651. outwidth = (binwidth if width is None
  1652. else max(binwidth, width))
  1653. warn_if_insufficient(width, binwidth)
  1654. return binary.zfill(outwidth)
  1655. else:
  1656. if width is None:
  1657. return '-' + bin(-num)[2:]
  1658. else:
  1659. poswidth = len(bin(-num)[2:])
  1660. # See gh-8679: remove extra digit
  1661. # for numbers at boundaries.
  1662. if 2**(poswidth - 1) == -num:
  1663. poswidth -= 1
  1664. twocomp = 2**(poswidth + 1) + num
  1665. binary = bin(twocomp)[2:]
  1666. binwidth = len(binary)
  1667. outwidth = max(binwidth, width)
  1668. warn_if_insufficient(width, binwidth)
  1669. return '1' * (outwidth - binwidth) + binary
  1670. @set_module('numpy')
  1671. def base_repr(number, base=2, padding=0):
  1672. """
  1673. Return a string representation of a number in the given base system.
  1674. Parameters
  1675. ----------
  1676. number : int
  1677. The value to convert. Positive and negative values are handled.
  1678. base : int, optional
  1679. Convert `number` to the `base` number system. The valid range is 2-36,
  1680. the default value is 2.
  1681. padding : int, optional
  1682. Number of zeros padded on the left. Default is 0 (no padding).
  1683. Returns
  1684. -------
  1685. out : str
  1686. String representation of `number` in `base` system.
  1687. See Also
  1688. --------
  1689. binary_repr : Faster version of `base_repr` for base 2.
  1690. Examples
  1691. --------
  1692. >>> np.base_repr(5)
  1693. '101'
  1694. >>> np.base_repr(6, 5)
  1695. '11'
  1696. >>> np.base_repr(7, base=5, padding=3)
  1697. '00012'
  1698. >>> np.base_repr(10, base=16)
  1699. 'A'
  1700. >>> np.base_repr(32, base=16)
  1701. '20'
  1702. """
  1703. digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1704. if base > len(digits):
  1705. raise ValueError("Bases greater than 36 not handled in base_repr.")
  1706. elif base < 2:
  1707. raise ValueError("Bases less than 2 not handled in base_repr.")
  1708. num = abs(number)
  1709. res = []
  1710. while num:
  1711. res.append(digits[num % base])
  1712. num //= base
  1713. if padding:
  1714. res.append('0' * padding)
  1715. if number < 0:
  1716. res.append('-')
  1717. return ''.join(reversed(res or '0'))
  1718. # These are all essentially abbreviations
  1719. # These might wind up in a special abbreviations module
  1720. def _maketup(descr, val):
  1721. dt = dtype(descr)
  1722. # Place val in all scalar tuples:
  1723. fields = dt.fields
  1724. if fields is None:
  1725. return val
  1726. else:
  1727. res = [_maketup(fields[name][0], val) for name in dt.names]
  1728. return tuple(res)
  1729. def _identity_dispatcher(n, dtype=None, *, like=None):
  1730. return (like,)
  1731. @set_array_function_like_doc
  1732. @set_module('numpy')
  1733. def identity(n, dtype=None, *, like=None):
  1734. """
  1735. Return the identity array.
  1736. The identity array is a square array with ones on
  1737. the main diagonal.
  1738. Parameters
  1739. ----------
  1740. n : int
  1741. Number of rows (and columns) in `n` x `n` output.
  1742. dtype : data-type, optional
  1743. Data-type of the output. Defaults to ``float``.
  1744. ${ARRAY_FUNCTION_LIKE}
  1745. .. versionadded:: 1.20.0
  1746. Returns
  1747. -------
  1748. out : ndarray
  1749. `n` x `n` array with its main diagonal set to one,
  1750. and all other elements 0.
  1751. Examples
  1752. --------
  1753. >>> np.identity(3)
  1754. array([[1., 0., 0.],
  1755. [0., 1., 0.],
  1756. [0., 0., 1.]])
  1757. """
  1758. if like is not None:
  1759. return _identity_with_like(n, dtype=dtype, like=like)
  1760. from numpy import eye
  1761. return eye(n, dtype=dtype, like=like)
  1762. _identity_with_like = array_function_dispatch(
  1763. _identity_dispatcher
  1764. )(identity)
  1765. def _allclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
  1766. return (a, b)
  1767. @array_function_dispatch(_allclose_dispatcher)
  1768. def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
  1769. """
  1770. Returns True if two arrays are element-wise equal within a tolerance.
  1771. The tolerance values are positive, typically very small numbers. The
  1772. relative difference (`rtol` * abs(`b`)) and the absolute difference
  1773. `atol` are added together to compare against the absolute difference
  1774. between `a` and `b`.
  1775. NaNs are treated as equal if they are in the same place and if
  1776. ``equal_nan=True``. Infs are treated as equal if they are in the same
  1777. place and of the same sign in both arrays.
  1778. Parameters
  1779. ----------
  1780. a, b : array_like
  1781. Input arrays to compare.
  1782. rtol : float
  1783. The relative tolerance parameter (see Notes).
  1784. atol : float
  1785. The absolute tolerance parameter (see Notes).
  1786. equal_nan : bool
  1787. Whether to compare NaN's as equal. If True, NaN's in `a` will be
  1788. considered equal to NaN's in `b` in the output array.
  1789. .. versionadded:: 1.10.0
  1790. Returns
  1791. -------
  1792. allclose : bool
  1793. Returns True if the two arrays are equal within the given
  1794. tolerance; False otherwise.
  1795. See Also
  1796. --------
  1797. isclose, all, any, equal
  1798. Notes
  1799. -----
  1800. If the following equation is element-wise True, then allclose returns
  1801. True.
  1802. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
  1803. The above equation is not symmetric in `a` and `b`, so that
  1804. ``allclose(a, b)`` might be different from ``allclose(b, a)`` in
  1805. some rare cases.
  1806. The comparison of `a` and `b` uses standard broadcasting, which
  1807. means that `a` and `b` need not have the same shape in order for
  1808. ``allclose(a, b)`` to evaluate to True. The same is true for
  1809. `equal` but not `array_equal`.
  1810. `allclose` is not defined for non-numeric data types.
  1811. Examples
  1812. --------
  1813. >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
  1814. False
  1815. >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
  1816. True
  1817. >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
  1818. False
  1819. >>> np.allclose([1.0, np.nan], [1.0, np.nan])
  1820. False
  1821. >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
  1822. True
  1823. """
  1824. res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
  1825. return bool(res)
  1826. def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
  1827. return (a, b)
  1828. @array_function_dispatch(_isclose_dispatcher)
  1829. def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
  1830. """
  1831. Returns a boolean array where two arrays are element-wise equal within a
  1832. tolerance.
  1833. The tolerance values are positive, typically very small numbers. The
  1834. relative difference (`rtol` * abs(`b`)) and the absolute difference
  1835. `atol` are added together to compare against the absolute difference
  1836. between `a` and `b`.
  1837. .. warning:: The default `atol` is not appropriate for comparing numbers
  1838. that are much smaller than one (see Notes).
  1839. Parameters
  1840. ----------
  1841. a, b : array_like
  1842. Input arrays to compare.
  1843. rtol : float
  1844. The relative tolerance parameter (see Notes).
  1845. atol : float
  1846. The absolute tolerance parameter (see Notes).
  1847. equal_nan : bool
  1848. Whether to compare NaN's as equal. If True, NaN's in `a` will be
  1849. considered equal to NaN's in `b` in the output array.
  1850. Returns
  1851. -------
  1852. y : array_like
  1853. Returns a boolean array of where `a` and `b` are equal within the
  1854. given tolerance. If both `a` and `b` are scalars, returns a single
  1855. boolean value.
  1856. See Also
  1857. --------
  1858. allclose
  1859. math.isclose
  1860. Notes
  1861. -----
  1862. .. versionadded:: 1.7.0
  1863. For finite values, isclose uses the following equation to test whether
  1864. two floating point values are equivalent.
  1865. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
  1866. Unlike the built-in `math.isclose`, the above equation is not symmetric
  1867. in `a` and `b` -- it assumes `b` is the reference value -- so that
  1868. `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
  1869. the default value of atol is not zero, and is used to determine what
  1870. small values should be considered close to zero. The default value is
  1871. appropriate for expected values of order unity: if the expected values
  1872. are significantly smaller than one, it can result in false positives.
  1873. `atol` should be carefully selected for the use case at hand. A zero value
  1874. for `atol` will result in `False` if either `a` or `b` is zero.
  1875. `isclose` is not defined for non-numeric data types.
  1876. Examples
  1877. --------
  1878. >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
  1879. array([ True, False])
  1880. >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
  1881. array([ True, True])
  1882. >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
  1883. array([False, True])
  1884. >>> np.isclose([1.0, np.nan], [1.0, np.nan])
  1885. array([ True, False])
  1886. >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
  1887. array([ True, True])
  1888. >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
  1889. array([ True, False])
  1890. >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
  1891. array([False, False])
  1892. >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
  1893. array([ True, True])
  1894. >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
  1895. array([False, True])
  1896. """
  1897. def within_tol(x, y, atol, rtol):
  1898. with errstate(invalid='ignore'):
  1899. return less_equal(abs(x-y), atol + rtol * abs(y))
  1900. x = asanyarray(a)
  1901. y = asanyarray(b)
  1902. # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
  1903. # This will cause casting of x later. Also, make sure to allow subclasses
  1904. # (e.g., for numpy.ma).
  1905. # NOTE: We explicitly allow timedelta, which used to work. This could
  1906. # possibly be deprecated. See also gh-18286.
  1907. # timedelta works if `atol` is an integer or also a timedelta.
  1908. # Although, the default tolerances are unlikely to be useful
  1909. if y.dtype.kind != "m":
  1910. dt = multiarray.result_type(y, 1.)
  1911. y = asanyarray(y, dtype=dt)
  1912. xfin = isfinite(x)
  1913. yfin = isfinite(y)
  1914. if all(xfin) and all(yfin):
  1915. return within_tol(x, y, atol, rtol)
  1916. else:
  1917. finite = xfin & yfin
  1918. cond = zeros_like(finite, subok=True)
  1919. # Because we're using boolean indexing, x & y must be the same shape.
  1920. # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
  1921. # lib.stride_tricks, though, so we can't import it here.
  1922. x = x * ones_like(cond)
  1923. y = y * ones_like(cond)
  1924. # Avoid subtraction with infinite/nan values...
  1925. cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
  1926. # Check for equality of infinite values...
  1927. cond[~finite] = (x[~finite] == y[~finite])
  1928. if equal_nan:
  1929. # Make NaN == NaN
  1930. both_nan = isnan(x) & isnan(y)
  1931. # Needed to treat masked arrays correctly. = True would not work.
  1932. cond[both_nan] = both_nan[both_nan]
  1933. return cond[()] # Flatten 0d arrays to scalars
  1934. def _array_equal_dispatcher(a1, a2, equal_nan=None):
  1935. return (a1, a2)
  1936. @array_function_dispatch(_array_equal_dispatcher)
  1937. def array_equal(a1, a2, equal_nan=False):
  1938. """
  1939. True if two arrays have the same shape and elements, False otherwise.
  1940. Parameters
  1941. ----------
  1942. a1, a2 : array_like
  1943. Input arrays.
  1944. equal_nan : bool
  1945. Whether to compare NaN's as equal. If the dtype of a1 and a2 is
  1946. complex, values will be considered equal if either the real or the
  1947. imaginary component of a given value is ``nan``.
  1948. .. versionadded:: 1.19.0
  1949. Returns
  1950. -------
  1951. b : bool
  1952. Returns True if the arrays are equal.
  1953. See Also
  1954. --------
  1955. allclose: Returns True if two arrays are element-wise equal within a
  1956. tolerance.
  1957. array_equiv: Returns True if input arrays are shape consistent and all
  1958. elements equal.
  1959. Examples
  1960. --------
  1961. >>> np.array_equal([1, 2], [1, 2])
  1962. True
  1963. >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
  1964. True
  1965. >>> np.array_equal([1, 2], [1, 2, 3])
  1966. False
  1967. >>> np.array_equal([1, 2], [1, 4])
  1968. False
  1969. >>> a = np.array([1, np.nan])
  1970. >>> np.array_equal(a, a)
  1971. False
  1972. >>> np.array_equal(a, a, equal_nan=True)
  1973. True
  1974. When ``equal_nan`` is True, complex values with nan components are
  1975. considered equal if either the real *or* the imaginary components are nan.
  1976. >>> a = np.array([1 + 1j])
  1977. >>> b = a.copy()
  1978. >>> a.real = np.nan
  1979. >>> b.imag = np.nan
  1980. >>> np.array_equal(a, b, equal_nan=True)
  1981. True
  1982. """
  1983. try:
  1984. a1, a2 = asarray(a1), asarray(a2)
  1985. except Exception:
  1986. return False
  1987. if a1.shape != a2.shape:
  1988. return False
  1989. if not equal_nan:
  1990. return bool(asarray(a1 == a2).all())
  1991. # Handling NaN values if equal_nan is True
  1992. a1nan, a2nan = isnan(a1), isnan(a2)
  1993. # NaN's occur at different locations
  1994. if not (a1nan == a2nan).all():
  1995. return False
  1996. # Shapes of a1, a2 and masks are guaranteed to be consistent by this point
  1997. return bool(asarray(a1[~a1nan] == a2[~a1nan]).all())
  1998. def _array_equiv_dispatcher(a1, a2):
  1999. return (a1, a2)
  2000. @array_function_dispatch(_array_equiv_dispatcher)
  2001. def array_equiv(a1, a2):
  2002. """
  2003. Returns True if input arrays are shape consistent and all elements equal.
  2004. Shape consistent means they are either the same shape, or one input array
  2005. can be broadcasted to create the same shape as the other one.
  2006. Parameters
  2007. ----------
  2008. a1, a2 : array_like
  2009. Input arrays.
  2010. Returns
  2011. -------
  2012. out : bool
  2013. True if equivalent, False otherwise.
  2014. Examples
  2015. --------
  2016. >>> np.array_equiv([1, 2], [1, 2])
  2017. True
  2018. >>> np.array_equiv([1, 2], [1, 3])
  2019. False
  2020. Showing the shape equivalence:
  2021. >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
  2022. True
  2023. >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
  2024. False
  2025. >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
  2026. False
  2027. """
  2028. try:
  2029. a1, a2 = asarray(a1), asarray(a2)
  2030. except Exception:
  2031. return False
  2032. try:
  2033. multiarray.broadcast(a1, a2)
  2034. except Exception:
  2035. return False
  2036. return bool(asarray(a1 == a2).all())
  2037. Inf = inf = infty = Infinity = PINF
  2038. nan = NaN = NAN
  2039. False_ = bool_(False)
  2040. True_ = bool_(True)
  2041. def extend_all(module):
  2042. existing = set(__all__)
  2043. mall = getattr(module, '__all__')
  2044. for a in mall:
  2045. if a not in existing:
  2046. __all__.append(a)
  2047. from .umath import *
  2048. from .numerictypes import *
  2049. from . import fromnumeric
  2050. from .fromnumeric import *
  2051. from . import arrayprint
  2052. from .arrayprint import *
  2053. from . import _asarray
  2054. from ._asarray import *
  2055. from . import _ufunc_config
  2056. from ._ufunc_config import *
  2057. extend_all(fromnumeric)
  2058. extend_all(umath)
  2059. extend_all(numerictypes)
  2060. extend_all(arrayprint)
  2061. extend_all(_asarray)
  2062. extend_all(_ufunc_config)