numeric.py 90 KB

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