numeric.py 75 KB

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