numeric.py 75 KB

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