numeric.py 76 KB

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