test_function_base.py 154 KB

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