test_function_base.py 115 KB

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