numeric.py 80 KB

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