numeric.py 73 KB

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