test_function_base.py 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561
  1. import operator
  2. import warnings
  3. import sys
  4. import decimal
  5. from fractions import Fraction
  6. import math
  7. import pytest
  8. import hypothesis
  9. from hypothesis.extra.numpy import arrays
  10. import hypothesis.strategies as st
  11. import numpy as np
  12. from numpy import ma
  13. from numpy.testing import (
  14. assert_, assert_equal, assert_array_equal, assert_almost_equal,
  15. assert_array_almost_equal, assert_raises, assert_allclose, IS_PYPY,
  16. assert_warns, assert_raises_regex, suppress_warnings, HAS_REFCOUNT,
  17. )
  18. import numpy.lib.function_base as nfb
  19. from numpy.random import rand
  20. from numpy.lib import (
  21. add_newdoc_ufunc, angle, average, bartlett, blackman, corrcoef, cov,
  22. delete, diff, digitize, extract, flipud, gradient, hamming, hanning,
  23. i0, insert, interp, kaiser, meshgrid, msort, piecewise, place, rot90,
  24. select, setxor1d, sinc, trapz, trim_zeros, unwrap, unique, vectorize
  25. )
  26. def get_mat(n):
  27. data = np.arange(n)
  28. data = np.add.outer(data, data)
  29. return data
  30. def _make_complex(real, imag):
  31. """
  32. Like real + 1j * imag, but behaves as expected when imag contains non-finite
  33. values
  34. """
  35. ret = np.zeros(np.broadcast(real, imag).shape, np.complex_)
  36. ret.real = real
  37. ret.imag = imag
  38. return ret
  39. class TestRot90:
  40. def test_basic(self):
  41. assert_raises(ValueError, rot90, np.ones(4))
  42. assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(0,1,2))
  43. assert_raises(ValueError, rot90, np.ones((2,2)), axes=(0,2))
  44. assert_raises(ValueError, rot90, np.ones((2,2)), axes=(1,1))
  45. assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(-2,1))
  46. a = [[0, 1, 2],
  47. [3, 4, 5]]
  48. b1 = [[2, 5],
  49. [1, 4],
  50. [0, 3]]
  51. b2 = [[5, 4, 3],
  52. [2, 1, 0]]
  53. b3 = [[3, 0],
  54. [4, 1],
  55. [5, 2]]
  56. b4 = [[0, 1, 2],
  57. [3, 4, 5]]
  58. for k in range(-3, 13, 4):
  59. assert_equal(rot90(a, k=k), b1)
  60. for k in range(-2, 13, 4):
  61. assert_equal(rot90(a, k=k), b2)
  62. for k in range(-1, 13, 4):
  63. assert_equal(rot90(a, k=k), b3)
  64. for k in range(0, 13, 4):
  65. assert_equal(rot90(a, k=k), b4)
  66. assert_equal(rot90(rot90(a, axes=(0,1)), axes=(1,0)), a)
  67. assert_equal(rot90(a, k=1, axes=(1,0)), rot90(a, k=-1, axes=(0,1)))
  68. def test_axes(self):
  69. a = np.ones((50, 40, 3))
  70. assert_equal(rot90(a).shape, (40, 50, 3))
  71. assert_equal(rot90(a, axes=(0,2)), rot90(a, axes=(0,-1)))
  72. assert_equal(rot90(a, axes=(1,2)), rot90(a, axes=(-2,-1)))
  73. def test_rotation_axes(self):
  74. a = np.arange(8).reshape((2,2,2))
  75. a_rot90_01 = [[[2, 3],
  76. [6, 7]],
  77. [[0, 1],
  78. [4, 5]]]
  79. a_rot90_12 = [[[1, 3],
  80. [0, 2]],
  81. [[5, 7],
  82. [4, 6]]]
  83. a_rot90_20 = [[[4, 0],
  84. [6, 2]],
  85. [[5, 1],
  86. [7, 3]]]
  87. a_rot90_10 = [[[4, 5],
  88. [0, 1]],
  89. [[6, 7],
  90. [2, 3]]]
  91. assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)
  92. assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)
  93. assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)
  94. for k in range(1,5):
  95. assert_equal(rot90(a, k=k, axes=(2, 0)),
  96. rot90(a_rot90_20, k=k-1, axes=(2, 0)))
  97. class TestFlip:
  98. def test_axes(self):
  99. assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)
  100. assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)
  101. assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)
  102. assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
  103. def test_basic_lr(self):
  104. a = get_mat(4)
  105. b = a[:, ::-1]
  106. assert_equal(np.flip(a, 1), b)
  107. a = [[0, 1, 2],
  108. [3, 4, 5]]
  109. b = [[2, 1, 0],
  110. [5, 4, 3]]
  111. assert_equal(np.flip(a, 1), b)
  112. def test_basic_ud(self):
  113. a = get_mat(4)
  114. b = a[::-1, :]
  115. assert_equal(np.flip(a, 0), b)
  116. a = [[0, 1, 2],
  117. [3, 4, 5]]
  118. b = [[3, 4, 5],
  119. [0, 1, 2]]
  120. assert_equal(np.flip(a, 0), b)
  121. def test_3d_swap_axis0(self):
  122. a = np.array([[[0, 1],
  123. [2, 3]],
  124. [[4, 5],
  125. [6, 7]]])
  126. b = np.array([[[4, 5],
  127. [6, 7]],
  128. [[0, 1],
  129. [2, 3]]])
  130. assert_equal(np.flip(a, 0), b)
  131. def test_3d_swap_axis1(self):
  132. a = np.array([[[0, 1],
  133. [2, 3]],
  134. [[4, 5],
  135. [6, 7]]])
  136. b = np.array([[[2, 3],
  137. [0, 1]],
  138. [[6, 7],
  139. [4, 5]]])
  140. assert_equal(np.flip(a, 1), b)
  141. def test_3d_swap_axis2(self):
  142. a = np.array([[[0, 1],
  143. [2, 3]],
  144. [[4, 5],
  145. [6, 7]]])
  146. b = np.array([[[1, 0],
  147. [3, 2]],
  148. [[5, 4],
  149. [7, 6]]])
  150. assert_equal(np.flip(a, 2), b)
  151. def test_4d(self):
  152. a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
  153. for i in range(a.ndim):
  154. assert_equal(np.flip(a, i),
  155. np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
  156. def test_default_axis(self):
  157. a = np.array([[1, 2, 3],
  158. [4, 5, 6]])
  159. b = np.array([[6, 5, 4],
  160. [3, 2, 1]])
  161. assert_equal(np.flip(a), b)
  162. def test_multiple_axes(self):
  163. a = np.array([[[0, 1],
  164. [2, 3]],
  165. [[4, 5],
  166. [6, 7]]])
  167. assert_equal(np.flip(a, axis=()), a)
  168. b = np.array([[[5, 4],
  169. [7, 6]],
  170. [[1, 0],
  171. [3, 2]]])
  172. assert_equal(np.flip(a, axis=(0, 2)), b)
  173. c = np.array([[[3, 2],
  174. [1, 0]],
  175. [[7, 6],
  176. [5, 4]]])
  177. assert_equal(np.flip(a, axis=(1, 2)), c)
  178. class TestAny:
  179. def test_basic(self):
  180. y1 = [0, 0, 1, 0]
  181. y2 = [0, 0, 0, 0]
  182. y3 = [1, 0, 1, 0]
  183. assert_(np.any(y1))
  184. assert_(np.any(y3))
  185. assert_(not np.any(y2))
  186. def test_nd(self):
  187. y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
  188. assert_(np.any(y1))
  189. assert_array_equal(np.sometrue(y1, axis=0), [1, 1, 0])
  190. assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1])
  191. class TestAll:
  192. def test_basic(self):
  193. y1 = [0, 1, 1, 0]
  194. y2 = [0, 0, 0, 0]
  195. y3 = [1, 1, 1, 1]
  196. assert_(not np.all(y1))
  197. assert_(np.all(y3))
  198. assert_(not np.all(y2))
  199. assert_(np.all(~np.array(y2)))
  200. def test_nd(self):
  201. y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
  202. assert_(not np.all(y1))
  203. assert_array_equal(np.alltrue(y1, axis=0), [0, 0, 1])
  204. assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1])
  205. class TestCopy:
  206. def test_basic(self):
  207. a = np.array([[1, 2], [3, 4]])
  208. a_copy = np.copy(a)
  209. assert_array_equal(a, a_copy)
  210. a_copy[0, 0] = 10
  211. assert_equal(a[0, 0], 1)
  212. assert_equal(a_copy[0, 0], 10)
  213. def test_order(self):
  214. # It turns out that people rely on np.copy() preserving order by
  215. # default; changing this broke scikit-learn:
  216. # github.com/scikit-learn/scikit-learn/commit/7842748cf777412c506a8c0ed28090711d3a3783 # noqa
  217. a = np.array([[1, 2], [3, 4]])
  218. assert_(a.flags.c_contiguous)
  219. assert_(not a.flags.f_contiguous)
  220. a_fort = np.array([[1, 2], [3, 4]], order="F")
  221. assert_(not a_fort.flags.c_contiguous)
  222. assert_(a_fort.flags.f_contiguous)
  223. a_copy = np.copy(a)
  224. assert_(a_copy.flags.c_contiguous)
  225. assert_(not a_copy.flags.f_contiguous)
  226. a_fort_copy = np.copy(a_fort)
  227. assert_(not a_fort_copy.flags.c_contiguous)
  228. assert_(a_fort_copy.flags.f_contiguous)
  229. def test_subok(self):
  230. mx = ma.ones(5)
  231. assert_(not ma.isMaskedArray(np.copy(mx, subok=False)))
  232. assert_(ma.isMaskedArray(np.copy(mx, subok=True)))
  233. # Default behavior
  234. assert_(not ma.isMaskedArray(np.copy(mx)))
  235. class TestAverage:
  236. def test_basic(self):
  237. y1 = np.array([1, 2, 3])
  238. assert_(average(y1, axis=0) == 2.)
  239. y2 = np.array([1., 2., 3.])
  240. assert_(average(y2, axis=0) == 2.)
  241. y3 = [0., 0., 0.]
  242. assert_(average(y3, axis=0) == 0.)
  243. y4 = np.ones((4, 4))
  244. y4[0, 1] = 0
  245. y4[1, 0] = 2
  246. assert_almost_equal(y4.mean(0), average(y4, 0))
  247. assert_almost_equal(y4.mean(1), average(y4, 1))
  248. y5 = rand(5, 5)
  249. assert_almost_equal(y5.mean(0), average(y5, 0))
  250. assert_almost_equal(y5.mean(1), average(y5, 1))
  251. def test_weights(self):
  252. y = np.arange(10)
  253. w = np.arange(10)
  254. actual = average(y, weights=w)
  255. desired = (np.arange(10) ** 2).sum() * 1. / np.arange(10).sum()
  256. assert_almost_equal(actual, desired)
  257. y1 = np.array([[1, 2, 3], [4, 5, 6]])
  258. w0 = [1, 2]
  259. actual = average(y1, weights=w0, axis=0)
  260. desired = np.array([3., 4., 5.])
  261. assert_almost_equal(actual, desired)
  262. w1 = [0, 0, 1]
  263. actual = average(y1, weights=w1, axis=1)
  264. desired = np.array([3., 6.])
  265. assert_almost_equal(actual, desired)
  266. # This should raise an error. Can we test for that ?
  267. # assert_equal(average(y1, weights=w1), 9./2.)
  268. # 2D Case
  269. w2 = [[0, 0, 1], [0, 0, 2]]
  270. desired = np.array([3., 6.])
  271. assert_array_equal(average(y1, weights=w2, axis=1), desired)
  272. assert_equal(average(y1, weights=w2), 5.)
  273. y3 = rand(5).astype(np.float32)
  274. w3 = rand(5).astype(np.float64)
  275. assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3))
  276. def test_returned(self):
  277. y = np.array([[1, 2, 3], [4, 5, 6]])
  278. # No weights
  279. avg, scl = average(y, returned=True)
  280. assert_equal(scl, 6.)
  281. avg, scl = average(y, 0, returned=True)
  282. assert_array_equal(scl, np.array([2., 2., 2.]))
  283. avg, scl = average(y, 1, returned=True)
  284. assert_array_equal(scl, np.array([3., 3.]))
  285. # With weights
  286. w0 = [1, 2]
  287. avg, scl = average(y, weights=w0, axis=0, returned=True)
  288. assert_array_equal(scl, np.array([3., 3., 3.]))
  289. w1 = [1, 2, 3]
  290. avg, scl = average(y, weights=w1, axis=1, returned=True)
  291. assert_array_equal(scl, np.array([6., 6.]))
  292. w2 = [[0, 0, 1], [1, 2, 3]]
  293. avg, scl = average(y, weights=w2, axis=1, returned=True)
  294. assert_array_equal(scl, np.array([1., 6.]))
  295. def test_subclasses(self):
  296. class subclass(np.ndarray):
  297. pass
  298. a = np.array([[1,2],[3,4]]).view(subclass)
  299. w = np.array([[1,2],[3,4]]).view(subclass)
  300. assert_equal(type(np.average(a)), subclass)
  301. assert_equal(type(np.average(a, weights=w)), subclass)
  302. def test_upcasting(self):
  303. typs = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),
  304. ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]
  305. for at, wt, rt in typs:
  306. a = np.array([[1,2],[3,4]], dtype=at)
  307. w = np.array([[1,2],[3,4]], dtype=wt)
  308. assert_equal(np.average(a, weights=w).dtype, np.dtype(rt))
  309. def test_object_dtype(self):
  310. a = np.array([decimal.Decimal(x) for x in range(10)])
  311. w = np.array([decimal.Decimal(1) for _ in range(10)])
  312. w /= w.sum()
  313. assert_almost_equal(a.mean(0), average(a, weights=w))
  314. class TestSelect:
  315. choices = [np.array([1, 2, 3]),
  316. np.array([4, 5, 6]),
  317. np.array([7, 8, 9])]
  318. conditions = [np.array([False, False, False]),
  319. np.array([False, True, False]),
  320. np.array([False, False, True])]
  321. def _select(self, cond, values, default=0):
  322. output = []
  323. for m in range(len(cond)):
  324. output += [V[m] for V, C in zip(values, cond) if C[m]] or [default]
  325. return output
  326. def test_basic(self):
  327. choices = self.choices
  328. conditions = self.conditions
  329. assert_array_equal(select(conditions, choices, default=15),
  330. self._select(conditions, choices, default=15))
  331. assert_equal(len(choices), 3)
  332. assert_equal(len(conditions), 3)
  333. def test_broadcasting(self):
  334. conditions = [np.array(True), np.array([False, True, False])]
  335. choices = [1, np.arange(12).reshape(4, 3)]
  336. assert_array_equal(select(conditions, choices), np.ones((4, 3)))
  337. # default can broadcast too:
  338. assert_equal(select([True], [0], default=[0]).shape, (1,))
  339. def test_return_dtype(self):
  340. assert_equal(select(self.conditions, self.choices, 1j).dtype,
  341. np.complex_)
  342. # But the conditions need to be stronger then the scalar default
  343. # if it is scalar.
  344. choices = [choice.astype(np.int8) for choice in self.choices]
  345. assert_equal(select(self.conditions, choices).dtype, np.int8)
  346. d = np.array([1, 2, 3, np.nan, 5, 7])
  347. m = np.isnan(d)
  348. assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0])
  349. def test_deprecated_empty(self):
  350. assert_raises(ValueError, select, [], [], 3j)
  351. assert_raises(ValueError, select, [], [])
  352. def test_non_bool_deprecation(self):
  353. choices = self.choices
  354. conditions = self.conditions[:]
  355. conditions[0] = conditions[0].astype(np.int_)
  356. assert_raises(TypeError, select, conditions, choices)
  357. conditions[0] = conditions[0].astype(np.uint8)
  358. assert_raises(TypeError, select, conditions, choices)
  359. assert_raises(TypeError, select, conditions, choices)
  360. def test_many_arguments(self):
  361. # This used to be limited by NPY_MAXARGS == 32
  362. conditions = [np.array([False])] * 100
  363. choices = [np.array([1])] * 100
  364. select(conditions, choices)
  365. class TestInsert:
  366. def test_basic(self):
  367. a = [1, 2, 3]
  368. assert_equal(insert(a, 0, 1), [1, 1, 2, 3])
  369. assert_equal(insert(a, 3, 1), [1, 2, 3, 1])
  370. assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  371. assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  372. assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9])
  373. assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3])
  374. assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9])
  375. b = np.array([0, 1], dtype=np.float64)
  376. assert_equal(insert(b, 0, b[0]), [0., 0., 1.])
  377. assert_equal(insert(b, [], []), b)
  378. # Bools will be treated differently in the future:
  379. # assert_equal(insert(a, np.array([True]*4), 9), [9, 1, 9, 2, 9, 3, 9])
  380. with warnings.catch_warnings(record=True) as w:
  381. warnings.filterwarnings('always', '', FutureWarning)
  382. assert_equal(
  383. insert(a, np.array([True] * 4), 9), [1, 9, 9, 9, 9, 2, 3])
  384. assert_(w[0].category is FutureWarning)
  385. def test_multidim(self):
  386. a = [[1, 1, 1]]
  387. r = [[2, 2, 2],
  388. [1, 1, 1]]
  389. assert_equal(insert(a, 0, [1]), [1, 1, 1, 1])
  390. assert_equal(insert(a, 0, [2, 2, 2], axis=0), r)
  391. assert_equal(insert(a, 0, 2, axis=0), r)
  392. assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]])
  393. a = np.array([[1, 1], [2, 2], [3, 3]])
  394. b = np.arange(1, 4).repeat(3).reshape(3, 3)
  395. c = np.concatenate(
  396. (a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T,
  397. a[:, 1:2]), axis=1)
  398. assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b)
  399. assert_equal(insert(a, [1], [1, 2, 3], axis=1), c)
  400. # scalars behave differently, in this case exactly opposite:
  401. assert_equal(insert(a, 1, [1, 2, 3], axis=1), b)
  402. assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c)
  403. a = np.arange(4).reshape(2, 2)
  404. assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a)
  405. assert_equal(insert(a[:1,:], 1, a[1,:], axis=0), a)
  406. # negative axis value
  407. a = np.arange(24).reshape((2, 3, 4))
  408. assert_equal(insert(a, 1, a[:,:, 3], axis=-1),
  409. insert(a, 1, a[:,:, 3], axis=2))
  410. assert_equal(insert(a, 1, a[:, 2,:], axis=-2),
  411. insert(a, 1, a[:, 2,:], axis=1))
  412. # invalid axis value
  413. assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=3)
  414. assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=-4)
  415. # negative axis value
  416. a = np.arange(24).reshape((2, 3, 4))
  417. assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
  418. insert(a, 1, a[:, :, 3], axis=2))
  419. assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
  420. insert(a, 1, a[:, 2, :], axis=1))
  421. def test_0d(self):
  422. a = np.array(1)
  423. with pytest.raises(np.AxisError):
  424. insert(a, [], 2, axis=0)
  425. with pytest.raises(TypeError):
  426. insert(a, [], 2, axis="nonsense")
  427. def test_subclass(self):
  428. class SubClass(np.ndarray):
  429. pass
  430. a = np.arange(10).view(SubClass)
  431. assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  432. assert_(isinstance(np.insert(a, [], []), SubClass))
  433. assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass))
  434. assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass))
  435. assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass))
  436. # This is an error in the future:
  437. a = np.array(1).view(SubClass)
  438. assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  439. def test_index_array_copied(self):
  440. x = np.array([1, 1, 1])
  441. np.insert([0, 1, 2], x, [3, 4, 5])
  442. assert_equal(x, np.array([1, 1, 1]))
  443. def test_structured_array(self):
  444. a = np.array([(1, 'a'), (2, 'b'), (3, 'c')],
  445. dtype=[('foo', 'i'), ('bar', 'a1')])
  446. val = (4, 'd')
  447. b = np.insert(a, 0, val)
  448. assert_array_equal(b[0], np.array(val, dtype=b.dtype))
  449. val = [(4, 'd')] * 2
  450. b = np.insert(a, [0, 2], val)
  451. assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))
  452. def test_index_floats(self):
  453. with pytest.raises(IndexError):
  454. np.insert([0, 1, 2], np.array([1.0, 2.0]), [10, 20])
  455. with pytest.raises(IndexError):
  456. np.insert([0, 1, 2], np.array([], dtype=float), [])
  457. class TestAmax:
  458. def test_basic(self):
  459. a = [3, 4, 5, 10, -3, -5, 6.0]
  460. assert_equal(np.amax(a), 10.0)
  461. b = [[3, 6.0, 9.0],
  462. [4, 10.0, 5.0],
  463. [8, 3.0, 2.0]]
  464. assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0])
  465. assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
  466. class TestAmin:
  467. def test_basic(self):
  468. a = [3, 4, 5, 10, -3, -5, 6.0]
  469. assert_equal(np.amin(a), -5.0)
  470. b = [[3, 6.0, 9.0],
  471. [4, 10.0, 5.0],
  472. [8, 3.0, 2.0]]
  473. assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])
  474. assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
  475. class TestPtp:
  476. def test_basic(self):
  477. a = np.array([3, 4, 5, 10, -3, -5, 6.0])
  478. assert_equal(a.ptp(axis=0), 15.0)
  479. b = np.array([[3, 6.0, 9.0],
  480. [4, 10.0, 5.0],
  481. [8, 3.0, 2.0]])
  482. assert_equal(b.ptp(axis=0), [5.0, 7.0, 7.0])
  483. assert_equal(b.ptp(axis=-1), [6.0, 6.0, 6.0])
  484. assert_equal(b.ptp(axis=0, keepdims=True), [[5.0, 7.0, 7.0]])
  485. assert_equal(b.ptp(axis=(0,1), keepdims=True), [[8.0]])
  486. class TestCumsum:
  487. def test_basic(self):
  488. ba = [1, 2, 10, 11, 6, 5, 4]
  489. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  490. for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,
  491. np.uint32, np.float32, np.float64, np.complex64,
  492. np.complex128]:
  493. a = np.array(ba, ctype)
  494. a2 = np.array(ba2, ctype)
  495. tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
  496. assert_array_equal(np.cumsum(a, axis=0), tgt)
  497. tgt = np.array(
  498. [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
  499. assert_array_equal(np.cumsum(a2, axis=0), tgt)
  500. tgt = np.array(
  501. [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
  502. assert_array_equal(np.cumsum(a2, axis=1), tgt)
  503. class TestProd:
  504. def test_basic(self):
  505. ba = [1, 2, 10, 11, 6, 5, 4]
  506. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  507. for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  508. np.float32, np.float64, np.complex64, np.complex128]:
  509. a = np.array(ba, ctype)
  510. a2 = np.array(ba2, ctype)
  511. if ctype in ['1', 'b']:
  512. assert_raises(ArithmeticError, np.prod, a)
  513. assert_raises(ArithmeticError, np.prod, a2, 1)
  514. else:
  515. assert_equal(a.prod(axis=0), 26400)
  516. assert_array_equal(a2.prod(axis=0),
  517. np.array([50, 36, 84, 180], ctype))
  518. assert_array_equal(a2.prod(axis=-1),
  519. np.array([24, 1890, 600], ctype))
  520. class TestCumprod:
  521. def test_basic(self):
  522. ba = [1, 2, 10, 11, 6, 5, 4]
  523. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  524. for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  525. np.float32, np.float64, np.complex64, np.complex128]:
  526. a = np.array(ba, ctype)
  527. a2 = np.array(ba2, ctype)
  528. if ctype in ['1', 'b']:
  529. assert_raises(ArithmeticError, np.cumprod, a)
  530. assert_raises(ArithmeticError, np.cumprod, a2, 1)
  531. assert_raises(ArithmeticError, np.cumprod, a)
  532. else:
  533. assert_array_equal(np.cumprod(a, axis=-1),
  534. np.array([1, 2, 20, 220,
  535. 1320, 6600, 26400], ctype))
  536. assert_array_equal(np.cumprod(a2, axis=0),
  537. np.array([[1, 2, 3, 4],
  538. [5, 12, 21, 36],
  539. [50, 36, 84, 180]], ctype))
  540. assert_array_equal(np.cumprod(a2, axis=-1),
  541. np.array([[1, 2, 6, 24],
  542. [5, 30, 210, 1890],
  543. [10, 30, 120, 600]], ctype))
  544. class TestDiff:
  545. def test_basic(self):
  546. x = [1, 4, 6, 7, 12]
  547. out = np.array([3, 2, 1, 5])
  548. out2 = np.array([-1, -1, 4])
  549. out3 = np.array([0, 5])
  550. assert_array_equal(diff(x), out)
  551. assert_array_equal(diff(x, n=2), out2)
  552. assert_array_equal(diff(x, n=3), out3)
  553. x = [1.1, 2.2, 3.0, -0.2, -0.1]
  554. out = np.array([1.1, 0.8, -3.2, 0.1])
  555. assert_almost_equal(diff(x), out)
  556. x = [True, True, False, False]
  557. out = np.array([False, True, False])
  558. out2 = np.array([True, True])
  559. assert_array_equal(diff(x), out)
  560. assert_array_equal(diff(x, n=2), out2)
  561. def test_axis(self):
  562. x = np.zeros((10, 20, 30))
  563. x[:, 1::2, :] = 1
  564. exp = np.ones((10, 19, 30))
  565. exp[:, 1::2, :] = -1
  566. assert_array_equal(diff(x), np.zeros((10, 20, 29)))
  567. assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29)))
  568. assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30)))
  569. assert_array_equal(diff(x, axis=1), exp)
  570. assert_array_equal(diff(x, axis=-2), exp)
  571. assert_raises(np.AxisError, diff, x, axis=3)
  572. assert_raises(np.AxisError, diff, x, axis=-4)
  573. x = np.array(1.11111111111, np.float64)
  574. assert_raises(ValueError, diff, x)
  575. def test_nd(self):
  576. x = 20 * rand(10, 20, 30)
  577. out1 = x[:, :, 1:] - x[:, :, :-1]
  578. out2 = out1[:, :, 1:] - out1[:, :, :-1]
  579. out3 = x[1:, :, :] - x[:-1, :, :]
  580. out4 = out3[1:, :, :] - out3[:-1, :, :]
  581. assert_array_equal(diff(x), out1)
  582. assert_array_equal(diff(x, n=2), out2)
  583. assert_array_equal(diff(x, axis=0), out3)
  584. assert_array_equal(diff(x, n=2, axis=0), out4)
  585. def test_n(self):
  586. x = list(range(3))
  587. assert_raises(ValueError, diff, x, n=-1)
  588. output = [diff(x, n=n) for n in range(1, 5)]
  589. expected = [[1, 1], [0], [], []]
  590. assert_(diff(x, n=0) is x)
  591. for n, (expected, out) in enumerate(zip(expected, output), start=1):
  592. assert_(type(out) is np.ndarray)
  593. assert_array_equal(out, expected)
  594. assert_equal(out.dtype, np.int_)
  595. assert_equal(len(out), max(0, len(x) - n))
  596. def test_times(self):
  597. x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
  598. expected = [
  599. np.array([1, 1], dtype='timedelta64[D]'),
  600. np.array([0], dtype='timedelta64[D]'),
  601. ]
  602. expected.extend([np.array([], dtype='timedelta64[D]')] * 3)
  603. for n, exp in enumerate(expected, start=1):
  604. out = diff(x, n=n)
  605. assert_array_equal(out, exp)
  606. assert_equal(out.dtype, exp.dtype)
  607. def test_subclass(self):
  608. x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
  609. mask=[[False, False], [True, False],
  610. [False, True], [True, True], [False, False]])
  611. out = diff(x)
  612. assert_array_equal(out.data, [[1], [1], [1], [1], [1]])
  613. assert_array_equal(out.mask, [[False], [True],
  614. [True], [True], [False]])
  615. assert_(type(out) is type(x))
  616. out3 = diff(x, n=3)
  617. assert_array_equal(out3.data, [[], [], [], [], []])
  618. assert_array_equal(out3.mask, [[], [], [], [], []])
  619. assert_(type(out3) is type(x))
  620. def test_prepend(self):
  621. x = np.arange(5) + 1
  622. assert_array_equal(diff(x, prepend=0), np.ones(5))
  623. assert_array_equal(diff(x, prepend=[0]), np.ones(5))
  624. assert_array_equal(np.cumsum(np.diff(x, prepend=0)), x)
  625. assert_array_equal(diff(x, prepend=[-1, 0]), np.ones(6))
  626. x = np.arange(4).reshape(2, 2)
  627. result = np.diff(x, axis=1, prepend=0)
  628. expected = [[0, 1], [2, 1]]
  629. assert_array_equal(result, expected)
  630. result = np.diff(x, axis=1, prepend=[[0], [0]])
  631. assert_array_equal(result, expected)
  632. result = np.diff(x, axis=0, prepend=0)
  633. expected = [[0, 1], [2, 2]]
  634. assert_array_equal(result, expected)
  635. result = np.diff(x, axis=0, prepend=[[0, 0]])
  636. assert_array_equal(result, expected)
  637. assert_raises(ValueError, np.diff, x, prepend=np.zeros((3,3)))
  638. assert_raises(np.AxisError, diff, x, prepend=0, axis=3)
  639. def test_append(self):
  640. x = np.arange(5)
  641. result = diff(x, append=0)
  642. expected = [1, 1, 1, 1, -4]
  643. assert_array_equal(result, expected)
  644. result = diff(x, append=[0])
  645. assert_array_equal(result, expected)
  646. result = diff(x, append=[0, 2])
  647. expected = expected + [2]
  648. assert_array_equal(result, expected)
  649. x = np.arange(4).reshape(2, 2)
  650. result = np.diff(x, axis=1, append=0)
  651. expected = [[1, -1], [1, -3]]
  652. assert_array_equal(result, expected)
  653. result = np.diff(x, axis=1, append=[[0], [0]])
  654. assert_array_equal(result, expected)
  655. result = np.diff(x, axis=0, append=0)
  656. expected = [[2, 2], [-2, -3]]
  657. assert_array_equal(result, expected)
  658. result = np.diff(x, axis=0, append=[[0, 0]])
  659. assert_array_equal(result, expected)
  660. assert_raises(ValueError, np.diff, x, append=np.zeros((3,3)))
  661. assert_raises(np.AxisError, diff, x, append=0, axis=3)
  662. class TestDelete:
  663. def setup(self):
  664. self.a = np.arange(5)
  665. self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)
  666. def _check_inverse_of_slicing(self, indices):
  667. a_del = delete(self.a, indices)
  668. nd_a_del = delete(self.nd_a, indices, axis=1)
  669. msg = 'Delete failed for obj: %r' % indices
  670. assert_array_equal(setxor1d(a_del, self.a[indices, ]), self.a,
  671. err_msg=msg)
  672. xor = setxor1d(nd_a_del[0,:, 0], self.nd_a[0, indices, 0])
  673. assert_array_equal(xor, self.nd_a[0,:, 0], err_msg=msg)
  674. def test_slices(self):
  675. lims = [-6, -2, 0, 1, 2, 4, 5]
  676. steps = [-3, -1, 1, 3]
  677. for start in lims:
  678. for stop in lims:
  679. for step in steps:
  680. s = slice(start, stop, step)
  681. self._check_inverse_of_slicing(s)
  682. def test_fancy(self):
  683. self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]]))
  684. with pytest.raises(IndexError):
  685. delete(self.a, [100])
  686. with pytest.raises(IndexError):
  687. delete(self.a, [-100])
  688. self._check_inverse_of_slicing([0, -1, 2, 2])
  689. self._check_inverse_of_slicing([True, False, False, True, False])
  690. # not legal, indexing with these would change the dimension
  691. with pytest.raises(ValueError):
  692. delete(self.a, True)
  693. with pytest.raises(ValueError):
  694. delete(self.a, False)
  695. # not enough items
  696. with pytest.raises(ValueError):
  697. delete(self.a, [False]*4)
  698. def test_single(self):
  699. self._check_inverse_of_slicing(0)
  700. self._check_inverse_of_slicing(-4)
  701. def test_0d(self):
  702. a = np.array(1)
  703. with pytest.raises(np.AxisError):
  704. delete(a, [], axis=0)
  705. with pytest.raises(TypeError):
  706. delete(a, [], axis="nonsense")
  707. def test_subclass(self):
  708. class SubClass(np.ndarray):
  709. pass
  710. a = self.a.view(SubClass)
  711. assert_(isinstance(delete(a, 0), SubClass))
  712. assert_(isinstance(delete(a, []), SubClass))
  713. assert_(isinstance(delete(a, [0, 1]), SubClass))
  714. assert_(isinstance(delete(a, slice(1, 2)), SubClass))
  715. assert_(isinstance(delete(a, slice(1, -2)), SubClass))
  716. def test_array_order_preserve(self):
  717. # See gh-7113
  718. k = np.arange(10).reshape(2, 5, order='F')
  719. m = delete(k, slice(60, None), axis=1)
  720. # 'k' is Fortran ordered, and 'm' should have the
  721. # same ordering as 'k' and NOT become C ordered
  722. assert_equal(m.flags.c_contiguous, k.flags.c_contiguous)
  723. assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)
  724. def test_index_floats(self):
  725. with pytest.raises(IndexError):
  726. np.delete([0, 1, 2], np.array([1.0, 2.0]))
  727. with pytest.raises(IndexError):
  728. np.delete([0, 1, 2], np.array([], dtype=float))
  729. class TestGradient:
  730. def test_basic(self):
  731. v = [[1, 1], [3, 4]]
  732. x = np.array(v)
  733. dx = [np.array([[2., 3.], [2., 3.]]),
  734. np.array([[0., 0.], [1., 1.]])]
  735. assert_array_equal(gradient(x), dx)
  736. assert_array_equal(gradient(v), dx)
  737. def test_args(self):
  738. dx = np.cumsum(np.ones(5))
  739. dx_uneven = [1., 2., 5., 9., 11.]
  740. f_2d = np.arange(25).reshape(5, 5)
  741. # distances must be scalars or have size equal to gradient[axis]
  742. gradient(np.arange(5), 3.)
  743. gradient(np.arange(5), np.array(3.))
  744. gradient(np.arange(5), dx)
  745. # dy is set equal to dx because scalar
  746. gradient(f_2d, 1.5)
  747. gradient(f_2d, np.array(1.5))
  748. gradient(f_2d, dx_uneven, dx_uneven)
  749. # mix between even and uneven spaces and
  750. # mix between scalar and vector
  751. gradient(f_2d, dx, 2)
  752. # 2D but axis specified
  753. gradient(f_2d, dx, axis=1)
  754. # 2d coordinate arguments are not yet allowed
  755. assert_raises_regex(ValueError, '.*scalars or 1d',
  756. gradient, f_2d, np.stack([dx]*2, axis=-1), 1)
  757. def test_badargs(self):
  758. f_2d = np.arange(25).reshape(5, 5)
  759. x = np.cumsum(np.ones(5))
  760. # wrong sizes
  761. assert_raises(ValueError, gradient, f_2d, x, np.ones(2))
  762. assert_raises(ValueError, gradient, f_2d, 1, np.ones(2))
  763. assert_raises(ValueError, gradient, f_2d, np.ones(2), np.ones(2))
  764. # wrong number of arguments
  765. assert_raises(TypeError, gradient, f_2d, x)
  766. assert_raises(TypeError, gradient, f_2d, x, axis=(0,1))
  767. assert_raises(TypeError, gradient, f_2d, x, x, x)
  768. assert_raises(TypeError, gradient, f_2d, 1, 1, 1)
  769. assert_raises(TypeError, gradient, f_2d, x, x, axis=1)
  770. assert_raises(TypeError, gradient, f_2d, 1, 1, axis=1)
  771. def test_datetime64(self):
  772. # Make sure gradient() can handle special types like datetime64
  773. x = np.array(
  774. ['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',
  775. '1910-10-12', '1910-12-12', '1912-12-12'],
  776. dtype='datetime64[D]')
  777. dx = np.array(
  778. [-5, -3, 0, 31, 61, 396, 731],
  779. dtype='timedelta64[D]')
  780. assert_array_equal(gradient(x), dx)
  781. assert_(dx.dtype == np.dtype('timedelta64[D]'))
  782. def test_masked(self):
  783. # Make sure that gradient supports subclasses like masked arrays
  784. x = np.ma.array([[1, 1], [3, 4]],
  785. mask=[[False, False], [False, False]])
  786. out = gradient(x)[0]
  787. assert_equal(type(out), type(x))
  788. # And make sure that the output and input don't have aliased mask
  789. # arrays
  790. assert_(x._mask is not out._mask)
  791. # Also check that edge_order=2 doesn't alter the original mask
  792. x2 = np.ma.arange(5)
  793. x2[2] = np.ma.masked
  794. np.gradient(x2, edge_order=2)
  795. assert_array_equal(x2.mask, [False, False, True, False, False])
  796. def test_second_order_accurate(self):
  797. # Testing that the relative numerical error is less that 3% for
  798. # this example problem. This corresponds to second order
  799. # accurate finite differences for all interior and boundary
  800. # points.
  801. x = np.linspace(0, 1, 10)
  802. dx = x[1] - x[0]
  803. y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  804. analytical = 6 * x ** 2 + 8 * x + 2
  805. num_error = np.abs((np.gradient(y, dx, edge_order=2) / analytical) - 1)
  806. assert_(np.all(num_error < 0.03) == True)
  807. # test with unevenly spaced
  808. np.random.seed(0)
  809. x = np.sort(np.random.random(10))
  810. y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  811. analytical = 6 * x ** 2 + 8 * x + 2
  812. num_error = np.abs((np.gradient(y, x, edge_order=2) / analytical) - 1)
  813. assert_(np.all(num_error < 0.03) == True)
  814. def test_spacing(self):
  815. f = np.array([0, 2., 3., 4., 5., 5.])
  816. f = np.tile(f, (6,1)) + f.reshape(-1, 1)
  817. x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])
  818. x_even = np.arange(6.)
  819. fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6,1))
  820. fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6,1))
  821. fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6,1))
  822. fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6,1))
  823. # evenly spaced
  824. for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:
  825. res1 = gradient(f, 1., axis=(0,1), edge_order=edge_order)
  826. res2 = gradient(f, x_even, x_even,
  827. axis=(0,1), edge_order=edge_order)
  828. res3 = gradient(f, x_even, x_even,
  829. axis=None, edge_order=edge_order)
  830. assert_array_equal(res1, res2)
  831. assert_array_equal(res2, res3)
  832. assert_almost_equal(res1[0], exp_res.T)
  833. assert_almost_equal(res1[1], exp_res)
  834. res1 = gradient(f, 1., axis=0, edge_order=edge_order)
  835. res2 = gradient(f, x_even, axis=0, edge_order=edge_order)
  836. assert_(res1.shape == res2.shape)
  837. assert_almost_equal(res2, exp_res.T)
  838. res1 = gradient(f, 1., axis=1, edge_order=edge_order)
  839. res2 = gradient(f, x_even, axis=1, edge_order=edge_order)
  840. assert_(res1.shape == res2.shape)
  841. assert_array_equal(res2, exp_res)
  842. # unevenly spaced
  843. for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:
  844. res1 = gradient(f, x_uneven, x_uneven,
  845. axis=(0,1), edge_order=edge_order)
  846. res2 = gradient(f, x_uneven, x_uneven,
  847. axis=None, edge_order=edge_order)
  848. assert_array_equal(res1, res2)
  849. assert_almost_equal(res1[0], exp_res.T)
  850. assert_almost_equal(res1[1], exp_res)
  851. res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)
  852. assert_almost_equal(res1, exp_res.T)
  853. res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)
  854. assert_almost_equal(res1, exp_res)
  855. # mixed
  856. res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=1)
  857. res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=1)
  858. assert_array_equal(res1[0], res2[1])
  859. assert_array_equal(res1[1], res2[0])
  860. assert_almost_equal(res1[0], fdx_even_ord1.T)
  861. assert_almost_equal(res1[1], fdx_uneven_ord1)
  862. res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=2)
  863. res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=2)
  864. assert_array_equal(res1[0], res2[1])
  865. assert_array_equal(res1[1], res2[0])
  866. assert_almost_equal(res1[0], fdx_even_ord2.T)
  867. assert_almost_equal(res1[1], fdx_uneven_ord2)
  868. def test_specific_axes(self):
  869. # Testing that gradient can work on a given axis only
  870. v = [[1, 1], [3, 4]]
  871. x = np.array(v)
  872. dx = [np.array([[2., 3.], [2., 3.]]),
  873. np.array([[0., 0.], [1., 1.]])]
  874. assert_array_equal(gradient(x, axis=0), dx[0])
  875. assert_array_equal(gradient(x, axis=1), dx[1])
  876. assert_array_equal(gradient(x, axis=-1), dx[1])
  877. assert_array_equal(gradient(x, axis=(1, 0)), [dx[1], dx[0]])
  878. # test axis=None which means all axes
  879. assert_almost_equal(gradient(x, axis=None), [dx[0], dx[1]])
  880. # and is the same as no axis keyword given
  881. assert_almost_equal(gradient(x, axis=None), gradient(x))
  882. # test vararg order
  883. assert_array_equal(gradient(x, 2, 3, axis=(1, 0)),
  884. [dx[1]/2.0, dx[0]/3.0])
  885. # test maximal number of varargs
  886. assert_raises(TypeError, gradient, x, 1, 2, axis=1)
  887. assert_raises(np.AxisError, gradient, x, axis=3)
  888. assert_raises(np.AxisError, gradient, x, axis=-3)
  889. # assert_raises(TypeError, gradient, x, axis=[1,])
  890. def test_timedelta64(self):
  891. # Make sure gradient() can handle special types like timedelta64
  892. x = np.array(
  893. [-5, -3, 10, 12, 61, 321, 300],
  894. dtype='timedelta64[D]')
  895. dx = np.array(
  896. [2, 7, 7, 25, 154, 119, -21],
  897. dtype='timedelta64[D]')
  898. assert_array_equal(gradient(x), dx)
  899. assert_(dx.dtype == np.dtype('timedelta64[D]'))
  900. def test_inexact_dtypes(self):
  901. for dt in [np.float16, np.float32, np.float64]:
  902. # dtypes should not be promoted in a different way to what diff does
  903. x = np.array([1, 2, 3], dtype=dt)
  904. assert_equal(gradient(x).dtype, np.diff(x).dtype)
  905. def test_values(self):
  906. # needs at least 2 points for edge_order ==1
  907. gradient(np.arange(2), edge_order=1)
  908. # needs at least 3 points for edge_order ==1
  909. gradient(np.arange(3), edge_order=2)
  910. assert_raises(ValueError, gradient, np.arange(0), edge_order=1)
  911. assert_raises(ValueError, gradient, np.arange(0), edge_order=2)
  912. assert_raises(ValueError, gradient, np.arange(1), edge_order=1)
  913. assert_raises(ValueError, gradient, np.arange(1), edge_order=2)
  914. assert_raises(ValueError, gradient, np.arange(2), edge_order=2)
  915. @pytest.mark.parametrize('f_dtype', [np.uint8, np.uint16,
  916. np.uint32, np.uint64])
  917. def test_f_decreasing_unsigned_int(self, f_dtype):
  918. f = np.array([5, 4, 3, 2, 1], dtype=f_dtype)
  919. g = gradient(f)
  920. assert_array_equal(g, [-1]*len(f))
  921. @pytest.mark.parametrize('f_dtype', [np.int8, np.int16,
  922. np.int32, np.int64])
  923. def test_f_signed_int_big_jump(self, f_dtype):
  924. maxint = np.iinfo(f_dtype).max
  925. x = np.array([1, 3])
  926. f = np.array([-1, maxint], dtype=f_dtype)
  927. dfdx = gradient(f, x)
  928. assert_array_equal(dfdx, [(maxint + 1) // 2]*2)
  929. @pytest.mark.parametrize('x_dtype', [np.uint8, np.uint16,
  930. np.uint32, np.uint64])
  931. def test_x_decreasing_unsigned(self, x_dtype):
  932. x = np.array([3, 2, 1], dtype=x_dtype)
  933. f = np.array([0, 2, 4])
  934. dfdx = gradient(f, x)
  935. assert_array_equal(dfdx, [-2]*len(x))
  936. @pytest.mark.parametrize('x_dtype', [np.int8, np.int16,
  937. np.int32, np.int64])
  938. def test_x_signed_int_big_jump(self, x_dtype):
  939. minint = np.iinfo(x_dtype).min
  940. maxint = np.iinfo(x_dtype).max
  941. x = np.array([-1, maxint], dtype=x_dtype)
  942. f = np.array([minint // 2, 0])
  943. dfdx = gradient(f, x)
  944. assert_array_equal(dfdx, [0.5, 0.5])
  945. class TestAngle:
  946. def test_basic(self):
  947. x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
  948. 1, 1j, -1, -1j, 1 - 3j, -1 + 3j]
  949. y = angle(x)
  950. yo = [
  951. np.arctan(3.0 / 1.0),
  952. np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,
  953. -np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)]
  954. z = angle(x, deg=True)
  955. zo = np.array(yo) * 180 / np.pi
  956. assert_array_almost_equal(y, yo, 11)
  957. assert_array_almost_equal(z, zo, 11)
  958. def test_subclass(self):
  959. x = np.ma.array([1 + 3j, 1, np.sqrt(2)/2 * (1 + 1j)])
  960. x[1] = np.ma.masked
  961. expected = np.ma.array([np.arctan(3.0 / 1.0), 0, np.arctan(1.0)])
  962. expected[1] = np.ma.masked
  963. actual = angle(x)
  964. assert_equal(type(actual), type(expected))
  965. assert_equal(actual.mask, expected.mask)
  966. assert_equal(actual, expected)
  967. class TestTrimZeros:
  968. a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
  969. b = a.astype(float)
  970. c = a.astype(complex)
  971. d = a.astype(object)
  972. def values(self):
  973. attr_names = ('a', 'b', 'c', 'd')
  974. return (getattr(self, name) for name in attr_names)
  975. def test_basic(self):
  976. slc = np.s_[2:-1]
  977. for arr in self.values():
  978. res = trim_zeros(arr)
  979. assert_array_equal(res, arr[slc])
  980. def test_leading_skip(self):
  981. slc = np.s_[:-1]
  982. for arr in self.values():
  983. res = trim_zeros(arr, trim='b')
  984. assert_array_equal(res, arr[slc])
  985. def test_trailing_skip(self):
  986. slc = np.s_[2:]
  987. for arr in self.values():
  988. res = trim_zeros(arr, trim='F')
  989. assert_array_equal(res, arr[slc])
  990. def test_all_zero(self):
  991. for _arr in self.values():
  992. arr = np.zeros_like(_arr, dtype=_arr.dtype)
  993. res1 = trim_zeros(arr, trim='B')
  994. assert len(res1) == 0
  995. res2 = trim_zeros(arr, trim='f')
  996. assert len(res2) == 0
  997. def test_size_zero(self):
  998. arr = np.zeros(0)
  999. res = trim_zeros(arr)
  1000. assert_array_equal(arr, res)
  1001. @pytest.mark.parametrize(
  1002. 'arr',
  1003. [np.array([0, 2**62, 0]),
  1004. np.array([0, 2**63, 0]),
  1005. np.array([0, 2**64, 0])]
  1006. )
  1007. def test_overflow(self, arr):
  1008. slc = np.s_[1:2]
  1009. res = trim_zeros(arr)
  1010. assert_array_equal(res, arr[slc])
  1011. def test_no_trim(self):
  1012. arr = np.array([None, 1, None])
  1013. res = trim_zeros(arr)
  1014. assert_array_equal(arr, res)
  1015. def test_list_to_list(self):
  1016. res = trim_zeros(self.a.tolist())
  1017. assert isinstance(res, list)
  1018. class TestExtins:
  1019. def test_basic(self):
  1020. a = np.array([1, 3, 2, 1, 2, 3, 3])
  1021. b = extract(a > 1, a)
  1022. assert_array_equal(b, [3, 2, 2, 3, 3])
  1023. def test_place(self):
  1024. # Make sure that non-np.ndarray objects
  1025. # raise an error instead of doing nothing
  1026. assert_raises(TypeError, place, [1, 2, 3], [True, False], [0, 1])
  1027. a = np.array([1, 4, 3, 2, 5, 8, 7])
  1028. place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6])
  1029. assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7])
  1030. place(a, np.zeros(7), [])
  1031. assert_array_equal(a, np.arange(1, 8))
  1032. place(a, [1, 0, 1, 0, 1, 0, 1], [8, 9])
  1033. assert_array_equal(a, [8, 2, 9, 4, 8, 6, 9])
  1034. assert_raises_regex(ValueError, "Cannot insert from an empty array",
  1035. lambda: place(a, [0, 0, 0, 0, 0, 1, 0], []))
  1036. # See Issue #6974
  1037. a = np.array(['12', '34'])
  1038. place(a, [0, 1], '9')
  1039. assert_array_equal(a, ['12', '9'])
  1040. def test_both(self):
  1041. a = rand(10)
  1042. mask = a > 0.5
  1043. ac = a.copy()
  1044. c = extract(mask, a)
  1045. place(a, mask, 0)
  1046. place(a, mask, c)
  1047. assert_array_equal(a, ac)
  1048. # _foo1 and _foo2 are used in some tests in TestVectorize.
  1049. def _foo1(x, y=1.0):
  1050. return y*math.floor(x)
  1051. def _foo2(x, y=1.0, z=0.0):
  1052. return y*math.floor(x) + z
  1053. class TestVectorize:
  1054. def test_simple(self):
  1055. def addsubtract(a, b):
  1056. if a > b:
  1057. return a - b
  1058. else:
  1059. return a + b
  1060. f = vectorize(addsubtract)
  1061. r = f([0, 3, 6, 9], [1, 3, 5, 7])
  1062. assert_array_equal(r, [1, 6, 1, 2])
  1063. def test_scalar(self):
  1064. def addsubtract(a, b):
  1065. if a > b:
  1066. return a - b
  1067. else:
  1068. return a + b
  1069. f = vectorize(addsubtract)
  1070. r = f([0, 3, 6, 9], 5)
  1071. assert_array_equal(r, [5, 8, 1, 4])
  1072. def test_large(self):
  1073. x = np.linspace(-3, 2, 10000)
  1074. f = vectorize(lambda x: x)
  1075. y = f(x)
  1076. assert_array_equal(y, x)
  1077. def test_ufunc(self):
  1078. f = vectorize(math.cos)
  1079. args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])
  1080. r1 = f(args)
  1081. r2 = np.cos(args)
  1082. assert_array_almost_equal(r1, r2)
  1083. def test_keywords(self):
  1084. def foo(a, b=1):
  1085. return a + b
  1086. f = vectorize(foo)
  1087. args = np.array([1, 2, 3])
  1088. r1 = f(args)
  1089. r2 = np.array([2, 3, 4])
  1090. assert_array_equal(r1, r2)
  1091. r1 = f(args, 2)
  1092. r2 = np.array([3, 4, 5])
  1093. assert_array_equal(r1, r2)
  1094. def test_keywords_with_otypes_order1(self):
  1095. # gh-1620: The second call of f would crash with
  1096. # `ValueError: invalid number of arguments`.
  1097. f = vectorize(_foo1, otypes=[float])
  1098. # We're testing the caching of ufuncs by vectorize, so the order
  1099. # of these function calls is an important part of the test.
  1100. r1 = f(np.arange(3.0), 1.0)
  1101. r2 = f(np.arange(3.0))
  1102. assert_array_equal(r1, r2)
  1103. def test_keywords_with_otypes_order2(self):
  1104. # gh-1620: The second call of f would crash with
  1105. # `ValueError: non-broadcastable output operand with shape ()
  1106. # doesn't match the broadcast shape (3,)`.
  1107. f = vectorize(_foo1, otypes=[float])
  1108. # We're testing the caching of ufuncs by vectorize, so the order
  1109. # of these function calls is an important part of the test.
  1110. r1 = f(np.arange(3.0))
  1111. r2 = f(np.arange(3.0), 1.0)
  1112. assert_array_equal(r1, r2)
  1113. def test_keywords_with_otypes_order3(self):
  1114. # gh-1620: The third call of f would crash with
  1115. # `ValueError: invalid number of arguments`.
  1116. f = vectorize(_foo1, otypes=[float])
  1117. # We're testing the caching of ufuncs by vectorize, so the order
  1118. # of these function calls is an important part of the test.
  1119. r1 = f(np.arange(3.0))
  1120. r2 = f(np.arange(3.0), y=1.0)
  1121. r3 = f(np.arange(3.0))
  1122. assert_array_equal(r1, r2)
  1123. assert_array_equal(r1, r3)
  1124. def test_keywords_with_otypes_several_kwd_args1(self):
  1125. # gh-1620 Make sure different uses of keyword arguments
  1126. # don't break the vectorized function.
  1127. f = vectorize(_foo2, otypes=[float])
  1128. # We're testing the caching of ufuncs by vectorize, so the order
  1129. # of these function calls is an important part of the test.
  1130. r1 = f(10.4, z=100)
  1131. r2 = f(10.4, y=-1)
  1132. r3 = f(10.4)
  1133. assert_equal(r1, _foo2(10.4, z=100))
  1134. assert_equal(r2, _foo2(10.4, y=-1))
  1135. assert_equal(r3, _foo2(10.4))
  1136. def test_keywords_with_otypes_several_kwd_args2(self):
  1137. # gh-1620 Make sure different uses of keyword arguments
  1138. # don't break the vectorized function.
  1139. f = vectorize(_foo2, otypes=[float])
  1140. # We're testing the caching of ufuncs by vectorize, so the order
  1141. # of these function calls is an important part of the test.
  1142. r1 = f(z=100, x=10.4, y=-1)
  1143. r2 = f(1, 2, 3)
  1144. assert_equal(r1, _foo2(z=100, x=10.4, y=-1))
  1145. assert_equal(r2, _foo2(1, 2, 3))
  1146. def test_keywords_no_func_code(self):
  1147. # This needs to test a function that has keywords but
  1148. # no func_code attribute, since otherwise vectorize will
  1149. # inspect the func_code.
  1150. import random
  1151. try:
  1152. vectorize(random.randrange) # Should succeed
  1153. except Exception:
  1154. raise AssertionError()
  1155. def test_keywords2_ticket_2100(self):
  1156. # Test kwarg support: enhancement ticket 2100
  1157. def foo(a, b=1):
  1158. return a + b
  1159. f = vectorize(foo)
  1160. args = np.array([1, 2, 3])
  1161. r1 = f(a=args)
  1162. r2 = np.array([2, 3, 4])
  1163. assert_array_equal(r1, r2)
  1164. r1 = f(b=1, a=args)
  1165. assert_array_equal(r1, r2)
  1166. r1 = f(args, b=2)
  1167. r2 = np.array([3, 4, 5])
  1168. assert_array_equal(r1, r2)
  1169. def test_keywords3_ticket_2100(self):
  1170. # Test excluded with mixed positional and kwargs: ticket 2100
  1171. def mypolyval(x, p):
  1172. _p = list(p)
  1173. res = _p.pop(0)
  1174. while _p:
  1175. res = res * x + _p.pop(0)
  1176. return res
  1177. vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
  1178. ans = [3, 6]
  1179. assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
  1180. assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
  1181. assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))
  1182. def test_keywords4_ticket_2100(self):
  1183. # Test vectorizing function with no positional args.
  1184. @vectorize
  1185. def f(**kw):
  1186. res = 1.0
  1187. for _k in kw:
  1188. res *= kw[_k]
  1189. return res
  1190. assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])
  1191. def test_keywords5_ticket_2100(self):
  1192. # Test vectorizing function with no kwargs args.
  1193. @vectorize
  1194. def f(*v):
  1195. return np.prod(v)
  1196. assert_array_equal(f([1, 2], [3, 4]), [3, 8])
  1197. def test_coverage1_ticket_2100(self):
  1198. def foo():
  1199. return 1
  1200. f = vectorize(foo)
  1201. assert_array_equal(f(), 1)
  1202. def test_assigning_docstring(self):
  1203. def foo(x):
  1204. """Original documentation"""
  1205. return x
  1206. f = vectorize(foo)
  1207. assert_equal(f.__doc__, foo.__doc__)
  1208. doc = "Provided documentation"
  1209. f = vectorize(foo, doc=doc)
  1210. assert_equal(f.__doc__, doc)
  1211. def test_UnboundMethod_ticket_1156(self):
  1212. # Regression test for issue 1156
  1213. class Foo:
  1214. b = 2
  1215. def bar(self, a):
  1216. return a ** self.b
  1217. assert_array_equal(vectorize(Foo().bar)(np.arange(9)),
  1218. np.arange(9) ** 2)
  1219. assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),
  1220. np.arange(9) ** 2)
  1221. def test_execution_order_ticket_1487(self):
  1222. # Regression test for dependence on execution order: issue 1487
  1223. f1 = vectorize(lambda x: x)
  1224. res1a = f1(np.arange(3))
  1225. res1b = f1(np.arange(0.1, 3))
  1226. f2 = vectorize(lambda x: x)
  1227. res2b = f2(np.arange(0.1, 3))
  1228. res2a = f2(np.arange(3))
  1229. assert_equal(res1a, res2a)
  1230. assert_equal(res1b, res2b)
  1231. def test_string_ticket_1892(self):
  1232. # Test vectorization over strings: issue 1892.
  1233. f = np.vectorize(lambda x: x)
  1234. s = '0123456789' * 10
  1235. assert_equal(s, f(s))
  1236. def test_cache(self):
  1237. # Ensure that vectorized func called exactly once per argument.
  1238. _calls = [0]
  1239. @vectorize
  1240. def f(x):
  1241. _calls[0] += 1
  1242. return x ** 2
  1243. f.cache = True
  1244. x = np.arange(5)
  1245. assert_array_equal(f(x), x * x)
  1246. assert_equal(_calls[0], len(x))
  1247. def test_otypes(self):
  1248. f = np.vectorize(lambda x: x)
  1249. f.otypes = 'i'
  1250. x = np.arange(5)
  1251. assert_array_equal(f(x), x)
  1252. def test_parse_gufunc_signature(self):
  1253. assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))
  1254. assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),
  1255. ([('x', 'y')], [()]))
  1256. assert_equal(nfb._parse_gufunc_signature('(x),(y)->()'),
  1257. ([('x',), ('y',)], [()]))
  1258. assert_equal(nfb._parse_gufunc_signature('(x)->(y)'),
  1259. ([('x',)], [('y',)]))
  1260. assert_equal(nfb._parse_gufunc_signature('(x)->(y),()'),
  1261. ([('x',)], [('y',), ()]))
  1262. assert_equal(nfb._parse_gufunc_signature('(),(a,b,c),(d)->(d,e)'),
  1263. ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
  1264. with assert_raises(ValueError):
  1265. nfb._parse_gufunc_signature('(x)(y)->()')
  1266. with assert_raises(ValueError):
  1267. nfb._parse_gufunc_signature('(x),(y)->')
  1268. with assert_raises(ValueError):
  1269. nfb._parse_gufunc_signature('((x))->(x)')
  1270. def test_signature_simple(self):
  1271. def addsubtract(a, b):
  1272. if a > b:
  1273. return a - b
  1274. else:
  1275. return a + b
  1276. f = vectorize(addsubtract, signature='(),()->()')
  1277. r = f([0, 3, 6, 9], [1, 3, 5, 7])
  1278. assert_array_equal(r, [1, 6, 1, 2])
  1279. def test_signature_mean_last(self):
  1280. def mean(a):
  1281. return a.mean()
  1282. f = vectorize(mean, signature='(n)->()')
  1283. r = f([[1, 3], [2, 4]])
  1284. assert_array_equal(r, [2, 3])
  1285. def test_signature_center(self):
  1286. def center(a):
  1287. return a - a.mean()
  1288. f = vectorize(center, signature='(n)->(n)')
  1289. r = f([[1, 3], [2, 4]])
  1290. assert_array_equal(r, [[-1, 1], [-1, 1]])
  1291. def test_signature_two_outputs(self):
  1292. f = vectorize(lambda x: (x, x), signature='()->(),()')
  1293. r = f([1, 2, 3])
  1294. assert_(isinstance(r, tuple) and len(r) == 2)
  1295. assert_array_equal(r[0], [1, 2, 3])
  1296. assert_array_equal(r[1], [1, 2, 3])
  1297. def test_signature_outer(self):
  1298. f = vectorize(np.outer, signature='(a),(b)->(a,b)')
  1299. r = f([1, 2], [1, 2, 3])
  1300. assert_array_equal(r, [[1, 2, 3], [2, 4, 6]])
  1301. r = f([[[1, 2]]], [1, 2, 3])
  1302. assert_array_equal(r, [[[[1, 2, 3], [2, 4, 6]]]])
  1303. r = f([[1, 0], [2, 0]], [1, 2, 3])
  1304. assert_array_equal(r, [[[1, 2, 3], [0, 0, 0]],
  1305. [[2, 4, 6], [0, 0, 0]]])
  1306. r = f([1, 2], [[1, 2, 3], [0, 0, 0]])
  1307. assert_array_equal(r, [[[1, 2, 3], [2, 4, 6]],
  1308. [[0, 0, 0], [0, 0, 0]]])
  1309. def test_signature_computed_size(self):
  1310. f = vectorize(lambda x: x[:-1], signature='(n)->(m)')
  1311. r = f([1, 2, 3])
  1312. assert_array_equal(r, [1, 2])
  1313. r = f([[1, 2, 3], [2, 3, 4]])
  1314. assert_array_equal(r, [[1, 2], [2, 3]])
  1315. def test_signature_excluded(self):
  1316. def foo(a, b=1):
  1317. return a + b
  1318. f = vectorize(foo, signature='()->()', excluded={'b'})
  1319. assert_array_equal(f([1, 2, 3]), [2, 3, 4])
  1320. assert_array_equal(f([1, 2, 3], b=0), [1, 2, 3])
  1321. def test_signature_otypes(self):
  1322. f = vectorize(lambda x: x, signature='(n)->(n)', otypes=['float64'])
  1323. r = f([1, 2, 3])
  1324. assert_equal(r.dtype, np.dtype('float64'))
  1325. assert_array_equal(r, [1, 2, 3])
  1326. def test_signature_invalid_inputs(self):
  1327. f = vectorize(operator.add, signature='(n),(n)->(n)')
  1328. with assert_raises_regex(TypeError, 'wrong number of positional'):
  1329. f([1, 2])
  1330. with assert_raises_regex(
  1331. ValueError, 'does not have enough dimensions'):
  1332. f(1, 2)
  1333. with assert_raises_regex(
  1334. ValueError, 'inconsistent size for core dimension'):
  1335. f([1, 2], [1, 2, 3])
  1336. f = vectorize(operator.add, signature='()->()')
  1337. with assert_raises_regex(TypeError, 'wrong number of positional'):
  1338. f(1, 2)
  1339. def test_signature_invalid_outputs(self):
  1340. f = vectorize(lambda x: x[:-1], signature='(n)->(n)')
  1341. with assert_raises_regex(
  1342. ValueError, 'inconsistent size for core dimension'):
  1343. f([1, 2, 3])
  1344. f = vectorize(lambda x: x, signature='()->(),()')
  1345. with assert_raises_regex(ValueError, 'wrong number of outputs'):
  1346. f(1)
  1347. f = vectorize(lambda x: (x, x), signature='()->()')
  1348. with assert_raises_regex(ValueError, 'wrong number of outputs'):
  1349. f([1, 2])
  1350. def test_size_zero_output(self):
  1351. # see issue 5868
  1352. f = np.vectorize(lambda x: x)
  1353. x = np.zeros([0, 5], dtype=int)
  1354. with assert_raises_regex(ValueError, 'otypes'):
  1355. f(x)
  1356. f.otypes = 'i'
  1357. assert_array_equal(f(x), x)
  1358. f = np.vectorize(lambda x: x, signature='()->()')
  1359. with assert_raises_regex(ValueError, 'otypes'):
  1360. f(x)
  1361. f = np.vectorize(lambda x: x, signature='()->()', otypes='i')
  1362. assert_array_equal(f(x), x)
  1363. f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i')
  1364. assert_array_equal(f(x), x)
  1365. f = np.vectorize(lambda x: x, signature='(n)->(n)')
  1366. assert_array_equal(f(x.T), x.T)
  1367. f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i')
  1368. with assert_raises_regex(ValueError, 'new output dimensions'):
  1369. f(x)
  1370. class TestLeaks:
  1371. class A:
  1372. iters = 20
  1373. def bound(self, *args):
  1374. return 0
  1375. @staticmethod
  1376. def unbound(*args):
  1377. return 0
  1378. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1379. @pytest.mark.parametrize('name, incr', [
  1380. ('bound', A.iters),
  1381. ('unbound', 0),
  1382. ])
  1383. def test_frompyfunc_leaks(self, name, incr):
  1384. # exposed in gh-11867 as np.vectorized, but the problem stems from
  1385. # frompyfunc.
  1386. # class.attribute = np.frompyfunc(<method>) creates a
  1387. # reference cycle if <method> is a bound class method. It requires a
  1388. # gc collection cycle to break the cycle (on CPython 3)
  1389. import gc
  1390. A_func = getattr(self.A, name)
  1391. gc.disable()
  1392. try:
  1393. refcount = sys.getrefcount(A_func)
  1394. for i in range(self.A.iters):
  1395. a = self.A()
  1396. a.f = np.frompyfunc(getattr(a, name), 1, 1)
  1397. out = a.f(np.arange(10))
  1398. a = None
  1399. # A.func is part of a reference cycle if incr is non-zero
  1400. assert_equal(sys.getrefcount(A_func), refcount + incr)
  1401. for i in range(5):
  1402. gc.collect()
  1403. assert_equal(sys.getrefcount(A_func), refcount)
  1404. finally:
  1405. gc.enable()
  1406. class TestDigitize:
  1407. def test_forward(self):
  1408. x = np.arange(-6, 5)
  1409. bins = np.arange(-5, 5)
  1410. assert_array_equal(digitize(x, bins), np.arange(11))
  1411. def test_reverse(self):
  1412. x = np.arange(5, -6, -1)
  1413. bins = np.arange(5, -5, -1)
  1414. assert_array_equal(digitize(x, bins), np.arange(11))
  1415. def test_random(self):
  1416. x = rand(10)
  1417. bin = np.linspace(x.min(), x.max(), 10)
  1418. assert_(np.all(digitize(x, bin) != 0))
  1419. def test_right_basic(self):
  1420. x = [1, 5, 4, 10, 8, 11, 0]
  1421. bins = [1, 5, 10]
  1422. default_answer = [1, 2, 1, 3, 2, 3, 0]
  1423. assert_array_equal(digitize(x, bins), default_answer)
  1424. right_answer = [0, 1, 1, 2, 2, 3, 0]
  1425. assert_array_equal(digitize(x, bins, True), right_answer)
  1426. def test_right_open(self):
  1427. x = np.arange(-6, 5)
  1428. bins = np.arange(-6, 4)
  1429. assert_array_equal(digitize(x, bins, True), np.arange(11))
  1430. def test_right_open_reverse(self):
  1431. x = np.arange(5, -6, -1)
  1432. bins = np.arange(4, -6, -1)
  1433. assert_array_equal(digitize(x, bins, True), np.arange(11))
  1434. def test_right_open_random(self):
  1435. x = rand(10)
  1436. bins = np.linspace(x.min(), x.max(), 10)
  1437. assert_(np.all(digitize(x, bins, True) != 10))
  1438. def test_monotonic(self):
  1439. x = [-1, 0, 1, 2]
  1440. bins = [0, 0, 1]
  1441. assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3])
  1442. assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3])
  1443. bins = [1, 1, 0]
  1444. assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0])
  1445. assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0])
  1446. bins = [1, 1, 1, 1]
  1447. assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4])
  1448. assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4])
  1449. bins = [0, 0, 1, 0]
  1450. assert_raises(ValueError, digitize, x, bins)
  1451. bins = [1, 1, 0, 1]
  1452. assert_raises(ValueError, digitize, x, bins)
  1453. def test_casting_error(self):
  1454. x = [1, 2, 3 + 1.j]
  1455. bins = [1, 2, 3]
  1456. assert_raises(TypeError, digitize, x, bins)
  1457. x, bins = bins, x
  1458. assert_raises(TypeError, digitize, x, bins)
  1459. def test_return_type(self):
  1460. # Functions returning indices should always return base ndarrays
  1461. class A(np.ndarray):
  1462. pass
  1463. a = np.arange(5).view(A)
  1464. b = np.arange(1, 3).view(A)
  1465. assert_(not isinstance(digitize(b, a, False), A))
  1466. assert_(not isinstance(digitize(b, a, True), A))
  1467. def test_large_integers_increasing(self):
  1468. # gh-11022
  1469. x = 2**54 # loses precision in a float
  1470. assert_equal(np.digitize(x, [x - 1, x + 1]), 1)
  1471. @pytest.mark.xfail(
  1472. reason="gh-11022: np.core.multiarray._monoticity loses precision")
  1473. def test_large_integers_decreasing(self):
  1474. # gh-11022
  1475. x = 2**54 # loses precision in a float
  1476. assert_equal(np.digitize(x, [x + 1, x - 1]), 1)
  1477. class TestUnwrap:
  1478. def test_simple(self):
  1479. # check that unwrap removes jumps greater that 2*pi
  1480. assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])
  1481. # check that unwrap maintains continuity
  1482. assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
  1483. class TestFilterwindows:
  1484. def test_hanning(self):
  1485. # check symmetry
  1486. w = hanning(10)
  1487. assert_equal(w, flipud(w))
  1488. # check known value
  1489. assert_almost_equal(np.sum(w, axis=0), 4.500, 4)
  1490. def test_hamming(self):
  1491. # check symmetry
  1492. w = hamming(10)
  1493. assert_equal(w, flipud(w))
  1494. # check known value
  1495. assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)
  1496. def test_bartlett(self):
  1497. # check symmetry
  1498. w = bartlett(10)
  1499. assert_equal(w, flipud(w))
  1500. # check known value
  1501. assert_almost_equal(np.sum(w, axis=0), 4.4444, 4)
  1502. def test_blackman(self):
  1503. # check symmetry
  1504. w = blackman(10)
  1505. assert_equal(w, flipud(w))
  1506. # check known value
  1507. assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
  1508. class TestTrapz:
  1509. def test_simple(self):
  1510. x = np.arange(-10, 10, .1)
  1511. r = trapz(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
  1512. # check integral of normal equals 1
  1513. assert_almost_equal(r, 1, 7)
  1514. def test_ndim(self):
  1515. x = np.linspace(0, 1, 3)
  1516. y = np.linspace(0, 2, 8)
  1517. z = np.linspace(0, 3, 13)
  1518. wx = np.ones_like(x) * (x[1] - x[0])
  1519. wx[0] /= 2
  1520. wx[-1] /= 2
  1521. wy = np.ones_like(y) * (y[1] - y[0])
  1522. wy[0] /= 2
  1523. wy[-1] /= 2
  1524. wz = np.ones_like(z) * (z[1] - z[0])
  1525. wz[0] /= 2
  1526. wz[-1] /= 2
  1527. q = x[:, None, None] + y[None,:, None] + z[None, None,:]
  1528. qx = (q * wx[:, None, None]).sum(axis=0)
  1529. qy = (q * wy[None, :, None]).sum(axis=1)
  1530. qz = (q * wz[None, None, :]).sum(axis=2)
  1531. # n-d `x`
  1532. r = trapz(q, x=x[:, None, None], axis=0)
  1533. assert_almost_equal(r, qx)
  1534. r = trapz(q, x=y[None,:, None], axis=1)
  1535. assert_almost_equal(r, qy)
  1536. r = trapz(q, x=z[None, None,:], axis=2)
  1537. assert_almost_equal(r, qz)
  1538. # 1-d `x`
  1539. r = trapz(q, x=x, axis=0)
  1540. assert_almost_equal(r, qx)
  1541. r = trapz(q, x=y, axis=1)
  1542. assert_almost_equal(r, qy)
  1543. r = trapz(q, x=z, axis=2)
  1544. assert_almost_equal(r, qz)
  1545. def test_masked(self):
  1546. # Testing that masked arrays behave as if the function is 0 where
  1547. # masked
  1548. x = np.arange(5)
  1549. y = x * x
  1550. mask = x == 2
  1551. ym = np.ma.array(y, mask=mask)
  1552. r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
  1553. assert_almost_equal(trapz(ym, x), r)
  1554. xm = np.ma.array(x, mask=mask)
  1555. assert_almost_equal(trapz(ym, xm), r)
  1556. xm = np.ma.array(x, mask=mask)
  1557. assert_almost_equal(trapz(y, xm), r)
  1558. class TestSinc:
  1559. def test_simple(self):
  1560. assert_(sinc(0) == 1)
  1561. w = sinc(np.linspace(-1, 1, 100))
  1562. # check symmetry
  1563. assert_array_almost_equal(w, flipud(w), 7)
  1564. def test_array_like(self):
  1565. x = [0, 0.5]
  1566. y1 = sinc(np.array(x))
  1567. y2 = sinc(list(x))
  1568. y3 = sinc(tuple(x))
  1569. assert_array_equal(y1, y2)
  1570. assert_array_equal(y1, y3)
  1571. class TestUnique:
  1572. def test_simple(self):
  1573. x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
  1574. assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))
  1575. assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))
  1576. x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
  1577. assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
  1578. x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j])
  1579. assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))
  1580. class TestCheckFinite:
  1581. def test_simple(self):
  1582. a = [1, 2, 3]
  1583. b = [1, 2, np.inf]
  1584. c = [1, 2, np.nan]
  1585. np.lib.asarray_chkfinite(a)
  1586. assert_raises(ValueError, np.lib.asarray_chkfinite, b)
  1587. assert_raises(ValueError, np.lib.asarray_chkfinite, c)
  1588. def test_dtype_order(self):
  1589. # Regression test for missing dtype and order arguments
  1590. a = [1, 2, 3]
  1591. a = np.lib.asarray_chkfinite(a, order='F', dtype=np.float64)
  1592. assert_(a.dtype == np.float64)
  1593. class TestCorrCoef:
  1594. A = np.array(
  1595. [[0.15391142, 0.18045767, 0.14197213],
  1596. [0.70461506, 0.96474128, 0.27906989],
  1597. [0.9297531, 0.32296769, 0.19267156]])
  1598. B = np.array(
  1599. [[0.10377691, 0.5417086, 0.49807457],
  1600. [0.82872117, 0.77801674, 0.39226705],
  1601. [0.9314666, 0.66800209, 0.03538394]])
  1602. res1 = np.array(
  1603. [[1., 0.9379533, -0.04931983],
  1604. [0.9379533, 1., 0.30007991],
  1605. [-0.04931983, 0.30007991, 1.]])
  1606. res2 = np.array(
  1607. [[1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523],
  1608. [0.9379533, 1., 0.30007991, -0.04781421, 0.88157256, 0.78052386],
  1609. [-0.04931983, 0.30007991, 1., -0.96717111, 0.71483595, 0.83053601],
  1610. [0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113],
  1611. [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],
  1612. [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])
  1613. def test_non_array(self):
  1614. assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
  1615. [[1., -1.], [-1., 1.]])
  1616. def test_simple(self):
  1617. tgt1 = corrcoef(self.A)
  1618. assert_almost_equal(tgt1, self.res1)
  1619. assert_(np.all(np.abs(tgt1) <= 1.0))
  1620. tgt2 = corrcoef(self.A, self.B)
  1621. assert_almost_equal(tgt2, self.res2)
  1622. assert_(np.all(np.abs(tgt2) <= 1.0))
  1623. def test_ddof(self):
  1624. # ddof raises DeprecationWarning
  1625. with suppress_warnings() as sup:
  1626. warnings.simplefilter("always")
  1627. assert_warns(DeprecationWarning, corrcoef, self.A, ddof=-1)
  1628. sup.filter(DeprecationWarning)
  1629. # ddof has no or negligible effect on the function
  1630. assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1)
  1631. assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2)
  1632. assert_almost_equal(corrcoef(self.A, ddof=3), self.res1)
  1633. assert_almost_equal(corrcoef(self.A, self.B, ddof=3), self.res2)
  1634. def test_bias(self):
  1635. # bias raises DeprecationWarning
  1636. with suppress_warnings() as sup:
  1637. warnings.simplefilter("always")
  1638. assert_warns(DeprecationWarning, corrcoef, self.A, self.B, 1, 0)
  1639. assert_warns(DeprecationWarning, corrcoef, self.A, bias=0)
  1640. sup.filter(DeprecationWarning)
  1641. # bias has no or negligible effect on the function
  1642. assert_almost_equal(corrcoef(self.A, bias=1), self.res1)
  1643. def test_complex(self):
  1644. x = np.array([[1, 2, 3], [1j, 2j, 3j]])
  1645. res = corrcoef(x)
  1646. tgt = np.array([[1., -1.j], [1.j, 1.]])
  1647. assert_allclose(res, tgt)
  1648. assert_(np.all(np.abs(res) <= 1.0))
  1649. def test_xy(self):
  1650. x = np.array([[1, 2, 3]])
  1651. y = np.array([[1j, 2j, 3j]])
  1652. assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))
  1653. def test_empty(self):
  1654. with warnings.catch_warnings(record=True):
  1655. warnings.simplefilter('always', RuntimeWarning)
  1656. assert_array_equal(corrcoef(np.array([])), np.nan)
  1657. assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),
  1658. np.array([]).reshape(0, 0))
  1659. assert_array_equal(corrcoef(np.array([]).reshape(2, 0)),
  1660. np.array([[np.nan, np.nan], [np.nan, np.nan]]))
  1661. def test_extreme(self):
  1662. x = [[1e-100, 1e100], [1e100, 1e-100]]
  1663. with np.errstate(all='raise'):
  1664. c = corrcoef(x)
  1665. assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))
  1666. assert_(np.all(np.abs(c) <= 1.0))
  1667. @pytest.mark.parametrize("test_type", [np.half, np.single, np.double, np.longdouble])
  1668. def test_corrcoef_dtype(self, test_type):
  1669. cast_A = self.A.astype(test_type)
  1670. res = corrcoef(cast_A, dtype=test_type)
  1671. assert test_type == res.dtype
  1672. class TestCov:
  1673. x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
  1674. res1 = np.array([[1., -1.], [-1., 1.]])
  1675. x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
  1676. frequencies = np.array([1, 4, 1])
  1677. x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T
  1678. res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])
  1679. unit_frequencies = np.ones(3, dtype=np.int_)
  1680. weights = np.array([1.0, 4.0, 1.0])
  1681. res3 = np.array([[2. / 3., -2. / 3.], [-2. / 3., 2. / 3.]])
  1682. unit_weights = np.ones(3)
  1683. x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])
  1684. def test_basic(self):
  1685. assert_allclose(cov(self.x1), self.res1)
  1686. def test_complex(self):
  1687. x = np.array([[1, 2, 3], [1j, 2j, 3j]])
  1688. res = np.array([[1., -1.j], [1.j, 1.]])
  1689. assert_allclose(cov(x), res)
  1690. assert_allclose(cov(x, aweights=np.ones(3)), res)
  1691. def test_xy(self):
  1692. x = np.array([[1, 2, 3]])
  1693. y = np.array([[1j, 2j, 3j]])
  1694. assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))
  1695. def test_empty(self):
  1696. with warnings.catch_warnings(record=True):
  1697. warnings.simplefilter('always', RuntimeWarning)
  1698. assert_array_equal(cov(np.array([])), np.nan)
  1699. assert_array_equal(cov(np.array([]).reshape(0, 2)),
  1700. np.array([]).reshape(0, 0))
  1701. assert_array_equal(cov(np.array([]).reshape(2, 0)),
  1702. np.array([[np.nan, np.nan], [np.nan, np.nan]]))
  1703. def test_wrong_ddof(self):
  1704. with warnings.catch_warnings(record=True):
  1705. warnings.simplefilter('always', RuntimeWarning)
  1706. assert_array_equal(cov(self.x1, ddof=5),
  1707. np.array([[np.inf, -np.inf],
  1708. [-np.inf, np.inf]]))
  1709. def test_1D_rowvar(self):
  1710. assert_allclose(cov(self.x3), cov(self.x3, rowvar=False))
  1711. y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501])
  1712. assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=False))
  1713. def test_1D_variance(self):
  1714. assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1))
  1715. def test_fweights(self):
  1716. assert_allclose(cov(self.x2, fweights=self.frequencies),
  1717. cov(self.x2_repeats))
  1718. assert_allclose(cov(self.x1, fweights=self.frequencies),
  1719. self.res2)
  1720. assert_allclose(cov(self.x1, fweights=self.unit_frequencies),
  1721. self.res1)
  1722. nonint = self.frequencies + 0.5
  1723. assert_raises(TypeError, cov, self.x1, fweights=nonint)
  1724. f = np.ones((2, 3), dtype=np.int_)
  1725. assert_raises(RuntimeError, cov, self.x1, fweights=f)
  1726. f = np.ones(2, dtype=np.int_)
  1727. assert_raises(RuntimeError, cov, self.x1, fweights=f)
  1728. f = -1 * np.ones(3, dtype=np.int_)
  1729. assert_raises(ValueError, cov, self.x1, fweights=f)
  1730. def test_aweights(self):
  1731. assert_allclose(cov(self.x1, aweights=self.weights), self.res3)
  1732. assert_allclose(cov(self.x1, aweights=3.0 * self.weights),
  1733. cov(self.x1, aweights=self.weights))
  1734. assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1)
  1735. w = np.ones((2, 3))
  1736. assert_raises(RuntimeError, cov, self.x1, aweights=w)
  1737. w = np.ones(2)
  1738. assert_raises(RuntimeError, cov, self.x1, aweights=w)
  1739. w = -1.0 * np.ones(3)
  1740. assert_raises(ValueError, cov, self.x1, aweights=w)
  1741. def test_unit_fweights_and_aweights(self):
  1742. assert_allclose(cov(self.x2, fweights=self.frequencies,
  1743. aweights=self.unit_weights),
  1744. cov(self.x2_repeats))
  1745. assert_allclose(cov(self.x1, fweights=self.frequencies,
  1746. aweights=self.unit_weights),
  1747. self.res2)
  1748. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  1749. aweights=self.unit_weights),
  1750. self.res1)
  1751. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  1752. aweights=self.weights),
  1753. self.res3)
  1754. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  1755. aweights=3.0 * self.weights),
  1756. cov(self.x1, aweights=self.weights))
  1757. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  1758. aweights=self.unit_weights),
  1759. self.res1)
  1760. @pytest.mark.parametrize("test_type", [np.half, np.single, np.double, np.longdouble])
  1761. def test_cov_dtype(self, test_type):
  1762. cast_x1 = self.x1.astype(test_type)
  1763. res = cov(cast_x1, dtype=test_type)
  1764. assert test_type == res.dtype
  1765. class Test_I0:
  1766. def test_simple(self):
  1767. assert_almost_equal(
  1768. i0(0.5),
  1769. np.array(1.0634833707413234))
  1770. # need at least one test above 8, as the implementation is piecewise
  1771. A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0])
  1772. expected = np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049, 2815.71662847])
  1773. assert_almost_equal(i0(A), expected)
  1774. assert_almost_equal(i0(-A), expected)
  1775. B = np.array([[0.827002, 0.99959078],
  1776. [0.89694769, 0.39298162],
  1777. [0.37954418, 0.05206293],
  1778. [0.36465447, 0.72446427],
  1779. [0.48164949, 0.50324519]])
  1780. assert_almost_equal(
  1781. i0(B),
  1782. np.array([[1.17843223, 1.26583466],
  1783. [1.21147086, 1.03898290],
  1784. [1.03633899, 1.00067775],
  1785. [1.03352052, 1.13557954],
  1786. [1.05884290, 1.06432317]]))
  1787. # Regression test for gh-11205
  1788. i0_0 = np.i0([0.])
  1789. assert_equal(i0_0.shape, (1,))
  1790. assert_array_equal(np.i0([0.]), np.array([1.]))
  1791. def test_non_array(self):
  1792. a = np.arange(4)
  1793. class array_like:
  1794. __array_interface__ = a.__array_interface__
  1795. def __array_wrap__(self, arr):
  1796. return self
  1797. # E.g. pandas series survive ufunc calls through array-wrap:
  1798. assert isinstance(np.abs(array_like()), array_like)
  1799. exp = np.i0(a)
  1800. res = np.i0(array_like())
  1801. assert_array_equal(exp, res)
  1802. def test_complex(self):
  1803. a = np.array([0, 1 + 2j])
  1804. with pytest.raises(TypeError, match="i0 not supported for complex values"):
  1805. res = i0(a)
  1806. class TestKaiser:
  1807. def test_simple(self):
  1808. assert_(np.isfinite(kaiser(1, 1.0)))
  1809. assert_almost_equal(kaiser(0, 1.0),
  1810. np.array([]))
  1811. assert_almost_equal(kaiser(2, 1.0),
  1812. np.array([0.78984831, 0.78984831]))
  1813. assert_almost_equal(kaiser(5, 1.0),
  1814. np.array([0.78984831, 0.94503323, 1.,
  1815. 0.94503323, 0.78984831]))
  1816. assert_almost_equal(kaiser(5, 1.56789),
  1817. np.array([0.58285404, 0.88409679, 1.,
  1818. 0.88409679, 0.58285404]))
  1819. def test_int_beta(self):
  1820. kaiser(3, 4)
  1821. class TestMsort:
  1822. def test_simple(self):
  1823. A = np.array([[0.44567325, 0.79115165, 0.54900530],
  1824. [0.36844147, 0.37325583, 0.96098397],
  1825. [0.64864341, 0.52929049, 0.39172155]])
  1826. assert_almost_equal(
  1827. msort(A),
  1828. np.array([[0.36844147, 0.37325583, 0.39172155],
  1829. [0.44567325, 0.52929049, 0.54900530],
  1830. [0.64864341, 0.79115165, 0.96098397]]))
  1831. class TestMeshgrid:
  1832. def test_simple(self):
  1833. [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
  1834. assert_array_equal(X, np.array([[1, 2, 3],
  1835. [1, 2, 3],
  1836. [1, 2, 3],
  1837. [1, 2, 3]]))
  1838. assert_array_equal(Y, np.array([[4, 4, 4],
  1839. [5, 5, 5],
  1840. [6, 6, 6],
  1841. [7, 7, 7]]))
  1842. def test_single_input(self):
  1843. [X] = meshgrid([1, 2, 3, 4])
  1844. assert_array_equal(X, np.array([1, 2, 3, 4]))
  1845. def test_no_input(self):
  1846. args = []
  1847. assert_array_equal([], meshgrid(*args))
  1848. assert_array_equal([], meshgrid(*args, copy=False))
  1849. def test_indexing(self):
  1850. x = [1, 2, 3]
  1851. y = [4, 5, 6, 7]
  1852. [X, Y] = meshgrid(x, y, indexing='ij')
  1853. assert_array_equal(X, np.array([[1, 1, 1, 1],
  1854. [2, 2, 2, 2],
  1855. [3, 3, 3, 3]]))
  1856. assert_array_equal(Y, np.array([[4, 5, 6, 7],
  1857. [4, 5, 6, 7],
  1858. [4, 5, 6, 7]]))
  1859. # Test expected shapes:
  1860. z = [8, 9]
  1861. assert_(meshgrid(x, y)[0].shape == (4, 3))
  1862. assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
  1863. assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
  1864. assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))
  1865. assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
  1866. def test_sparse(self):
  1867. [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
  1868. assert_array_equal(X, np.array([[1, 2, 3]]))
  1869. assert_array_equal(Y, np.array([[4], [5], [6], [7]]))
  1870. def test_invalid_arguments(self):
  1871. # Test that meshgrid complains about invalid arguments
  1872. # Regression test for issue #4755:
  1873. # https://github.com/numpy/numpy/issues/4755
  1874. assert_raises(TypeError, meshgrid,
  1875. [1, 2, 3], [4, 5, 6, 7], indices='ij')
  1876. def test_return_type(self):
  1877. # Test for appropriate dtype in returned arrays.
  1878. # Regression test for issue #5297
  1879. # https://github.com/numpy/numpy/issues/5297
  1880. x = np.arange(0, 10, dtype=np.float32)
  1881. y = np.arange(10, 20, dtype=np.float64)
  1882. X, Y = np.meshgrid(x,y)
  1883. assert_(X.dtype == x.dtype)
  1884. assert_(Y.dtype == y.dtype)
  1885. # copy
  1886. X, Y = np.meshgrid(x,y, copy=True)
  1887. assert_(X.dtype == x.dtype)
  1888. assert_(Y.dtype == y.dtype)
  1889. # sparse
  1890. X, Y = np.meshgrid(x,y, sparse=True)
  1891. assert_(X.dtype == x.dtype)
  1892. assert_(Y.dtype == y.dtype)
  1893. def test_writeback(self):
  1894. # Issue 8561
  1895. X = np.array([1.1, 2.2])
  1896. Y = np.array([3.3, 4.4])
  1897. x, y = np.meshgrid(X, Y, sparse=False, copy=True)
  1898. x[0, :] = 0
  1899. assert_equal(x[0, :], 0)
  1900. assert_equal(x[1, :], X)
  1901. class TestPiecewise:
  1902. def test_simple(self):
  1903. # Condition is single bool list
  1904. x = piecewise([0, 0], [True, False], [1])
  1905. assert_array_equal(x, [1, 0])
  1906. # List of conditions: single bool list
  1907. x = piecewise([0, 0], [[True, False]], [1])
  1908. assert_array_equal(x, [1, 0])
  1909. # Conditions is single bool array
  1910. x = piecewise([0, 0], np.array([True, False]), [1])
  1911. assert_array_equal(x, [1, 0])
  1912. # Condition is single int array
  1913. x = piecewise([0, 0], np.array([1, 0]), [1])
  1914. assert_array_equal(x, [1, 0])
  1915. # List of conditions: int array
  1916. x = piecewise([0, 0], [np.array([1, 0])], [1])
  1917. assert_array_equal(x, [1, 0])
  1918. x = piecewise([0, 0], [[False, True]], [lambda x:-1])
  1919. assert_array_equal(x, [0, -1])
  1920. assert_raises_regex(ValueError, '1 or 2 functions are expected',
  1921. piecewise, [0, 0], [[False, True]], [])
  1922. assert_raises_regex(ValueError, '1 or 2 functions are expected',
  1923. piecewise, [0, 0], [[False, True]], [1, 2, 3])
  1924. def test_two_conditions(self):
  1925. x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
  1926. assert_array_equal(x, [3, 4])
  1927. def test_scalar_domains_three_conditions(self):
  1928. x = piecewise(3, [True, False, False], [4, 2, 0])
  1929. assert_equal(x, 4)
  1930. def test_default(self):
  1931. # No value specified for x[1], should be 0
  1932. x = piecewise([1, 2], [True, False], [2])
  1933. assert_array_equal(x, [2, 0])
  1934. # Should set x[1] to 3
  1935. x = piecewise([1, 2], [True, False], [2, 3])
  1936. assert_array_equal(x, [2, 3])
  1937. def test_0d(self):
  1938. x = np.array(3)
  1939. y = piecewise(x, x > 3, [4, 0])
  1940. assert_(y.ndim == 0)
  1941. assert_(y == 0)
  1942. x = 5
  1943. y = piecewise(x, [True, False], [1, 0])
  1944. assert_(y.ndim == 0)
  1945. assert_(y == 1)
  1946. # With 3 ranges (It was failing, before)
  1947. y = piecewise(x, [False, False, True], [1, 2, 3])
  1948. assert_array_equal(y, 3)
  1949. def test_0d_comparison(self):
  1950. x = 3
  1951. y = piecewise(x, [x <= 3, x > 3], [4, 0]) # Should succeed.
  1952. assert_equal(y, 4)
  1953. # With 3 ranges (It was failing, before)
  1954. x = 4
  1955. y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3])
  1956. assert_array_equal(y, 2)
  1957. assert_raises_regex(ValueError, '2 or 3 functions are expected',
  1958. piecewise, x, [x <= 3, x > 3], [1])
  1959. assert_raises_regex(ValueError, '2 or 3 functions are expected',
  1960. piecewise, x, [x <= 3, x > 3], [1, 1, 1, 1])
  1961. def test_0d_0d_condition(self):
  1962. x = np.array(3)
  1963. c = np.array(x > 3)
  1964. y = piecewise(x, [c], [1, 2])
  1965. assert_equal(y, 2)
  1966. def test_multidimensional_extrafunc(self):
  1967. x = np.array([[-2.5, -1.5, -0.5],
  1968. [0.5, 1.5, 2.5]])
  1969. y = piecewise(x, [x < 0, x >= 2], [-1, 1, 3])
  1970. assert_array_equal(y, np.array([[-1., -1., -1.],
  1971. [3., 3., 1.]]))
  1972. class TestBincount:
  1973. def test_simple(self):
  1974. y = np.bincount(np.arange(4))
  1975. assert_array_equal(y, np.ones(4))
  1976. def test_simple2(self):
  1977. y = np.bincount(np.array([1, 5, 2, 4, 1]))
  1978. assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1]))
  1979. def test_simple_weight(self):
  1980. x = np.arange(4)
  1981. w = np.array([0.2, 0.3, 0.5, 0.1])
  1982. y = np.bincount(x, w)
  1983. assert_array_equal(y, w)
  1984. def test_simple_weight2(self):
  1985. x = np.array([1, 2, 4, 5, 2])
  1986. w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
  1987. y = np.bincount(x, w)
  1988. assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1]))
  1989. def test_with_minlength(self):
  1990. x = np.array([0, 1, 0, 1, 1])
  1991. y = np.bincount(x, minlength=3)
  1992. assert_array_equal(y, np.array([2, 3, 0]))
  1993. x = []
  1994. y = np.bincount(x, minlength=0)
  1995. assert_array_equal(y, np.array([]))
  1996. def test_with_minlength_smaller_than_maxvalue(self):
  1997. x = np.array([0, 1, 1, 2, 2, 3, 3])
  1998. y = np.bincount(x, minlength=2)
  1999. assert_array_equal(y, np.array([1, 2, 2, 2]))
  2000. y = np.bincount(x, minlength=0)
  2001. assert_array_equal(y, np.array([1, 2, 2, 2]))
  2002. def test_with_minlength_and_weights(self):
  2003. x = np.array([1, 2, 4, 5, 2])
  2004. w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
  2005. y = np.bincount(x, w, 8)
  2006. assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0]))
  2007. def test_empty(self):
  2008. x = np.array([], dtype=int)
  2009. y = np.bincount(x)
  2010. assert_array_equal(x, y)
  2011. def test_empty_with_minlength(self):
  2012. x = np.array([], dtype=int)
  2013. y = np.bincount(x, minlength=5)
  2014. assert_array_equal(y, np.zeros(5, dtype=int))
  2015. def test_with_incorrect_minlength(self):
  2016. x = np.array([], dtype=int)
  2017. assert_raises_regex(TypeError,
  2018. "'str' object cannot be interpreted",
  2019. lambda: np.bincount(x, minlength="foobar"))
  2020. assert_raises_regex(ValueError,
  2021. "must not be negative",
  2022. lambda: np.bincount(x, minlength=-1))
  2023. x = np.arange(5)
  2024. assert_raises_regex(TypeError,
  2025. "'str' object cannot be interpreted",
  2026. lambda: np.bincount(x, minlength="foobar"))
  2027. assert_raises_regex(ValueError,
  2028. "must not be negative",
  2029. lambda: np.bincount(x, minlength=-1))
  2030. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2031. def test_dtype_reference_leaks(self):
  2032. # gh-6805
  2033. intp_refcount = sys.getrefcount(np.dtype(np.intp))
  2034. double_refcount = sys.getrefcount(np.dtype(np.double))
  2035. for j in range(10):
  2036. np.bincount([1, 2, 3])
  2037. assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
  2038. assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
  2039. for j in range(10):
  2040. np.bincount([1, 2, 3], [4, 5, 6])
  2041. assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
  2042. assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
  2043. @pytest.mark.parametrize("vals", [[[2, 2]], 2])
  2044. def test_error_not_1d(self, vals):
  2045. # Test that values has to be 1-D (both as array and nested list)
  2046. vals_arr = np.asarray(vals)
  2047. with assert_raises(ValueError):
  2048. np.bincount(vals_arr)
  2049. with assert_raises(ValueError):
  2050. np.bincount(vals)
  2051. class TestInterp:
  2052. def test_exceptions(self):
  2053. assert_raises(ValueError, interp, 0, [], [])
  2054. assert_raises(ValueError, interp, 0, [0], [1, 2])
  2055. assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)
  2056. assert_raises(ValueError, interp, 0, [], [], period=360)
  2057. assert_raises(ValueError, interp, 0, [0], [1, 2], period=360)
  2058. def test_basic(self):
  2059. x = np.linspace(0, 1, 5)
  2060. y = np.linspace(0, 1, 5)
  2061. x0 = np.linspace(0, 1, 50)
  2062. assert_almost_equal(np.interp(x0, x, y), x0)
  2063. def test_right_left_behavior(self):
  2064. # Needs range of sizes to test different code paths.
  2065. # size ==1 is special cased, 1 < size < 5 is linear search, and
  2066. # size >= 5 goes through local search and possibly binary search.
  2067. for size in range(1, 10):
  2068. xp = np.arange(size, dtype=np.double)
  2069. yp = np.ones(size, dtype=np.double)
  2070. incpts = np.array([-1, 0, size - 1, size], dtype=np.double)
  2071. decpts = incpts[::-1]
  2072. incres = interp(incpts, xp, yp)
  2073. decres = interp(decpts, xp, yp)
  2074. inctgt = np.array([1, 1, 1, 1], dtype=float)
  2075. dectgt = inctgt[::-1]
  2076. assert_equal(incres, inctgt)
  2077. assert_equal(decres, dectgt)
  2078. incres = interp(incpts, xp, yp, left=0)
  2079. decres = interp(decpts, xp, yp, left=0)
  2080. inctgt = np.array([0, 1, 1, 1], dtype=float)
  2081. dectgt = inctgt[::-1]
  2082. assert_equal(incres, inctgt)
  2083. assert_equal(decres, dectgt)
  2084. incres = interp(incpts, xp, yp, right=2)
  2085. decres = interp(decpts, xp, yp, right=2)
  2086. inctgt = np.array([1, 1, 1, 2], dtype=float)
  2087. dectgt = inctgt[::-1]
  2088. assert_equal(incres, inctgt)
  2089. assert_equal(decres, dectgt)
  2090. incres = interp(incpts, xp, yp, left=0, right=2)
  2091. decres = interp(decpts, xp, yp, left=0, right=2)
  2092. inctgt = np.array([0, 1, 1, 2], dtype=float)
  2093. dectgt = inctgt[::-1]
  2094. assert_equal(incres, inctgt)
  2095. assert_equal(decres, dectgt)
  2096. def test_scalar_interpolation_point(self):
  2097. x = np.linspace(0, 1, 5)
  2098. y = np.linspace(0, 1, 5)
  2099. x0 = 0
  2100. assert_almost_equal(np.interp(x0, x, y), x0)
  2101. x0 = .3
  2102. assert_almost_equal(np.interp(x0, x, y), x0)
  2103. x0 = np.float32(.3)
  2104. assert_almost_equal(np.interp(x0, x, y), x0)
  2105. x0 = np.float64(.3)
  2106. assert_almost_equal(np.interp(x0, x, y), x0)
  2107. x0 = np.nan
  2108. assert_almost_equal(np.interp(x0, x, y), x0)
  2109. def test_non_finite_behavior_exact_x(self):
  2110. x = [1, 2, 2.5, 3, 4]
  2111. xp = [1, 2, 3, 4]
  2112. fp = [1, 2, np.inf, 4]
  2113. assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.inf, np.inf, 4])
  2114. fp = [1, 2, np.nan, 4]
  2115. assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])
  2116. @pytest.fixture(params=[
  2117. lambda x: np.float_(x),
  2118. lambda x: _make_complex(x, 0),
  2119. lambda x: _make_complex(0, x),
  2120. lambda x: _make_complex(x, np.multiply(x, -2))
  2121. ], ids=[
  2122. 'real',
  2123. 'complex-real',
  2124. 'complex-imag',
  2125. 'complex-both'
  2126. ])
  2127. def sc(self, request):
  2128. """ scale function used by the below tests """
  2129. return request.param
  2130. def test_non_finite_any_nan(self, sc):
  2131. """ test that nans are propagated """
  2132. assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan))
  2133. assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan))
  2134. assert_equal(np.interp(0.5, [ 0, 1], sc([np.nan, 10])), sc(np.nan))
  2135. assert_equal(np.interp(0.5, [ 0, 1], sc([ 0, np.nan])), sc(np.nan))
  2136. def test_non_finite_inf(self, sc):
  2137. """ Test that interp between opposite infs gives nan """
  2138. assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 0, 10])), sc(np.nan))
  2139. assert_equal(np.interp(0.5, [ 0, 1], sc([-np.inf, +np.inf])), sc(np.nan))
  2140. assert_equal(np.interp(0.5, [ 0, 1], sc([+np.inf, -np.inf])), sc(np.nan))
  2141. # unless the y values are equal
  2142. assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 10, 10])), sc(10))
  2143. def test_non_finite_half_inf_xf(self, sc):
  2144. """ Test that interp where both axes have a bound at inf gives nan """
  2145. assert_equal(np.interp(0.5, [-np.inf, 1], sc([-np.inf, 10])), sc(np.nan))
  2146. assert_equal(np.interp(0.5, [-np.inf, 1], sc([+np.inf, 10])), sc(np.nan))
  2147. assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, -np.inf])), sc(np.nan))
  2148. assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, +np.inf])), sc(np.nan))
  2149. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([-np.inf, 10])), sc(np.nan))
  2150. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([+np.inf, 10])), sc(np.nan))
  2151. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, -np.inf])), sc(np.nan))
  2152. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, +np.inf])), sc(np.nan))
  2153. def test_non_finite_half_inf_x(self, sc):
  2154. """ Test interp where the x axis has a bound at inf """
  2155. assert_equal(np.interp(0.5, [-np.inf, -np.inf], sc([0, 10])), sc(10))
  2156. assert_equal(np.interp(0.5, [-np.inf, 1 ], sc([0, 10])), sc(10))
  2157. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([0, 10])), sc(0))
  2158. assert_equal(np.interp(0.5, [+np.inf, +np.inf], sc([0, 10])), sc(0))
  2159. def test_non_finite_half_inf_f(self, sc):
  2160. """ Test interp where the f axis has a bound at inf """
  2161. assert_equal(np.interp(0.5, [0, 1], sc([ 0, -np.inf])), sc(-np.inf))
  2162. assert_equal(np.interp(0.5, [0, 1], sc([ 0, +np.inf])), sc(+np.inf))
  2163. assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, 10])), sc(-np.inf))
  2164. assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, 10])), sc(+np.inf))
  2165. assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, -np.inf])), sc(-np.inf))
  2166. assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, +np.inf])), sc(+np.inf))
  2167. def test_complex_interp(self):
  2168. # test complex interpolation
  2169. x = np.linspace(0, 1, 5)
  2170. y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5))*1.0j
  2171. x0 = 0.3
  2172. y0 = x0 + (1+x0)*1.0j
  2173. assert_almost_equal(np.interp(x0, x, y), y0)
  2174. # test complex left and right
  2175. x0 = -1
  2176. left = 2 + 3.0j
  2177. assert_almost_equal(np.interp(x0, x, y, left=left), left)
  2178. x0 = 2.0
  2179. right = 2 + 3.0j
  2180. assert_almost_equal(np.interp(x0, x, y, right=right), right)
  2181. # test complex non finite
  2182. x = [1, 2, 2.5, 3, 4]
  2183. xp = [1, 2, 3, 4]
  2184. fp = [1, 2+1j, np.inf, 4]
  2185. y = [1, 2+1j, np.inf+0.5j, np.inf, 4]
  2186. assert_almost_equal(np.interp(x, xp, fp), y)
  2187. # test complex periodic
  2188. x = [-180, -170, -185, 185, -10, -5, 0, 365]
  2189. xp = [190, -190, 350, -350]
  2190. fp = [5+1.0j, 10+2j, 3+3j, 4+4j]
  2191. y = [7.5+1.5j, 5.+1.0j, 8.75+1.75j, 6.25+1.25j, 3.+3j, 3.25+3.25j,
  2192. 3.5+3.5j, 3.75+3.75j]
  2193. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2194. def test_zero_dimensional_interpolation_point(self):
  2195. x = np.linspace(0, 1, 5)
  2196. y = np.linspace(0, 1, 5)
  2197. x0 = np.array(.3)
  2198. assert_almost_equal(np.interp(x0, x, y), x0)
  2199. xp = np.array([0, 2, 4])
  2200. fp = np.array([1, -1, 1])
  2201. actual = np.interp(np.array(1), xp, fp)
  2202. assert_equal(actual, 0)
  2203. assert_(isinstance(actual, np.float64))
  2204. actual = np.interp(np.array(4.5), xp, fp, period=4)
  2205. assert_equal(actual, 0.5)
  2206. assert_(isinstance(actual, np.float64))
  2207. def test_if_len_x_is_small(self):
  2208. xp = np.arange(0, 10, 0.0001)
  2209. fp = np.sin(xp)
  2210. assert_almost_equal(np.interp(np.pi, xp, fp), 0.0)
  2211. def test_period(self):
  2212. x = [-180, -170, -185, 185, -10, -5, 0, 365]
  2213. xp = [190, -190, 350, -350]
  2214. fp = [5, 10, 3, 4]
  2215. y = [7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]
  2216. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2217. x = np.array(x, order='F').reshape(2, -1)
  2218. y = np.array(y, order='C').reshape(2, -1)
  2219. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2220. def compare_results(res, desired):
  2221. for i in range(len(desired)):
  2222. assert_array_equal(res[i], desired[i])
  2223. class TestPercentile:
  2224. def test_basic(self):
  2225. x = np.arange(8) * 0.5
  2226. assert_equal(np.percentile(x, 0), 0.)
  2227. assert_equal(np.percentile(x, 100), 3.5)
  2228. assert_equal(np.percentile(x, 50), 1.75)
  2229. x[1] = np.nan
  2230. assert_equal(np.percentile(x, 0), np.nan)
  2231. assert_equal(np.percentile(x, 0, interpolation='nearest'), np.nan)
  2232. def test_fraction(self):
  2233. x = [Fraction(i, 2) for i in range(8)]
  2234. p = np.percentile(x, Fraction(0))
  2235. assert_equal(p, Fraction(0))
  2236. assert_equal(type(p), Fraction)
  2237. p = np.percentile(x, Fraction(100))
  2238. assert_equal(p, Fraction(7, 2))
  2239. assert_equal(type(p), Fraction)
  2240. p = np.percentile(x, Fraction(50))
  2241. assert_equal(p, Fraction(7, 4))
  2242. assert_equal(type(p), Fraction)
  2243. def test_api(self):
  2244. d = np.ones(5)
  2245. np.percentile(d, 5, None, None, False)
  2246. np.percentile(d, 5, None, None, False, 'linear')
  2247. o = np.ones((1,))
  2248. np.percentile(d, 5, None, o, False, 'linear')
  2249. def test_2D(self):
  2250. x = np.array([[1, 1, 1],
  2251. [1, 1, 1],
  2252. [4, 4, 3],
  2253. [1, 1, 1],
  2254. [1, 1, 1]])
  2255. assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1])
  2256. def test_linear(self):
  2257. # Test defaults
  2258. assert_equal(np.percentile(range(10), 50), 4.5)
  2259. # explicitly specify interpolation_method 'linear' (the default)
  2260. assert_equal(np.percentile(range(10), 50,
  2261. interpolation='linear'), 4.5)
  2262. def test_lower_higher(self):
  2263. # interpolation_method 'lower'/'higher'
  2264. assert_equal(np.percentile(range(10), 50,
  2265. interpolation='lower'), 4)
  2266. assert_equal(np.percentile(range(10), 50,
  2267. interpolation='higher'), 5)
  2268. def test_midpoint(self):
  2269. assert_equal(np.percentile(range(10), 51,
  2270. interpolation='midpoint'), 4.5)
  2271. assert_equal(np.percentile(range(11), 51,
  2272. interpolation='midpoint'), 5.5)
  2273. assert_equal(np.percentile(range(11), 50,
  2274. interpolation='midpoint'), 5)
  2275. def test_nearest(self):
  2276. assert_equal(np.percentile(range(10), 51,
  2277. interpolation='nearest'), 5)
  2278. assert_equal(np.percentile(range(10), 49,
  2279. interpolation='nearest'), 4)
  2280. def test_sequence(self):
  2281. x = np.arange(8) * 0.5
  2282. assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75])
  2283. def test_axis(self):
  2284. x = np.arange(12).reshape(3, 4)
  2285. assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0])
  2286. r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]
  2287. assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0)
  2288. r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]]
  2289. assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T)
  2290. # ensure qth axis is always first as with np.array(old_percentile(..))
  2291. x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
  2292. assert_equal(np.percentile(x, (25, 50)).shape, (2,))
  2293. assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,))
  2294. assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6))
  2295. assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6))
  2296. assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6))
  2297. assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5))
  2298. assert_equal(
  2299. np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6))
  2300. assert_equal(np.percentile(x, (25, 50),
  2301. interpolation="higher").shape, (2,))
  2302. assert_equal(np.percentile(x, (25, 50, 75),
  2303. interpolation="higher").shape, (3,))
  2304. assert_equal(np.percentile(x, (25, 50), axis=0,
  2305. interpolation="higher").shape, (2, 4, 5, 6))
  2306. assert_equal(np.percentile(x, (25, 50), axis=1,
  2307. interpolation="higher").shape, (2, 3, 5, 6))
  2308. assert_equal(np.percentile(x, (25, 50), axis=2,
  2309. interpolation="higher").shape, (2, 3, 4, 6))
  2310. assert_equal(np.percentile(x, (25, 50), axis=3,
  2311. interpolation="higher").shape, (2, 3, 4, 5))
  2312. assert_equal(np.percentile(x, (25, 50, 75), axis=1,
  2313. interpolation="higher").shape, (3, 3, 5, 6))
  2314. def test_scalar_q(self):
  2315. # test for no empty dimensions for compatibility with old percentile
  2316. x = np.arange(12).reshape(3, 4)
  2317. assert_equal(np.percentile(x, 50), 5.5)
  2318. assert_(np.isscalar(np.percentile(x, 50)))
  2319. r0 = np.array([4., 5., 6., 7.])
  2320. assert_equal(np.percentile(x, 50, axis=0), r0)
  2321. assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
  2322. r1 = np.array([1.5, 5.5, 9.5])
  2323. assert_almost_equal(np.percentile(x, 50, axis=1), r1)
  2324. assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)
  2325. out = np.empty(1)
  2326. assert_equal(np.percentile(x, 50, out=out), 5.5)
  2327. assert_equal(out, 5.5)
  2328. out = np.empty(4)
  2329. assert_equal(np.percentile(x, 50, axis=0, out=out), r0)
  2330. assert_equal(out, r0)
  2331. out = np.empty(3)
  2332. assert_equal(np.percentile(x, 50, axis=1, out=out), r1)
  2333. assert_equal(out, r1)
  2334. # test for no empty dimensions for compatibility with old percentile
  2335. x = np.arange(12).reshape(3, 4)
  2336. assert_equal(np.percentile(x, 50, interpolation='lower'), 5.)
  2337. assert_(np.isscalar(np.percentile(x, 50)))
  2338. r0 = np.array([4., 5., 6., 7.])
  2339. c0 = np.percentile(x, 50, interpolation='lower', axis=0)
  2340. assert_equal(c0, r0)
  2341. assert_equal(c0.shape, r0.shape)
  2342. r1 = np.array([1., 5., 9.])
  2343. c1 = np.percentile(x, 50, interpolation='lower', axis=1)
  2344. assert_almost_equal(c1, r1)
  2345. assert_equal(c1.shape, r1.shape)
  2346. out = np.empty((), dtype=x.dtype)
  2347. c = np.percentile(x, 50, interpolation='lower', out=out)
  2348. assert_equal(c, 5)
  2349. assert_equal(out, 5)
  2350. out = np.empty(4, dtype=x.dtype)
  2351. c = np.percentile(x, 50, interpolation='lower', axis=0, out=out)
  2352. assert_equal(c, r0)
  2353. assert_equal(out, r0)
  2354. out = np.empty(3, dtype=x.dtype)
  2355. c = np.percentile(x, 50, interpolation='lower', axis=1, out=out)
  2356. assert_equal(c, r1)
  2357. assert_equal(out, r1)
  2358. def test_exception(self):
  2359. assert_raises(ValueError, np.percentile, [1, 2], 56,
  2360. interpolation='foobar')
  2361. assert_raises(ValueError, np.percentile, [1], 101)
  2362. assert_raises(ValueError, np.percentile, [1], -1)
  2363. assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101])
  2364. assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1])
  2365. def test_percentile_list(self):
  2366. assert_equal(np.percentile([1, 2, 3], 0), 1)
  2367. def test_percentile_out(self):
  2368. x = np.array([1, 2, 3])
  2369. y = np.zeros((3,))
  2370. p = (1, 2, 3)
  2371. np.percentile(x, p, out=y)
  2372. assert_equal(y, np.percentile(x, p))
  2373. x = np.array([[1, 2, 3],
  2374. [4, 5, 6]])
  2375. y = np.zeros((3, 3))
  2376. np.percentile(x, p, axis=0, out=y)
  2377. assert_equal(y, np.percentile(x, p, axis=0))
  2378. y = np.zeros((3, 2))
  2379. np.percentile(x, p, axis=1, out=y)
  2380. assert_equal(y, np.percentile(x, p, axis=1))
  2381. x = np.arange(12).reshape(3, 4)
  2382. # q.dim > 1, float
  2383. r0 = np.array([[2., 3., 4., 5.], [4., 5., 6., 7.]])
  2384. out = np.empty((2, 4))
  2385. assert_equal(np.percentile(x, (25, 50), axis=0, out=out), r0)
  2386. assert_equal(out, r0)
  2387. r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]])
  2388. out = np.empty((2, 3))
  2389. assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)
  2390. assert_equal(out, r1)
  2391. # q.dim > 1, int
  2392. r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
  2393. out = np.empty((2, 4), dtype=x.dtype)
  2394. c = np.percentile(x, (25, 50), interpolation='lower', axis=0, out=out)
  2395. assert_equal(c, r0)
  2396. assert_equal(out, r0)
  2397. r1 = np.array([[0, 4, 8], [1, 5, 9]])
  2398. out = np.empty((2, 3), dtype=x.dtype)
  2399. c = np.percentile(x, (25, 50), interpolation='lower', axis=1, out=out)
  2400. assert_equal(c, r1)
  2401. assert_equal(out, r1)
  2402. def test_percentile_empty_dim(self):
  2403. # empty dims are preserved
  2404. d = np.arange(11 * 2).reshape(11, 1, 2, 1)
  2405. assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1))
  2406. assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1))
  2407. assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1))
  2408. assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2))
  2409. assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2))
  2410. assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1))
  2411. assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1))
  2412. assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1))
  2413. assert_array_equal(np.percentile(d, 50, axis=2,
  2414. interpolation='midpoint').shape,
  2415. (11, 1, 1))
  2416. assert_array_equal(np.percentile(d, 50, axis=-2,
  2417. interpolation='midpoint').shape,
  2418. (11, 1, 1))
  2419. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape,
  2420. (2, 1, 2, 1))
  2421. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape,
  2422. (2, 11, 2, 1))
  2423. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape,
  2424. (2, 11, 1, 1))
  2425. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape,
  2426. (2, 11, 1, 2))
  2427. def test_percentile_no_overwrite(self):
  2428. a = np.array([2, 3, 4, 1])
  2429. np.percentile(a, [50], overwrite_input=False)
  2430. assert_equal(a, np.array([2, 3, 4, 1]))
  2431. a = np.array([2, 3, 4, 1])
  2432. np.percentile(a, [50])
  2433. assert_equal(a, np.array([2, 3, 4, 1]))
  2434. def test_no_p_overwrite(self):
  2435. p = np.linspace(0., 100., num=5)
  2436. np.percentile(np.arange(100.), p, interpolation="midpoint")
  2437. assert_array_equal(p, np.linspace(0., 100., num=5))
  2438. p = np.linspace(0., 100., num=5).tolist()
  2439. np.percentile(np.arange(100.), p, interpolation="midpoint")
  2440. assert_array_equal(p, np.linspace(0., 100., num=5).tolist())
  2441. def test_percentile_overwrite(self):
  2442. a = np.array([2, 3, 4, 1])
  2443. b = np.percentile(a, [50], overwrite_input=True)
  2444. assert_equal(b, np.array([2.5]))
  2445. b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True)
  2446. assert_equal(b, np.array([2.5]))
  2447. def test_extended_axis(self):
  2448. o = np.random.normal(size=(71, 23))
  2449. x = np.dstack([o] * 10)
  2450. assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))
  2451. x = np.moveaxis(x, -1, 0)
  2452. assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))
  2453. x = x.swapaxes(0, 1).copy()
  2454. assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))
  2455. x = x.swapaxes(0, 1).copy()
  2456. assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),
  2457. np.percentile(x, [25, 60], axis=None))
  2458. assert_equal(np.percentile(x, [25, 60], axis=(0,)),
  2459. np.percentile(x, [25, 60], axis=0))
  2460. d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
  2461. np.random.shuffle(d.ravel())
  2462. assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0],
  2463. np.percentile(d[:,:,:, 0].flatten(), 25))
  2464. assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
  2465. np.percentile(d[:,:, 1,:].flatten(), [10, 90]))
  2466. assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],
  2467. np.percentile(d[:,:, 2,:].flatten(), 25))
  2468. assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],
  2469. np.percentile(d[2,:,:,:].flatten(), 25))
  2470. assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],
  2471. np.percentile(d[2, 1,:,:].flatten(), 25))
  2472. assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],
  2473. np.percentile(d[2,:,:, 1].flatten(), 25))
  2474. assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],
  2475. np.percentile(d[2,:, 2,:].flatten(), 25))
  2476. def test_extended_axis_invalid(self):
  2477. d = np.ones((3, 5, 7, 11))
  2478. assert_raises(np.AxisError, np.percentile, d, axis=-5, q=25)
  2479. assert_raises(np.AxisError, np.percentile, d, axis=(0, -5), q=25)
  2480. assert_raises(np.AxisError, np.percentile, d, axis=4, q=25)
  2481. assert_raises(np.AxisError, np.percentile, d, axis=(0, 4), q=25)
  2482. # each of these refers to the same axis twice
  2483. assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25)
  2484. assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25)
  2485. assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25)
  2486. def test_keepdims(self):
  2487. d = np.ones((3, 5, 7, 11))
  2488. assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape,
  2489. (1, 1, 1, 1))
  2490. assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape,
  2491. (1, 1, 7, 11))
  2492. assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape,
  2493. (1, 5, 7, 1))
  2494. assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape,
  2495. (3, 1, 7, 11))
  2496. assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape,
  2497. (1, 1, 1, 1))
  2498. assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape,
  2499. (1, 1, 7, 1))
  2500. assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3),
  2501. keepdims=True).shape, (2, 1, 1, 7, 1))
  2502. assert_equal(np.percentile(d, [1, 7], axis=(0, 3),
  2503. keepdims=True).shape, (2, 1, 5, 7, 1))
  2504. def test_out(self):
  2505. o = np.zeros((4,))
  2506. d = np.ones((3, 4))
  2507. assert_equal(np.percentile(d, 0, 0, out=o), o)
  2508. assert_equal(np.percentile(d, 0, 0, interpolation='nearest', out=o), o)
  2509. o = np.zeros((3,))
  2510. assert_equal(np.percentile(d, 1, 1, out=o), o)
  2511. assert_equal(np.percentile(d, 1, 1, interpolation='nearest', out=o), o)
  2512. o = np.zeros(())
  2513. assert_equal(np.percentile(d, 2, out=o), o)
  2514. assert_equal(np.percentile(d, 2, interpolation='nearest', out=o), o)
  2515. def test_out_nan(self):
  2516. with warnings.catch_warnings(record=True):
  2517. warnings.filterwarnings('always', '', RuntimeWarning)
  2518. o = np.zeros((4,))
  2519. d = np.ones((3, 4))
  2520. d[2, 1] = np.nan
  2521. assert_equal(np.percentile(d, 0, 0, out=o), o)
  2522. assert_equal(
  2523. np.percentile(d, 0, 0, interpolation='nearest', out=o), o)
  2524. o = np.zeros((3,))
  2525. assert_equal(np.percentile(d, 1, 1, out=o), o)
  2526. assert_equal(
  2527. np.percentile(d, 1, 1, interpolation='nearest', out=o), o)
  2528. o = np.zeros(())
  2529. assert_equal(np.percentile(d, 1, out=o), o)
  2530. assert_equal(
  2531. np.percentile(d, 1, interpolation='nearest', out=o), o)
  2532. def test_nan_behavior(self):
  2533. a = np.arange(24, dtype=float)
  2534. a[2] = np.nan
  2535. assert_equal(np.percentile(a, 0.3), np.nan)
  2536. assert_equal(np.percentile(a, 0.3, axis=0), np.nan)
  2537. assert_equal(np.percentile(a, [0.3, 0.6], axis=0),
  2538. np.array([np.nan] * 2))
  2539. a = np.arange(24, dtype=float).reshape(2, 3, 4)
  2540. a[1, 2, 3] = np.nan
  2541. a[1, 1, 2] = np.nan
  2542. # no axis
  2543. assert_equal(np.percentile(a, 0.3), np.nan)
  2544. assert_equal(np.percentile(a, 0.3).ndim, 0)
  2545. # axis0 zerod
  2546. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0)
  2547. b[2, 3] = np.nan
  2548. b[1, 2] = np.nan
  2549. assert_equal(np.percentile(a, 0.3, 0), b)
  2550. # axis0 not zerod
  2551. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  2552. [0.3, 0.6], 0)
  2553. b[:, 2, 3] = np.nan
  2554. b[:, 1, 2] = np.nan
  2555. assert_equal(np.percentile(a, [0.3, 0.6], 0), b)
  2556. # axis1 zerod
  2557. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1)
  2558. b[1, 3] = np.nan
  2559. b[1, 2] = np.nan
  2560. assert_equal(np.percentile(a, 0.3, 1), b)
  2561. # axis1 not zerod
  2562. b = np.percentile(
  2563. np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1)
  2564. b[:, 1, 3] = np.nan
  2565. b[:, 1, 2] = np.nan
  2566. assert_equal(np.percentile(a, [0.3, 0.6], 1), b)
  2567. # axis02 zerod
  2568. b = np.percentile(
  2569. np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2))
  2570. b[1] = np.nan
  2571. b[2] = np.nan
  2572. assert_equal(np.percentile(a, 0.3, (0, 2)), b)
  2573. # axis02 not zerod
  2574. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  2575. [0.3, 0.6], (0, 2))
  2576. b[:, 1] = np.nan
  2577. b[:, 2] = np.nan
  2578. assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b)
  2579. # axis02 not zerod with nearest interpolation
  2580. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  2581. [0.3, 0.6], (0, 2), interpolation='nearest')
  2582. b[:, 1] = np.nan
  2583. b[:, 2] = np.nan
  2584. assert_equal(np.percentile(
  2585. a, [0.3, 0.6], (0, 2), interpolation='nearest'), b)
  2586. class TestQuantile:
  2587. # most of this is already tested by TestPercentile
  2588. def test_basic(self):
  2589. x = np.arange(8) * 0.5
  2590. assert_equal(np.quantile(x, 0), 0.)
  2591. assert_equal(np.quantile(x, 1), 3.5)
  2592. assert_equal(np.quantile(x, 0.5), 1.75)
  2593. def test_correct_quantile_value(self):
  2594. a = np.array([True])
  2595. tf_quant = np.quantile(True, False)
  2596. assert_equal(tf_quant, a[0])
  2597. assert_equal(type(tf_quant), a.dtype)
  2598. a = np.array([False, True, True])
  2599. quant_res = np.quantile(a, a)
  2600. assert_array_equal(quant_res, a)
  2601. assert_equal(a.dtype, quant_res.dtype)
  2602. def test_fraction(self):
  2603. # fractional input, integral quantile
  2604. x = [Fraction(i, 2) for i in range(8)]
  2605. q = np.quantile(x, 0)
  2606. assert_equal(q, 0)
  2607. assert_equal(type(q), Fraction)
  2608. q = np.quantile(x, 1)
  2609. assert_equal(q, Fraction(7, 2))
  2610. assert_equal(type(q), Fraction)
  2611. q = np.quantile(x, Fraction(1, 2))
  2612. assert_equal(q, Fraction(7, 4))
  2613. assert_equal(type(q), Fraction)
  2614. # repeat with integral input but fractional quantile
  2615. x = np.arange(8)
  2616. assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))
  2617. def test_no_p_overwrite(self):
  2618. # this is worth retesting, because quantile does not make a copy
  2619. p0 = np.array([0, 0.75, 0.25, 0.5, 1.0])
  2620. p = p0.copy()
  2621. np.quantile(np.arange(100.), p, interpolation="midpoint")
  2622. assert_array_equal(p, p0)
  2623. p0 = p0.tolist()
  2624. p = p.tolist()
  2625. np.quantile(np.arange(100.), p, interpolation="midpoint")
  2626. assert_array_equal(p, p0)
  2627. def test_quantile_monotonic(self):
  2628. # GH 14685
  2629. # test that the return value of quantile is monotonic if p0 is ordered
  2630. p0 = np.arange(0, 1, 0.01)
  2631. quantile = np.quantile(np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9,
  2632. 8, 8, 7]) * 0.1, p0)
  2633. assert_equal(np.sort(quantile), quantile)
  2634. @hypothesis.given(
  2635. arr=arrays(dtype=np.float64,
  2636. shape=st.integers(min_value=3, max_value=1000),
  2637. elements=st.floats(allow_infinity=False, allow_nan=False,
  2638. min_value=-1e300, max_value=1e300)))
  2639. def test_quantile_monotonic_hypo(self, arr):
  2640. p0 = np.arange(0, 1, 0.01)
  2641. quantile = np.quantile(arr, p0)
  2642. assert_equal(np.sort(quantile), quantile)
  2643. class TestLerp:
  2644. @hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,
  2645. min_value=0, max_value=1),
  2646. t1=st.floats(allow_nan=False, allow_infinity=False,
  2647. min_value=0, max_value=1),
  2648. a = st.floats(allow_nan=False, allow_infinity=False,
  2649. min_value=-1e300, max_value=1e300),
  2650. b = st.floats(allow_nan=False, allow_infinity=False,
  2651. min_value=-1e300, max_value=1e300))
  2652. def test_lerp_monotonic(self, t0, t1, a, b):
  2653. l0 = np.lib.function_base._lerp(a, b, t0)
  2654. l1 = np.lib.function_base._lerp(a, b, t1)
  2655. if t0 == t1 or a == b:
  2656. assert l0 == l1 # uninteresting
  2657. elif (t0 < t1) == (a < b):
  2658. assert l0 <= l1
  2659. else:
  2660. assert l0 >= l1
  2661. @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
  2662. min_value=0, max_value=1),
  2663. a=st.floats(allow_nan=False, allow_infinity=False,
  2664. min_value=-1e300, max_value=1e300),
  2665. b=st.floats(allow_nan=False, allow_infinity=False,
  2666. min_value=-1e300, max_value=1e300))
  2667. def test_lerp_bounded(self, t, a, b):
  2668. if a <= b:
  2669. assert a <= np.lib.function_base._lerp(a, b, t) <= b
  2670. else:
  2671. assert b <= np.lib.function_base._lerp(a, b, t) <= a
  2672. @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
  2673. min_value=0, max_value=1),
  2674. a=st.floats(allow_nan=False, allow_infinity=False,
  2675. min_value=-1e300, max_value=1e300),
  2676. b=st.floats(allow_nan=False, allow_infinity=False,
  2677. min_value=-1e300, max_value=1e300))
  2678. def test_lerp_symmetric(self, t, a, b):
  2679. # double subtraction is needed to remove the extra precision of t < 0.5
  2680. left = np.lib.function_base._lerp(a, b, 1 - (1 - t))
  2681. right = np.lib.function_base._lerp(b, a, 1 - t)
  2682. assert left == right
  2683. def test_lerp_0d_inputs(self):
  2684. a = np.array(2)
  2685. b = np.array(5)
  2686. t = np.array(0.2)
  2687. assert np.lib.function_base._lerp(a, b, t) == 2.6
  2688. class TestMedian:
  2689. def test_basic(self):
  2690. a0 = np.array(1)
  2691. a1 = np.arange(2)
  2692. a2 = np.arange(6).reshape(2, 3)
  2693. assert_equal(np.median(a0), 1)
  2694. assert_allclose(np.median(a1), 0.5)
  2695. assert_allclose(np.median(a2), 2.5)
  2696. assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5])
  2697. assert_equal(np.median(a2, axis=1), [1, 4])
  2698. assert_allclose(np.median(a2, axis=None), 2.5)
  2699. a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775])
  2700. assert_almost_equal((a[1] + a[3]) / 2., np.median(a))
  2701. a = np.array([0.0463301, 0.0444502, 0.141249])
  2702. assert_equal(a[0], np.median(a))
  2703. a = np.array([0.0444502, 0.141249, 0.0463301])
  2704. assert_equal(a[-1], np.median(a))
  2705. # check array scalar result
  2706. assert_equal(np.median(a).ndim, 0)
  2707. a[1] = np.nan
  2708. assert_equal(np.median(a).ndim, 0)
  2709. def test_axis_keyword(self):
  2710. a3 = np.array([[2, 3],
  2711. [0, 1],
  2712. [6, 7],
  2713. [4, 5]])
  2714. for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:
  2715. orig = a.copy()
  2716. np.median(a, axis=None)
  2717. for ax in range(a.ndim):
  2718. np.median(a, axis=ax)
  2719. assert_array_equal(a, orig)
  2720. assert_allclose(np.median(a3, axis=0), [3, 4])
  2721. assert_allclose(np.median(a3.T, axis=1), [3, 4])
  2722. assert_allclose(np.median(a3), 3.5)
  2723. assert_allclose(np.median(a3, axis=None), 3.5)
  2724. assert_allclose(np.median(a3.T), 3.5)
  2725. def test_overwrite_keyword(self):
  2726. a3 = np.array([[2, 3],
  2727. [0, 1],
  2728. [6, 7],
  2729. [4, 5]])
  2730. a0 = np.array(1)
  2731. a1 = np.arange(2)
  2732. a2 = np.arange(6).reshape(2, 3)
  2733. assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)
  2734. assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)
  2735. assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)
  2736. assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=0),
  2737. [1.5, 2.5, 3.5])
  2738. assert_allclose(
  2739. np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])
  2740. assert_allclose(
  2741. np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)
  2742. assert_allclose(
  2743. np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4])
  2744. assert_allclose(np.median(a3.T.copy(), overwrite_input=True, axis=1),
  2745. [3, 4])
  2746. a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
  2747. np.random.shuffle(a4.ravel())
  2748. assert_allclose(np.median(a4, axis=None),
  2749. np.median(a4.copy(), axis=None, overwrite_input=True))
  2750. assert_allclose(np.median(a4, axis=0),
  2751. np.median(a4.copy(), axis=0, overwrite_input=True))
  2752. assert_allclose(np.median(a4, axis=1),
  2753. np.median(a4.copy(), axis=1, overwrite_input=True))
  2754. assert_allclose(np.median(a4, axis=2),
  2755. np.median(a4.copy(), axis=2, overwrite_input=True))
  2756. def test_array_like(self):
  2757. x = [1, 2, 3]
  2758. assert_almost_equal(np.median(x), 2)
  2759. x2 = [x]
  2760. assert_almost_equal(np.median(x2), 2)
  2761. assert_allclose(np.median(x2, axis=0), x)
  2762. def test_subclass(self):
  2763. # gh-3846
  2764. class MySubClass(np.ndarray):
  2765. def __new__(cls, input_array, info=None):
  2766. obj = np.asarray(input_array).view(cls)
  2767. obj.info = info
  2768. return obj
  2769. def mean(self, axis=None, dtype=None, out=None):
  2770. return -7
  2771. a = MySubClass([1, 2, 3])
  2772. assert_equal(np.median(a), -7)
  2773. def test_out(self):
  2774. o = np.zeros((4,))
  2775. d = np.ones((3, 4))
  2776. assert_equal(np.median(d, 0, out=o), o)
  2777. o = np.zeros((3,))
  2778. assert_equal(np.median(d, 1, out=o), o)
  2779. o = np.zeros(())
  2780. assert_equal(np.median(d, out=o), o)
  2781. def test_out_nan(self):
  2782. with warnings.catch_warnings(record=True):
  2783. warnings.filterwarnings('always', '', RuntimeWarning)
  2784. o = np.zeros((4,))
  2785. d = np.ones((3, 4))
  2786. d[2, 1] = np.nan
  2787. assert_equal(np.median(d, 0, out=o), o)
  2788. o = np.zeros((3,))
  2789. assert_equal(np.median(d, 1, out=o), o)
  2790. o = np.zeros(())
  2791. assert_equal(np.median(d, out=o), o)
  2792. def test_nan_behavior(self):
  2793. a = np.arange(24, dtype=float)
  2794. a[2] = np.nan
  2795. assert_equal(np.median(a), np.nan)
  2796. assert_equal(np.median(a, axis=0), np.nan)
  2797. a = np.arange(24, dtype=float).reshape(2, 3, 4)
  2798. a[1, 2, 3] = np.nan
  2799. a[1, 1, 2] = np.nan
  2800. # no axis
  2801. assert_equal(np.median(a), np.nan)
  2802. assert_equal(np.median(a).ndim, 0)
  2803. # axis0
  2804. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 0)
  2805. b[2, 3] = np.nan
  2806. b[1, 2] = np.nan
  2807. assert_equal(np.median(a, 0), b)
  2808. # axis1
  2809. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 1)
  2810. b[1, 3] = np.nan
  2811. b[1, 2] = np.nan
  2812. assert_equal(np.median(a, 1), b)
  2813. # axis02
  2814. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), (0, 2))
  2815. b[1] = np.nan
  2816. b[2] = np.nan
  2817. assert_equal(np.median(a, (0, 2)), b)
  2818. def test_empty(self):
  2819. # mean(empty array) emits two warnings: empty slice and divide by 0
  2820. a = np.array([], dtype=float)
  2821. with warnings.catch_warnings(record=True) as w:
  2822. warnings.filterwarnings('always', '', RuntimeWarning)
  2823. assert_equal(np.median(a), np.nan)
  2824. assert_(w[0].category is RuntimeWarning)
  2825. assert_equal(len(w), 2)
  2826. # multiple dimensions
  2827. a = np.array([], dtype=float, ndmin=3)
  2828. # no axis
  2829. with warnings.catch_warnings(record=True) as w:
  2830. warnings.filterwarnings('always', '', RuntimeWarning)
  2831. assert_equal(np.median(a), np.nan)
  2832. assert_(w[0].category is RuntimeWarning)
  2833. # axis 0 and 1
  2834. b = np.array([], dtype=float, ndmin=2)
  2835. assert_equal(np.median(a, axis=0), b)
  2836. assert_equal(np.median(a, axis=1), b)
  2837. # axis 2
  2838. b = np.array(np.nan, dtype=float, ndmin=2)
  2839. with warnings.catch_warnings(record=True) as w:
  2840. warnings.filterwarnings('always', '', RuntimeWarning)
  2841. assert_equal(np.median(a, axis=2), b)
  2842. assert_(w[0].category is RuntimeWarning)
  2843. def test_object(self):
  2844. o = np.arange(7.)
  2845. assert_(type(np.median(o.astype(object))), float)
  2846. o[2] = np.nan
  2847. assert_(type(np.median(o.astype(object))), float)
  2848. def test_extended_axis(self):
  2849. o = np.random.normal(size=(71, 23))
  2850. x = np.dstack([o] * 10)
  2851. assert_equal(np.median(x, axis=(0, 1)), np.median(o))
  2852. x = np.moveaxis(x, -1, 0)
  2853. assert_equal(np.median(x, axis=(-2, -1)), np.median(o))
  2854. x = x.swapaxes(0, 1).copy()
  2855. assert_equal(np.median(x, axis=(0, -1)), np.median(o))
  2856. assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))
  2857. assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))
  2858. assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))
  2859. d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
  2860. np.random.shuffle(d.ravel())
  2861. assert_equal(np.median(d, axis=(0, 1, 2))[0],
  2862. np.median(d[:,:,:, 0].flatten()))
  2863. assert_equal(np.median(d, axis=(0, 1, 3))[1],
  2864. np.median(d[:,:, 1,:].flatten()))
  2865. assert_equal(np.median(d, axis=(3, 1, -4))[2],
  2866. np.median(d[:,:, 2,:].flatten()))
  2867. assert_equal(np.median(d, axis=(3, 1, 2))[2],
  2868. np.median(d[2,:,:,:].flatten()))
  2869. assert_equal(np.median(d, axis=(3, 2))[2, 1],
  2870. np.median(d[2, 1,:,:].flatten()))
  2871. assert_equal(np.median(d, axis=(1, -2))[2, 1],
  2872. np.median(d[2,:,:, 1].flatten()))
  2873. assert_equal(np.median(d, axis=(1, 3))[2, 2],
  2874. np.median(d[2,:, 2,:].flatten()))
  2875. def test_extended_axis_invalid(self):
  2876. d = np.ones((3, 5, 7, 11))
  2877. assert_raises(np.AxisError, np.median, d, axis=-5)
  2878. assert_raises(np.AxisError, np.median, d, axis=(0, -5))
  2879. assert_raises(np.AxisError, np.median, d, axis=4)
  2880. assert_raises(np.AxisError, np.median, d, axis=(0, 4))
  2881. assert_raises(ValueError, np.median, d, axis=(1, 1))
  2882. def test_keepdims(self):
  2883. d = np.ones((3, 5, 7, 11))
  2884. assert_equal(np.median(d, axis=None, keepdims=True).shape,
  2885. (1, 1, 1, 1))
  2886. assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape,
  2887. (1, 1, 7, 11))
  2888. assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape,
  2889. (1, 5, 7, 1))
  2890. assert_equal(np.median(d, axis=(1,), keepdims=True).shape,
  2891. (3, 1, 7, 11))
  2892. assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape,
  2893. (1, 1, 1, 1))
  2894. assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape,
  2895. (1, 1, 7, 1))
  2896. class TestAdd_newdoc_ufunc:
  2897. def test_ufunc_arg(self):
  2898. assert_raises(TypeError, add_newdoc_ufunc, 2, "blah")
  2899. assert_raises(ValueError, add_newdoc_ufunc, np.add, "blah")
  2900. def test_string_arg(self):
  2901. assert_raises(TypeError, add_newdoc_ufunc, np.add, 3)
  2902. class TestAdd_newdoc:
  2903. @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
  2904. @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc")
  2905. def test_add_doc(self):
  2906. # test that np.add_newdoc did attach a docstring successfully:
  2907. tgt = "Current flat index into the array."
  2908. assert_equal(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
  2909. assert_(len(np.core.ufunc.identity.__doc__) > 300)
  2910. assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300)
  2911. @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
  2912. def test_errors_are_ignored(self):
  2913. prev_doc = np.core.flatiter.index.__doc__
  2914. # nothing changed, but error ignored, this should probably
  2915. # give a warning (or even error) in the future.
  2916. np.add_newdoc("numpy.core", "flatiter", ("index", "bad docstring"))
  2917. assert prev_doc == np.core.flatiter.index.__doc__
  2918. class TestAddDocstring():
  2919. # Test should possibly be moved, but it also fits to be close to
  2920. # the newdoc tests...
  2921. @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
  2922. @pytest.mark.skipif(IS_PYPY, reason="PyPy does not modify tp_doc")
  2923. def test_add_same_docstring(self):
  2924. # test for attributes (which are C-level defined)
  2925. np.add_docstring(np.ndarray.flat, np.ndarray.flat.__doc__)
  2926. # And typical functions:
  2927. def func():
  2928. """docstring"""
  2929. return
  2930. np.add_docstring(func, func.__doc__)
  2931. @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
  2932. def test_different_docstring_fails(self):
  2933. # test for attributes (which are C-level defined)
  2934. with assert_raises(RuntimeError):
  2935. np.add_docstring(np.ndarray.flat, "different docstring")
  2936. # And typical functions:
  2937. def func():
  2938. """docstring"""
  2939. return
  2940. with assert_raises(RuntimeError):
  2941. np.add_docstring(func, "different docstring")
  2942. class TestSortComplex:
  2943. @pytest.mark.parametrize("type_in, type_out", [
  2944. ('l', 'D'),
  2945. ('h', 'F'),
  2946. ('H', 'F'),
  2947. ('b', 'F'),
  2948. ('B', 'F'),
  2949. ('g', 'G'),
  2950. ])
  2951. def test_sort_real(self, type_in, type_out):
  2952. # sort_complex() type casting for real input types
  2953. a = np.array([5, 3, 6, 2, 1], dtype=type_in)
  2954. actual = np.sort_complex(a)
  2955. expected = np.sort(a).astype(type_out)
  2956. assert_equal(actual, expected)
  2957. assert_equal(actual.dtype, expected.dtype)
  2958. def test_sort_complex(self):
  2959. # sort_complex() handling of complex input
  2960. a = np.array([2 + 3j, 1 - 2j, 1 - 3j, 2 + 1j], dtype='D')
  2961. expected = np.array([1 - 3j, 1 - 2j, 2 + 1j, 2 + 3j], dtype='D')
  2962. actual = np.sort_complex(a)
  2963. assert_equal(actual, expected)
  2964. assert_equal(actual.dtype, expected.dtype)