test_function_base.py 146 KB

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