numeric.py 70 KB

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