test_numeric.py 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608
  1. import sys
  2. import warnings
  3. import itertools
  4. import platform
  5. import pytest
  6. import math
  7. from decimal import Decimal
  8. import numpy as np
  9. from numpy.core import umath
  10. from numpy.random import rand, randint, randn
  11. from numpy.testing import (
  12. assert_, assert_equal, assert_raises, assert_raises_regex,
  13. assert_array_equal, assert_almost_equal, assert_array_almost_equal,
  14. assert_warns, assert_array_max_ulp, HAS_REFCOUNT, IS_WASM
  15. )
  16. from numpy.core._rational_tests import rational
  17. from hypothesis import given, strategies as st
  18. from hypothesis.extra import numpy as hynp
  19. class TestResize:
  20. def test_copies(self):
  21. A = np.array([[1, 2], [3, 4]])
  22. Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
  23. assert_equal(np.resize(A, (2, 4)), Ar1)
  24. Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
  25. assert_equal(np.resize(A, (4, 2)), Ar2)
  26. Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])
  27. assert_equal(np.resize(A, (4, 3)), Ar3)
  28. def test_repeats(self):
  29. A = np.array([1, 2, 3])
  30. Ar1 = np.array([[1, 2, 3, 1], [2, 3, 1, 2]])
  31. assert_equal(np.resize(A, (2, 4)), Ar1)
  32. Ar2 = np.array([[1, 2], [3, 1], [2, 3], [1, 2]])
  33. assert_equal(np.resize(A, (4, 2)), Ar2)
  34. Ar3 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
  35. assert_equal(np.resize(A, (4, 3)), Ar3)
  36. def test_zeroresize(self):
  37. A = np.array([[1, 2], [3, 4]])
  38. Ar = np.resize(A, (0,))
  39. assert_array_equal(Ar, np.array([]))
  40. assert_equal(A.dtype, Ar.dtype)
  41. Ar = np.resize(A, (0, 2))
  42. assert_equal(Ar.shape, (0, 2))
  43. Ar = np.resize(A, (2, 0))
  44. assert_equal(Ar.shape, (2, 0))
  45. def test_reshape_from_zero(self):
  46. # See also gh-6740
  47. A = np.zeros(0, dtype=[('a', np.float32)])
  48. Ar = np.resize(A, (2, 1))
  49. assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))
  50. assert_equal(A.dtype, Ar.dtype)
  51. def test_negative_resize(self):
  52. A = np.arange(0, 10, dtype=np.float32)
  53. new_shape = (-10, -1)
  54. with pytest.raises(ValueError, match=r"negative"):
  55. np.resize(A, new_shape=new_shape)
  56. def test_subclass(self):
  57. class MyArray(np.ndarray):
  58. __array_priority__ = 1.
  59. my_arr = np.array([1]).view(MyArray)
  60. assert type(np.resize(my_arr, 5)) is MyArray
  61. assert type(np.resize(my_arr, 0)) is MyArray
  62. my_arr = np.array([]).view(MyArray)
  63. assert type(np.resize(my_arr, 5)) is MyArray
  64. class TestNonarrayArgs:
  65. # check that non-array arguments to functions wrap them in arrays
  66. def test_choose(self):
  67. choices = [[0, 1, 2],
  68. [3, 4, 5],
  69. [5, 6, 7]]
  70. tgt = [5, 1, 5]
  71. a = [2, 0, 1]
  72. out = np.choose(a, choices)
  73. assert_equal(out, tgt)
  74. def test_clip(self):
  75. arr = [-1, 5, 2, 3, 10, -4, -9]
  76. out = np.clip(arr, 2, 7)
  77. tgt = [2, 5, 2, 3, 7, 2, 2]
  78. assert_equal(out, tgt)
  79. def test_compress(self):
  80. arr = [[0, 1, 2, 3, 4],
  81. [5, 6, 7, 8, 9]]
  82. tgt = [[5, 6, 7, 8, 9]]
  83. out = np.compress([0, 1], arr, axis=0)
  84. assert_equal(out, tgt)
  85. def test_count_nonzero(self):
  86. arr = [[0, 1, 7, 0, 0],
  87. [3, 0, 0, 2, 19]]
  88. tgt = np.array([2, 3])
  89. out = np.count_nonzero(arr, axis=1)
  90. assert_equal(out, tgt)
  91. def test_cumproduct(self):
  92. A = [[1, 2, 3], [4, 5, 6]]
  93. assert_(np.all(np.cumproduct(A) == np.array([1, 2, 6, 24, 120, 720])))
  94. def test_diagonal(self):
  95. a = [[0, 1, 2, 3],
  96. [4, 5, 6, 7],
  97. [8, 9, 10, 11]]
  98. out = np.diagonal(a)
  99. tgt = [0, 5, 10]
  100. assert_equal(out, tgt)
  101. def test_mean(self):
  102. A = [[1, 2, 3], [4, 5, 6]]
  103. assert_(np.mean(A) == 3.5)
  104. assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])))
  105. assert_(np.all(np.mean(A, 1) == np.array([2., 5.])))
  106. with warnings.catch_warnings(record=True) as w:
  107. warnings.filterwarnings('always', '', RuntimeWarning)
  108. assert_(np.isnan(np.mean([])))
  109. assert_(w[0].category is RuntimeWarning)
  110. def test_ptp(self):
  111. a = [3, 4, 5, 10, -3, -5, 6.0]
  112. assert_equal(np.ptp(a, axis=0), 15.0)
  113. def test_prod(self):
  114. arr = [[1, 2, 3, 4],
  115. [5, 6, 7, 9],
  116. [10, 3, 4, 5]]
  117. tgt = [24, 1890, 600]
  118. assert_equal(np.prod(arr, axis=-1), tgt)
  119. def test_ravel(self):
  120. a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  121. tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  122. assert_equal(np.ravel(a), tgt)
  123. def test_repeat(self):
  124. a = [1, 2, 3]
  125. tgt = [1, 1, 2, 2, 3, 3]
  126. out = np.repeat(a, 2)
  127. assert_equal(out, tgt)
  128. def test_reshape(self):
  129. arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  130. tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
  131. assert_equal(np.reshape(arr, (2, 6)), tgt)
  132. def test_round(self):
  133. arr = [1.56, 72.54, 6.35, 3.25]
  134. tgt = [1.6, 72.5, 6.4, 3.2]
  135. assert_equal(np.around(arr, decimals=1), tgt)
  136. s = np.float64(1.)
  137. assert_(isinstance(s.round(), np.float64))
  138. assert_equal(s.round(), 1.)
  139. @pytest.mark.parametrize('dtype', [
  140. np.int8, np.int16, np.int32, np.int64,
  141. np.uint8, np.uint16, np.uint32, np.uint64,
  142. np.float16, np.float32, np.float64,
  143. ])
  144. def test_dunder_round(self, dtype):
  145. s = dtype(1)
  146. assert_(isinstance(round(s), int))
  147. assert_(isinstance(round(s, None), int))
  148. assert_(isinstance(round(s, ndigits=None), int))
  149. assert_equal(round(s), 1)
  150. assert_equal(round(s, None), 1)
  151. assert_equal(round(s, ndigits=None), 1)
  152. @pytest.mark.parametrize('val, ndigits', [
  153. pytest.param(2**31 - 1, -1,
  154. marks=pytest.mark.xfail(reason="Out of range of int32")
  155. ),
  156. (2**31 - 1, 1-math.ceil(math.log10(2**31 - 1))),
  157. (2**31 - 1, -math.ceil(math.log10(2**31 - 1)))
  158. ])
  159. def test_dunder_round_edgecases(self, val, ndigits):
  160. assert_equal(round(val, ndigits), round(np.int32(val), ndigits))
  161. def test_dunder_round_accuracy(self):
  162. f = np.float64(5.1 * 10**73)
  163. assert_(isinstance(round(f, -73), np.float64))
  164. assert_array_max_ulp(round(f, -73), 5.0 * 10**73)
  165. assert_(isinstance(round(f, ndigits=-73), np.float64))
  166. assert_array_max_ulp(round(f, ndigits=-73), 5.0 * 10**73)
  167. i = np.int64(501)
  168. assert_(isinstance(round(i, -2), np.int64))
  169. assert_array_max_ulp(round(i, -2), 500)
  170. assert_(isinstance(round(i, ndigits=-2), np.int64))
  171. assert_array_max_ulp(round(i, ndigits=-2), 500)
  172. @pytest.mark.xfail(raises=AssertionError, reason="gh-15896")
  173. def test_round_py_consistency(self):
  174. f = 5.1 * 10**73
  175. assert_equal(round(np.float64(f), -73), round(f, -73))
  176. def test_searchsorted(self):
  177. arr = [-8, -5, -1, 3, 6, 10]
  178. out = np.searchsorted(arr, 0)
  179. assert_equal(out, 3)
  180. def test_size(self):
  181. A = [[1, 2, 3], [4, 5, 6]]
  182. assert_(np.size(A) == 6)
  183. assert_(np.size(A, 0) == 2)
  184. assert_(np.size(A, 1) == 3)
  185. def test_squeeze(self):
  186. A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]
  187. assert_equal(np.squeeze(A).shape, (3, 3))
  188. assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))
  189. assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))
  190. assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))
  191. assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))
  192. assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))
  193. assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))
  194. assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))
  195. assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))
  196. def test_std(self):
  197. A = [[1, 2, 3], [4, 5, 6]]
  198. assert_almost_equal(np.std(A), 1.707825127659933)
  199. assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5]))
  200. assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658]))
  201. with warnings.catch_warnings(record=True) as w:
  202. warnings.filterwarnings('always', '', RuntimeWarning)
  203. assert_(np.isnan(np.std([])))
  204. assert_(w[0].category is RuntimeWarning)
  205. def test_swapaxes(self):
  206. tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]]
  207. a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
  208. out = np.swapaxes(a, 0, 2)
  209. assert_equal(out, tgt)
  210. def test_sum(self):
  211. m = [[1, 2, 3],
  212. [4, 5, 6],
  213. [7, 8, 9]]
  214. tgt = [[6], [15], [24]]
  215. out = np.sum(m, axis=1, keepdims=True)
  216. assert_equal(tgt, out)
  217. def test_take(self):
  218. tgt = [2, 3, 5]
  219. indices = [1, 2, 4]
  220. a = [1, 2, 3, 4, 5]
  221. out = np.take(a, indices)
  222. assert_equal(out, tgt)
  223. def test_trace(self):
  224. c = [[1, 2], [3, 4], [5, 6]]
  225. assert_equal(np.trace(c), 5)
  226. def test_transpose(self):
  227. arr = [[1, 2], [3, 4], [5, 6]]
  228. tgt = [[1, 3, 5], [2, 4, 6]]
  229. assert_equal(np.transpose(arr, (1, 0)), tgt)
  230. def test_var(self):
  231. A = [[1, 2, 3], [4, 5, 6]]
  232. assert_almost_equal(np.var(A), 2.9166666666666665)
  233. assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25]))
  234. assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667]))
  235. with warnings.catch_warnings(record=True) as w:
  236. warnings.filterwarnings('always', '', RuntimeWarning)
  237. assert_(np.isnan(np.var([])))
  238. assert_(w[0].category is RuntimeWarning)
  239. B = np.array([None, 0])
  240. B[0] = 1j
  241. assert_almost_equal(np.var(B), 0.25)
  242. class TestIsscalar:
  243. def test_isscalar(self):
  244. assert_(np.isscalar(3.1))
  245. assert_(np.isscalar(np.int16(12345)))
  246. assert_(np.isscalar(False))
  247. assert_(np.isscalar('numpy'))
  248. assert_(not np.isscalar([3.1]))
  249. assert_(not np.isscalar(None))
  250. # PEP 3141
  251. from fractions import Fraction
  252. assert_(np.isscalar(Fraction(5, 17)))
  253. from numbers import Number
  254. assert_(np.isscalar(Number()))
  255. class TestBoolScalar:
  256. def test_logical(self):
  257. f = np.False_
  258. t = np.True_
  259. s = "xyz"
  260. assert_((t and s) is s)
  261. assert_((f and s) is f)
  262. def test_bitwise_or(self):
  263. f = np.False_
  264. t = np.True_
  265. assert_((t | t) is t)
  266. assert_((f | t) is t)
  267. assert_((t | f) is t)
  268. assert_((f | f) is f)
  269. def test_bitwise_and(self):
  270. f = np.False_
  271. t = np.True_
  272. assert_((t & t) is t)
  273. assert_((f & t) is f)
  274. assert_((t & f) is f)
  275. assert_((f & f) is f)
  276. def test_bitwise_xor(self):
  277. f = np.False_
  278. t = np.True_
  279. assert_((t ^ t) is f)
  280. assert_((f ^ t) is t)
  281. assert_((t ^ f) is t)
  282. assert_((f ^ f) is f)
  283. class TestBoolArray:
  284. def setup_method(self):
  285. # offset for simd tests
  286. self.t = np.array([True] * 41, dtype=bool)[1::]
  287. self.f = np.array([False] * 41, dtype=bool)[1::]
  288. self.o = np.array([False] * 42, dtype=bool)[2::]
  289. self.nm = self.f.copy()
  290. self.im = self.t.copy()
  291. self.nm[3] = True
  292. self.nm[-2] = True
  293. self.im[3] = False
  294. self.im[-2] = False
  295. def test_all_any(self):
  296. assert_(self.t.all())
  297. assert_(self.t.any())
  298. assert_(not self.f.all())
  299. assert_(not self.f.any())
  300. assert_(self.nm.any())
  301. assert_(self.im.any())
  302. assert_(not self.nm.all())
  303. assert_(not self.im.all())
  304. # check bad element in all positions
  305. for i in range(256 - 7):
  306. d = np.array([False] * 256, dtype=bool)[7::]
  307. d[i] = True
  308. assert_(np.any(d))
  309. e = np.array([True] * 256, dtype=bool)[7::]
  310. e[i] = False
  311. assert_(not np.all(e))
  312. assert_array_equal(e, ~d)
  313. # big array test for blocked libc loops
  314. for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
  315. d = np.array([False] * 100043, dtype=bool)
  316. d[i] = True
  317. assert_(np.any(d), msg="%r" % i)
  318. e = np.array([True] * 100043, dtype=bool)
  319. e[i] = False
  320. assert_(not np.all(e), msg="%r" % i)
  321. def test_logical_not_abs(self):
  322. assert_array_equal(~self.t, self.f)
  323. assert_array_equal(np.abs(~self.t), self.f)
  324. assert_array_equal(np.abs(~self.f), self.t)
  325. assert_array_equal(np.abs(self.f), self.f)
  326. assert_array_equal(~np.abs(self.f), self.t)
  327. assert_array_equal(~np.abs(self.t), self.f)
  328. assert_array_equal(np.abs(~self.nm), self.im)
  329. np.logical_not(self.t, out=self.o)
  330. assert_array_equal(self.o, self.f)
  331. np.abs(self.t, out=self.o)
  332. assert_array_equal(self.o, self.t)
  333. def test_logical_and_or_xor(self):
  334. assert_array_equal(self.t | self.t, self.t)
  335. assert_array_equal(self.f | self.f, self.f)
  336. assert_array_equal(self.t | self.f, self.t)
  337. assert_array_equal(self.f | self.t, self.t)
  338. np.logical_or(self.t, self.t, out=self.o)
  339. assert_array_equal(self.o, self.t)
  340. assert_array_equal(self.t & self.t, self.t)
  341. assert_array_equal(self.f & self.f, self.f)
  342. assert_array_equal(self.t & self.f, self.f)
  343. assert_array_equal(self.f & self.t, self.f)
  344. np.logical_and(self.t, self.t, out=self.o)
  345. assert_array_equal(self.o, self.t)
  346. assert_array_equal(self.t ^ self.t, self.f)
  347. assert_array_equal(self.f ^ self.f, self.f)
  348. assert_array_equal(self.t ^ self.f, self.t)
  349. assert_array_equal(self.f ^ self.t, self.t)
  350. np.logical_xor(self.t, self.t, out=self.o)
  351. assert_array_equal(self.o, self.f)
  352. assert_array_equal(self.nm & self.t, self.nm)
  353. assert_array_equal(self.im & self.f, False)
  354. assert_array_equal(self.nm & True, self.nm)
  355. assert_array_equal(self.im & False, self.f)
  356. assert_array_equal(self.nm | self.t, self.t)
  357. assert_array_equal(self.im | self.f, self.im)
  358. assert_array_equal(self.nm | True, self.t)
  359. assert_array_equal(self.im | False, self.im)
  360. assert_array_equal(self.nm ^ self.t, self.im)
  361. assert_array_equal(self.im ^ self.f, self.im)
  362. assert_array_equal(self.nm ^ True, self.im)
  363. assert_array_equal(self.im ^ False, self.im)
  364. class TestBoolCmp:
  365. def setup_method(self):
  366. self.f = np.ones(256, dtype=np.float32)
  367. self.ef = np.ones(self.f.size, dtype=bool)
  368. self.d = np.ones(128, dtype=np.float64)
  369. self.ed = np.ones(self.d.size, dtype=bool)
  370. # generate values for all permutation of 256bit simd vectors
  371. s = 0
  372. for i in range(32):
  373. self.f[s:s+8] = [i & 2**x for x in range(8)]
  374. self.ef[s:s+8] = [(i & 2**x) != 0 for x in range(8)]
  375. s += 8
  376. s = 0
  377. for i in range(16):
  378. self.d[s:s+4] = [i & 2**x for x in range(4)]
  379. self.ed[s:s+4] = [(i & 2**x) != 0 for x in range(4)]
  380. s += 4
  381. self.nf = self.f.copy()
  382. self.nd = self.d.copy()
  383. self.nf[self.ef] = np.nan
  384. self.nd[self.ed] = np.nan
  385. self.inff = self.f.copy()
  386. self.infd = self.d.copy()
  387. self.inff[::3][self.ef[::3]] = np.inf
  388. self.infd[::3][self.ed[::3]] = np.inf
  389. self.inff[1::3][self.ef[1::3]] = -np.inf
  390. self.infd[1::3][self.ed[1::3]] = -np.inf
  391. self.inff[2::3][self.ef[2::3]] = np.nan
  392. self.infd[2::3][self.ed[2::3]] = np.nan
  393. self.efnonan = self.ef.copy()
  394. self.efnonan[2::3] = False
  395. self.ednonan = self.ed.copy()
  396. self.ednonan[2::3] = False
  397. self.signf = self.f.copy()
  398. self.signd = self.d.copy()
  399. self.signf[self.ef] *= -1.
  400. self.signd[self.ed] *= -1.
  401. self.signf[1::6][self.ef[1::6]] = -np.inf
  402. self.signd[1::6][self.ed[1::6]] = -np.inf
  403. self.signf[3::6][self.ef[3::6]] = -np.nan
  404. self.signd[3::6][self.ed[3::6]] = -np.nan
  405. self.signf[4::6][self.ef[4::6]] = -0.
  406. self.signd[4::6][self.ed[4::6]] = -0.
  407. def test_float(self):
  408. # offset for alignment test
  409. for i in range(4):
  410. assert_array_equal(self.f[i:] > 0, self.ef[i:])
  411. assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:])
  412. assert_array_equal(self.f[i:] == 0, ~self.ef[i:])
  413. assert_array_equal(-self.f[i:] < 0, self.ef[i:])
  414. assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:])
  415. r = self.f[i:] != 0
  416. assert_array_equal(r, self.ef[i:])
  417. r2 = self.f[i:] != np.zeros_like(self.f[i:])
  418. r3 = 0 != self.f[i:]
  419. assert_array_equal(r, r2)
  420. assert_array_equal(r, r3)
  421. # check bool == 0x1
  422. assert_array_equal(r.view(np.int8), r.astype(np.int8))
  423. assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
  424. assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
  425. # isnan on amd64 takes the same code path
  426. assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:])
  427. assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:])
  428. assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:])
  429. assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:])
  430. assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:])
  431. def test_double(self):
  432. # offset for alignment test
  433. for i in range(2):
  434. assert_array_equal(self.d[i:] > 0, self.ed[i:])
  435. assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:])
  436. assert_array_equal(self.d[i:] == 0, ~self.ed[i:])
  437. assert_array_equal(-self.d[i:] < 0, self.ed[i:])
  438. assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:])
  439. r = self.d[i:] != 0
  440. assert_array_equal(r, self.ed[i:])
  441. r2 = self.d[i:] != np.zeros_like(self.d[i:])
  442. r3 = 0 != self.d[i:]
  443. assert_array_equal(r, r2)
  444. assert_array_equal(r, r3)
  445. # check bool == 0x1
  446. assert_array_equal(r.view(np.int8), r.astype(np.int8))
  447. assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
  448. assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
  449. # isnan on amd64 takes the same code path
  450. assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:])
  451. assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:])
  452. assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:])
  453. assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:])
  454. assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:])
  455. class TestSeterr:
  456. def test_default(self):
  457. err = np.geterr()
  458. assert_equal(err,
  459. dict(divide='warn',
  460. invalid='warn',
  461. over='warn',
  462. under='ignore')
  463. )
  464. def test_set(self):
  465. with np.errstate():
  466. err = np.seterr()
  467. old = np.seterr(divide='print')
  468. assert_(err == old)
  469. new = np.seterr()
  470. assert_(new['divide'] == 'print')
  471. np.seterr(over='raise')
  472. assert_(np.geterr()['over'] == 'raise')
  473. assert_(new['divide'] == 'print')
  474. np.seterr(**old)
  475. assert_(np.geterr() == old)
  476. @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
  477. @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
  478. def test_divide_err(self):
  479. with np.errstate(divide='raise'):
  480. with assert_raises(FloatingPointError):
  481. np.array([1.]) / np.array([0.])
  482. np.seterr(divide='ignore')
  483. np.array([1.]) / np.array([0.])
  484. @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
  485. def test_errobj(self):
  486. olderrobj = np.geterrobj()
  487. self.called = 0
  488. try:
  489. with warnings.catch_warnings(record=True) as w:
  490. warnings.simplefilter("always")
  491. with np.errstate(divide='warn'):
  492. np.seterrobj([20000, 1, None])
  493. np.array([1.]) / np.array([0.])
  494. assert_equal(len(w), 1)
  495. def log_err(*args):
  496. self.called += 1
  497. extobj_err = args
  498. assert_(len(extobj_err) == 2)
  499. assert_("divide" in extobj_err[0])
  500. with np.errstate(divide='ignore'):
  501. np.seterrobj([20000, 3, log_err])
  502. np.array([1.]) / np.array([0.])
  503. assert_equal(self.called, 1)
  504. np.seterrobj(olderrobj)
  505. with np.errstate(divide='ignore'):
  506. np.divide(1., 0., extobj=[20000, 3, log_err])
  507. assert_equal(self.called, 2)
  508. finally:
  509. np.seterrobj(olderrobj)
  510. del self.called
  511. def test_errobj_noerrmask(self):
  512. # errmask = 0 has a special code path for the default
  513. olderrobj = np.geterrobj()
  514. try:
  515. # set errobj to something non default
  516. np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT,
  517. umath.ERR_DEFAULT + 1, None])
  518. # call a ufunc
  519. np.isnan(np.array([6]))
  520. # same with the default, lots of times to get rid of possible
  521. # pre-existing stack in the code
  522. for i in range(10000):
  523. np.seterrobj([umath.UFUNC_BUFSIZE_DEFAULT, umath.ERR_DEFAULT,
  524. None])
  525. np.isnan(np.array([6]))
  526. finally:
  527. np.seterrobj(olderrobj)
  528. class TestFloatExceptions:
  529. def assert_raises_fpe(self, fpeerr, flop, x, y):
  530. ftype = type(x)
  531. try:
  532. flop(x, y)
  533. assert_(False,
  534. "Type %s did not raise fpe error '%s'." % (ftype, fpeerr))
  535. except FloatingPointError as exc:
  536. assert_(str(exc).find(fpeerr) >= 0,
  537. "Type %s raised wrong fpe error '%s'." % (ftype, exc))
  538. def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):
  539. # Check that fpe exception is raised.
  540. #
  541. # Given a floating operation `flop` and two scalar values, check that
  542. # the operation raises the floating point exception specified by
  543. # `fpeerr`. Tests all variants with 0-d array scalars as well.
  544. self.assert_raises_fpe(fpeerr, flop, sc1, sc2)
  545. self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2)
  546. self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()])
  547. self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()])
  548. # Test for all real and complex float types
  549. @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
  550. @pytest.mark.parametrize("typecode", np.typecodes["AllFloat"])
  551. def test_floating_exceptions(self, typecode):
  552. # Test basic arithmetic function errors
  553. with np.errstate(all='raise'):
  554. ftype = np.obj2sctype(typecode)
  555. if np.dtype(ftype).kind == 'f':
  556. # Get some extreme values for the type
  557. fi = np.finfo(ftype)
  558. ft_tiny = fi._machar.tiny
  559. ft_max = fi.max
  560. ft_eps = fi.eps
  561. underflow = 'underflow'
  562. divbyzero = 'divide by zero'
  563. else:
  564. # 'c', complex, corresponding real dtype
  565. rtype = type(ftype(0).real)
  566. fi = np.finfo(rtype)
  567. ft_tiny = ftype(fi._machar.tiny)
  568. ft_max = ftype(fi.max)
  569. ft_eps = ftype(fi.eps)
  570. # The complex types raise different exceptions
  571. underflow = ''
  572. divbyzero = ''
  573. overflow = 'overflow'
  574. invalid = 'invalid'
  575. # The value of tiny for double double is NaN, so we need to
  576. # pass the assert
  577. if not np.isnan(ft_tiny):
  578. self.assert_raises_fpe(underflow,
  579. lambda a, b: a/b, ft_tiny, ft_max)
  580. self.assert_raises_fpe(underflow,
  581. lambda a, b: a*b, ft_tiny, ft_tiny)
  582. self.assert_raises_fpe(overflow,
  583. lambda a, b: a*b, ft_max, ftype(2))
  584. self.assert_raises_fpe(overflow,
  585. lambda a, b: a/b, ft_max, ftype(0.5))
  586. self.assert_raises_fpe(overflow,
  587. lambda a, b: a+b, ft_max, ft_max*ft_eps)
  588. self.assert_raises_fpe(overflow,
  589. lambda a, b: a-b, -ft_max, ft_max*ft_eps)
  590. self.assert_raises_fpe(overflow,
  591. np.power, ftype(2), ftype(2**fi.nexp))
  592. self.assert_raises_fpe(divbyzero,
  593. lambda a, b: a/b, ftype(1), ftype(0))
  594. self.assert_raises_fpe(
  595. invalid, lambda a, b: a/b, ftype(np.inf), ftype(np.inf)
  596. )
  597. self.assert_raises_fpe(invalid,
  598. lambda a, b: a/b, ftype(0), ftype(0))
  599. self.assert_raises_fpe(
  600. invalid, lambda a, b: a-b, ftype(np.inf), ftype(np.inf)
  601. )
  602. self.assert_raises_fpe(
  603. invalid, lambda a, b: a+b, ftype(np.inf), ftype(-np.inf)
  604. )
  605. self.assert_raises_fpe(invalid,
  606. lambda a, b: a*b, ftype(0), ftype(np.inf))
  607. @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
  608. def test_warnings(self):
  609. # test warning code path
  610. with warnings.catch_warnings(record=True) as w:
  611. warnings.simplefilter("always")
  612. with np.errstate(all="warn"):
  613. np.divide(1, 0.)
  614. assert_equal(len(w), 1)
  615. assert_("divide by zero" in str(w[0].message))
  616. np.array(1e300) * np.array(1e300)
  617. assert_equal(len(w), 2)
  618. assert_("overflow" in str(w[-1].message))
  619. np.array(np.inf) - np.array(np.inf)
  620. assert_equal(len(w), 3)
  621. assert_("invalid value" in str(w[-1].message))
  622. np.array(1e-300) * np.array(1e-300)
  623. assert_equal(len(w), 4)
  624. assert_("underflow" in str(w[-1].message))
  625. class TestTypes:
  626. def check_promotion_cases(self, promote_func):
  627. # tests that the scalars get coerced correctly.
  628. b = np.bool_(0)
  629. i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
  630. u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0)
  631. f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0)
  632. c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0)
  633. # coercion within the same kind
  634. assert_equal(promote_func(i8, i16), np.dtype(np.int16))
  635. assert_equal(promote_func(i32, i8), np.dtype(np.int32))
  636. assert_equal(promote_func(i16, i64), np.dtype(np.int64))
  637. assert_equal(promote_func(u8, u32), np.dtype(np.uint32))
  638. assert_equal(promote_func(f32, f64), np.dtype(np.float64))
  639. assert_equal(promote_func(fld, f32), np.dtype(np.longdouble))
  640. assert_equal(promote_func(f64, fld), np.dtype(np.longdouble))
  641. assert_equal(promote_func(c128, c64), np.dtype(np.complex128))
  642. assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble))
  643. assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble))
  644. # coercion between kinds
  645. assert_equal(promote_func(b, i32), np.dtype(np.int32))
  646. assert_equal(promote_func(b, u8), np.dtype(np.uint8))
  647. assert_equal(promote_func(i8, u8), np.dtype(np.int16))
  648. assert_equal(promote_func(u8, i32), np.dtype(np.int32))
  649. assert_equal(promote_func(i64, u32), np.dtype(np.int64))
  650. assert_equal(promote_func(u64, i32), np.dtype(np.float64))
  651. assert_equal(promote_func(i32, f32), np.dtype(np.float64))
  652. assert_equal(promote_func(i64, f32), np.dtype(np.float64))
  653. assert_equal(promote_func(f32, i16), np.dtype(np.float32))
  654. assert_equal(promote_func(f32, u32), np.dtype(np.float64))
  655. assert_equal(promote_func(f32, c64), np.dtype(np.complex64))
  656. assert_equal(promote_func(c128, f32), np.dtype(np.complex128))
  657. assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble))
  658. # coercion between scalars and 1-D arrays
  659. assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8))
  660. assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8))
  661. assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32))
  662. assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32))
  663. assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int8))
  664. assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.int32))
  665. assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.uint32))
  666. assert_equal(promote_func(np.int32(-1), np.array([u64])),
  667. np.dtype(np.float64))
  668. assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float32))
  669. assert_equal(promote_func(fld, np.array([f32])), np.dtype(np.float32))
  670. assert_equal(promote_func(np.array([f64]), fld), np.dtype(np.float64))
  671. assert_equal(promote_func(fld, np.array([c64])),
  672. np.dtype(np.complex64))
  673. assert_equal(promote_func(c64, np.array([f64])),
  674. np.dtype(np.complex128))
  675. assert_equal(promote_func(np.complex64(3j), np.array([f64])),
  676. np.dtype(np.complex128))
  677. # coercion between scalars and 1-D arrays, where
  678. # the scalar has greater kind than the array
  679. assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64))
  680. assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64))
  681. assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64))
  682. assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64))
  683. assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64))
  684. # uint and int are treated as the same "kind" for
  685. # the purposes of array-scalar promotion.
  686. assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.uint16))
  687. # float and complex are treated as the same "kind" for
  688. # the purposes of array-scalar promotion, so that you can do
  689. # (0j + float32array) to get a complex64 array instead of
  690. # a complex128 array.
  691. assert_equal(promote_func(np.array([f32]), c128),
  692. np.dtype(np.complex64))
  693. def test_coercion(self):
  694. def res_type(a, b):
  695. return np.add(a, b).dtype
  696. self.check_promotion_cases(res_type)
  697. # Use-case: float/complex scalar * bool/int8 array
  698. # shouldn't narrow the float/complex type
  699. for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:
  700. b = 1.234 * a
  701. assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype)
  702. b = np.longdouble(1.234) * a
  703. assert_equal(b.dtype, np.dtype(np.longdouble),
  704. "array type %s" % a.dtype)
  705. b = np.float64(1.234) * a
  706. assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype)
  707. b = np.float32(1.234) * a
  708. assert_equal(b.dtype, np.dtype('f4'), "array type %s" % a.dtype)
  709. b = np.float16(1.234) * a
  710. assert_equal(b.dtype, np.dtype('f2'), "array type %s" % a.dtype)
  711. b = 1.234j * a
  712. assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype)
  713. b = np.clongdouble(1.234j) * a
  714. assert_equal(b.dtype, np.dtype(np.clongdouble),
  715. "array type %s" % a.dtype)
  716. b = np.complex128(1.234j) * a
  717. assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype)
  718. b = np.complex64(1.234j) * a
  719. assert_equal(b.dtype, np.dtype('c8'), "array type %s" % a.dtype)
  720. # The following use-case is problematic, and to resolve its
  721. # tricky side-effects requires more changes.
  722. #
  723. # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is
  724. # a float32, shouldn't promote to float64
  725. #
  726. # a = np.array([1.0, 1.5], dtype=np.float32)
  727. # t = np.array([True, False])
  728. # b = t*a
  729. # assert_equal(b, [1.0, 0.0])
  730. # assert_equal(b.dtype, np.dtype('f4'))
  731. # b = (1-t)*a
  732. # assert_equal(b, [0.0, 1.5])
  733. # assert_equal(b.dtype, np.dtype('f4'))
  734. #
  735. # Probably ~t (bitwise negation) is more proper to use here,
  736. # but this is arguably less intuitive to understand at a glance, and
  737. # would fail if 't' is actually an integer array instead of boolean:
  738. #
  739. # b = (~t)*a
  740. # assert_equal(b, [0.0, 1.5])
  741. # assert_equal(b.dtype, np.dtype('f4'))
  742. def test_result_type(self):
  743. self.check_promotion_cases(np.result_type)
  744. assert_(np.result_type(None) == np.dtype(None))
  745. def test_promote_types_endian(self):
  746. # promote_types should always return native-endian types
  747. assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))
  748. assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8'))
  749. assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21'))
  750. assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21'))
  751. assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21'))
  752. assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21'))
  753. assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8'))
  754. assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8'))
  755. assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8'))
  756. assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8'))
  757. assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8'))
  758. assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8'))
  759. assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8'))
  760. assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8'))
  761. assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8'))
  762. assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8'))
  763. def test_can_cast_and_promote_usertypes(self):
  764. # The rational type defines safe casting for signed integers,
  765. # boolean. Rational itself *does* cast safely to double.
  766. # (rational does not actually cast to all signed integers, e.g.
  767. # int64 can be both long and longlong and it registers only the first)
  768. valid_types = ["int8", "int16", "int32", "int64", "bool"]
  769. invalid_types = "BHILQP" + "FDG" + "mM" + "f" + "V"
  770. rational_dt = np.dtype(rational)
  771. for numpy_dtype in valid_types:
  772. numpy_dtype = np.dtype(numpy_dtype)
  773. assert np.can_cast(numpy_dtype, rational_dt)
  774. assert np.promote_types(numpy_dtype, rational_dt) is rational_dt
  775. for numpy_dtype in invalid_types:
  776. numpy_dtype = np.dtype(numpy_dtype)
  777. assert not np.can_cast(numpy_dtype, rational_dt)
  778. with pytest.raises(TypeError):
  779. np.promote_types(numpy_dtype, rational_dt)
  780. double_dt = np.dtype("double")
  781. assert np.can_cast(rational_dt, double_dt)
  782. assert np.promote_types(double_dt, rational_dt) is double_dt
  783. @pytest.mark.parametrize("swap", ["", "swap"])
  784. @pytest.mark.parametrize("string_dtype", ["U", "S"])
  785. def test_promote_types_strings(self, swap, string_dtype):
  786. if swap == "swap":
  787. promote_types = lambda a, b: np.promote_types(b, a)
  788. else:
  789. promote_types = np.promote_types
  790. S = string_dtype
  791. # Promote numeric with unsized string:
  792. assert_equal(promote_types('bool', S), np.dtype(S+'5'))
  793. assert_equal(promote_types('b', S), np.dtype(S+'4'))
  794. assert_equal(promote_types('u1', S), np.dtype(S+'3'))
  795. assert_equal(promote_types('u2', S), np.dtype(S+'5'))
  796. assert_equal(promote_types('u4', S), np.dtype(S+'10'))
  797. assert_equal(promote_types('u8', S), np.dtype(S+'20'))
  798. assert_equal(promote_types('i1', S), np.dtype(S+'4'))
  799. assert_equal(promote_types('i2', S), np.dtype(S+'6'))
  800. assert_equal(promote_types('i4', S), np.dtype(S+'11'))
  801. assert_equal(promote_types('i8', S), np.dtype(S+'21'))
  802. # Promote numeric with sized string:
  803. assert_equal(promote_types('bool', S+'1'), np.dtype(S+'5'))
  804. assert_equal(promote_types('bool', S+'30'), np.dtype(S+'30'))
  805. assert_equal(promote_types('b', S+'1'), np.dtype(S+'4'))
  806. assert_equal(promote_types('b', S+'30'), np.dtype(S+'30'))
  807. assert_equal(promote_types('u1', S+'1'), np.dtype(S+'3'))
  808. assert_equal(promote_types('u1', S+'30'), np.dtype(S+'30'))
  809. assert_equal(promote_types('u2', S+'1'), np.dtype(S+'5'))
  810. assert_equal(promote_types('u2', S+'30'), np.dtype(S+'30'))
  811. assert_equal(promote_types('u4', S+'1'), np.dtype(S+'10'))
  812. assert_equal(promote_types('u4', S+'30'), np.dtype(S+'30'))
  813. assert_equal(promote_types('u8', S+'1'), np.dtype(S+'20'))
  814. assert_equal(promote_types('u8', S+'30'), np.dtype(S+'30'))
  815. # Promote with object:
  816. assert_equal(promote_types('O', S+'30'), np.dtype('O'))
  817. @pytest.mark.parametrize(["dtype1", "dtype2"],
  818. [[np.dtype("V6"), np.dtype("V10")], # mismatch shape
  819. # Mismatching names:
  820. [np.dtype([("name1", "i8")]), np.dtype([("name2", "i8")])],
  821. ])
  822. def test_invalid_void_promotion(self, dtype1, dtype2):
  823. with pytest.raises(TypeError):
  824. np.promote_types(dtype1, dtype2)
  825. @pytest.mark.parametrize(["dtype1", "dtype2"],
  826. [[np.dtype("V10"), np.dtype("V10")],
  827. [np.dtype([("name1", "i8")]),
  828. np.dtype([("name1", np.dtype("i8").newbyteorder())])],
  829. [np.dtype("i8,i8"), np.dtype("i8,>i8")],
  830. [np.dtype("i8,i8"), np.dtype("i4,i4")],
  831. ])
  832. def test_valid_void_promotion(self, dtype1, dtype2):
  833. assert np.promote_types(dtype1, dtype2) == dtype1
  834. @pytest.mark.parametrize("dtype",
  835. list(np.typecodes["All"]) +
  836. ["i,i", "10i", "S3", "S100", "U3", "U100", rational])
  837. def test_promote_identical_types_metadata(self, dtype):
  838. # The same type passed in twice to promote types always
  839. # preserves metadata
  840. metadata = {1: 1}
  841. dtype = np.dtype(dtype, metadata=metadata)
  842. res = np.promote_types(dtype, dtype)
  843. assert res.metadata == dtype.metadata
  844. # byte-swapping preserves and makes the dtype native:
  845. dtype = dtype.newbyteorder()
  846. if dtype.isnative:
  847. # The type does not have byte swapping
  848. return
  849. res = np.promote_types(dtype, dtype)
  850. # Metadata is (currently) generally lost on byte-swapping (except for
  851. # unicode.
  852. if dtype.char != "U":
  853. assert res.metadata is None
  854. else:
  855. assert res.metadata == metadata
  856. assert res.isnative
  857. @pytest.mark.slow
  858. @pytest.mark.filterwarnings('ignore:Promotion of numbers:FutureWarning')
  859. @pytest.mark.parametrize(["dtype1", "dtype2"],
  860. itertools.product(
  861. list(np.typecodes["All"]) +
  862. ["i,i", "S3", "S100", "U3", "U100", rational],
  863. repeat=2))
  864. def test_promote_types_metadata(self, dtype1, dtype2):
  865. """Metadata handling in promotion does not appear formalized
  866. right now in NumPy. This test should thus be considered to
  867. document behaviour, rather than test the correct definition of it.
  868. This test is very ugly, it was useful for rewriting part of the
  869. promotion, but probably should eventually be replaced/deleted
  870. (i.e. when metadata handling in promotion is better defined).
  871. """
  872. metadata1 = {1: 1}
  873. metadata2 = {2: 2}
  874. dtype1 = np.dtype(dtype1, metadata=metadata1)
  875. dtype2 = np.dtype(dtype2, metadata=metadata2)
  876. try:
  877. res = np.promote_types(dtype1, dtype2)
  878. except TypeError:
  879. # Promotion failed, this test only checks metadata
  880. return
  881. if res.char not in "USV" or res.names is not None or res.shape != ():
  882. # All except string dtypes (and unstructured void) lose metadata
  883. # on promotion (unless both dtypes are identical).
  884. # At some point structured ones did not, but were restrictive.
  885. assert res.metadata is None
  886. elif res == dtype1:
  887. # If one result is the result, it is usually returned unchanged:
  888. assert res is dtype1
  889. elif res == dtype2:
  890. # dtype1 may have been cast to the same type/kind as dtype2.
  891. # If the resulting dtype is identical we currently pick the cast
  892. # version of dtype1, which lost the metadata:
  893. if np.promote_types(dtype1, dtype2.kind) == dtype2:
  894. res.metadata is None
  895. else:
  896. res.metadata == metadata2
  897. else:
  898. assert res.metadata is None
  899. # Try again for byteswapped version
  900. dtype1 = dtype1.newbyteorder()
  901. assert dtype1.metadata == metadata1
  902. res_bs = np.promote_types(dtype1, dtype2)
  903. assert res_bs == res
  904. assert res_bs.metadata == res.metadata
  905. def test_can_cast(self):
  906. assert_(np.can_cast(np.int32, np.int64))
  907. assert_(np.can_cast(np.float64, complex))
  908. assert_(not np.can_cast(complex, float))
  909. assert_(np.can_cast('i8', 'f8'))
  910. assert_(not np.can_cast('i8', 'f4'))
  911. assert_(np.can_cast('i4', 'S11'))
  912. assert_(np.can_cast('i8', 'i8', 'no'))
  913. assert_(not np.can_cast('<i8', '>i8', 'no'))
  914. assert_(np.can_cast('<i8', '>i8', 'equiv'))
  915. assert_(not np.can_cast('<i4', '>i8', 'equiv'))
  916. assert_(np.can_cast('<i4', '>i8', 'safe'))
  917. assert_(not np.can_cast('<i8', '>i4', 'safe'))
  918. assert_(np.can_cast('<i8', '>i4', 'same_kind'))
  919. assert_(not np.can_cast('<i8', '>u4', 'same_kind'))
  920. assert_(np.can_cast('<i8', '>u4', 'unsafe'))
  921. assert_(np.can_cast('bool', 'S5'))
  922. assert_(not np.can_cast('bool', 'S4'))
  923. assert_(np.can_cast('b', 'S4'))
  924. assert_(not np.can_cast('b', 'S3'))
  925. assert_(np.can_cast('u1', 'S3'))
  926. assert_(not np.can_cast('u1', 'S2'))
  927. assert_(np.can_cast('u2', 'S5'))
  928. assert_(not np.can_cast('u2', 'S4'))
  929. assert_(np.can_cast('u4', 'S10'))
  930. assert_(not np.can_cast('u4', 'S9'))
  931. assert_(np.can_cast('u8', 'S20'))
  932. assert_(not np.can_cast('u8', 'S19'))
  933. assert_(np.can_cast('i1', 'S4'))
  934. assert_(not np.can_cast('i1', 'S3'))
  935. assert_(np.can_cast('i2', 'S6'))
  936. assert_(not np.can_cast('i2', 'S5'))
  937. assert_(np.can_cast('i4', 'S11'))
  938. assert_(not np.can_cast('i4', 'S10'))
  939. assert_(np.can_cast('i8', 'S21'))
  940. assert_(not np.can_cast('i8', 'S20'))
  941. assert_(np.can_cast('bool', 'S5'))
  942. assert_(not np.can_cast('bool', 'S4'))
  943. assert_(np.can_cast('b', 'U4'))
  944. assert_(not np.can_cast('b', 'U3'))
  945. assert_(np.can_cast('u1', 'U3'))
  946. assert_(not np.can_cast('u1', 'U2'))
  947. assert_(np.can_cast('u2', 'U5'))
  948. assert_(not np.can_cast('u2', 'U4'))
  949. assert_(np.can_cast('u4', 'U10'))
  950. assert_(not np.can_cast('u4', 'U9'))
  951. assert_(np.can_cast('u8', 'U20'))
  952. assert_(not np.can_cast('u8', 'U19'))
  953. assert_(np.can_cast('i1', 'U4'))
  954. assert_(not np.can_cast('i1', 'U3'))
  955. assert_(np.can_cast('i2', 'U6'))
  956. assert_(not np.can_cast('i2', 'U5'))
  957. assert_(np.can_cast('i4', 'U11'))
  958. assert_(not np.can_cast('i4', 'U10'))
  959. assert_(np.can_cast('i8', 'U21'))
  960. assert_(not np.can_cast('i8', 'U20'))
  961. assert_raises(TypeError, np.can_cast, 'i4', None)
  962. assert_raises(TypeError, np.can_cast, None, 'i4')
  963. # Also test keyword arguments
  964. assert_(np.can_cast(from_=np.int32, to=np.int64))
  965. def test_can_cast_simple_to_structured(self):
  966. # Non-structured can only be cast to structured in 'unsafe' mode.
  967. assert_(not np.can_cast('i4', 'i4,i4'))
  968. assert_(not np.can_cast('i4', 'i4,i2'))
  969. assert_(np.can_cast('i4', 'i4,i4', casting='unsafe'))
  970. assert_(np.can_cast('i4', 'i4,i2', casting='unsafe'))
  971. # Even if there is just a single field which is OK.
  972. assert_(not np.can_cast('i2', [('f1', 'i4')]))
  973. assert_(not np.can_cast('i2', [('f1', 'i4')], casting='same_kind'))
  974. assert_(np.can_cast('i2', [('f1', 'i4')], casting='unsafe'))
  975. # It should be the same for recursive structured or subarrays.
  976. assert_(not np.can_cast('i2', [('f1', 'i4,i4')]))
  977. assert_(np.can_cast('i2', [('f1', 'i4,i4')], casting='unsafe'))
  978. assert_(not np.can_cast('i2', [('f1', '(2,3)i4')]))
  979. assert_(np.can_cast('i2', [('f1', '(2,3)i4')], casting='unsafe'))
  980. def test_can_cast_structured_to_simple(self):
  981. # Need unsafe casting for structured to simple.
  982. assert_(not np.can_cast([('f1', 'i4')], 'i4'))
  983. assert_(np.can_cast([('f1', 'i4')], 'i4', casting='unsafe'))
  984. assert_(np.can_cast([('f1', 'i4')], 'i2', casting='unsafe'))
  985. # Since it is unclear what is being cast, multiple fields to
  986. # single should not work even for unsafe casting.
  987. assert_(not np.can_cast('i4,i4', 'i4', casting='unsafe'))
  988. # But a single field inside a single field is OK.
  989. assert_(not np.can_cast([('f1', [('x', 'i4')])], 'i4'))
  990. assert_(np.can_cast([('f1', [('x', 'i4')])], 'i4', casting='unsafe'))
  991. # And a subarray is fine too - it will just take the first element
  992. # (arguably not very consistently; might also take the first field).
  993. assert_(not np.can_cast([('f0', '(3,)i4')], 'i4'))
  994. assert_(np.can_cast([('f0', '(3,)i4')], 'i4', casting='unsafe'))
  995. # But a structured subarray with multiple fields should fail.
  996. assert_(not np.can_cast([('f0', ('i4,i4'), (2,))], 'i4',
  997. casting='unsafe'))
  998. def test_can_cast_values(self):
  999. # gh-5917
  1000. for dt in np.sctypes['int'] + np.sctypes['uint']:
  1001. ii = np.iinfo(dt)
  1002. assert_(np.can_cast(ii.min, dt))
  1003. assert_(np.can_cast(ii.max, dt))
  1004. assert_(not np.can_cast(ii.min - 1, dt))
  1005. assert_(not np.can_cast(ii.max + 1, dt))
  1006. for dt in np.sctypes['float']:
  1007. fi = np.finfo(dt)
  1008. assert_(np.can_cast(fi.min, dt))
  1009. assert_(np.can_cast(fi.max, dt))
  1010. # Custom exception class to test exception propagation in fromiter
  1011. class NIterError(Exception):
  1012. pass
  1013. class TestFromiter:
  1014. def makegen(self):
  1015. return (x**2 for x in range(24))
  1016. def test_types(self):
  1017. ai32 = np.fromiter(self.makegen(), np.int32)
  1018. ai64 = np.fromiter(self.makegen(), np.int64)
  1019. af = np.fromiter(self.makegen(), float)
  1020. assert_(ai32.dtype == np.dtype(np.int32))
  1021. assert_(ai64.dtype == np.dtype(np.int64))
  1022. assert_(af.dtype == np.dtype(float))
  1023. def test_lengths(self):
  1024. expected = np.array(list(self.makegen()))
  1025. a = np.fromiter(self.makegen(), int)
  1026. a20 = np.fromiter(self.makegen(), int, 20)
  1027. assert_(len(a) == len(expected))
  1028. assert_(len(a20) == 20)
  1029. assert_raises(ValueError, np.fromiter,
  1030. self.makegen(), int, len(expected) + 10)
  1031. def test_values(self):
  1032. expected = np.array(list(self.makegen()))
  1033. a = np.fromiter(self.makegen(), int)
  1034. a20 = np.fromiter(self.makegen(), int, 20)
  1035. assert_(np.alltrue(a == expected, axis=0))
  1036. assert_(np.alltrue(a20 == expected[:20], axis=0))
  1037. def load_data(self, n, eindex):
  1038. # Utility method for the issue 2592 tests.
  1039. # Raise an exception at the desired index in the iterator.
  1040. for e in range(n):
  1041. if e == eindex:
  1042. raise NIterError('error at index %s' % eindex)
  1043. yield e
  1044. @pytest.mark.parametrize("dtype", [int, object])
  1045. @pytest.mark.parametrize(["count", "error_index"], [(10, 5), (10, 9)])
  1046. def test_2592(self, count, error_index, dtype):
  1047. # Test iteration exceptions are correctly raised. The data/generator
  1048. # has `count` elements but errors at `error_index`
  1049. iterable = self.load_data(count, error_index)
  1050. with pytest.raises(NIterError):
  1051. np.fromiter(iterable, dtype=dtype, count=count)
  1052. @pytest.mark.parametrize("dtype", ["S", "S0", "V0", "U0"])
  1053. def test_empty_not_structured(self, dtype):
  1054. # Note, "S0" could be allowed at some point, so long "S" (without
  1055. # any length) is rejected.
  1056. with pytest.raises(ValueError, match="Must specify length"):
  1057. np.fromiter([], dtype=dtype)
  1058. @pytest.mark.parametrize(["dtype", "data"],
  1059. [("d", [1, 2, 3, 4, 5, 6, 7, 8, 9]),
  1060. ("O", [1, 2, 3, 4, 5, 6, 7, 8, 9]),
  1061. ("i,O", [(1, 2), (5, 4), (2, 3), (9, 8), (6, 7)]),
  1062. # subarray dtypes (important because their dimensions end up
  1063. # in the result arrays dimension:
  1064. ("2i", [(1, 2), (5, 4), (2, 3), (9, 8), (6, 7)]),
  1065. (np.dtype(("O", (2, 3))),
  1066. [((1, 2, 3), (3, 4, 5)), ((3, 2, 1), (5, 4, 3))])])
  1067. @pytest.mark.parametrize("length_hint", [0, 1])
  1068. def test_growth_and_complicated_dtypes(self, dtype, data, length_hint):
  1069. dtype = np.dtype(dtype)
  1070. data = data * 100 # make sure we realloc a bit
  1071. class MyIter:
  1072. # Class/example from gh-15789
  1073. def __length_hint__(self):
  1074. # only required to be an estimate, this is legal
  1075. return length_hint # 0 or 1
  1076. def __iter__(self):
  1077. return iter(data)
  1078. res = np.fromiter(MyIter(), dtype=dtype)
  1079. expected = np.array(data, dtype=dtype)
  1080. assert_array_equal(res, expected)
  1081. def test_empty_result(self):
  1082. class MyIter:
  1083. def __length_hint__(self):
  1084. return 10
  1085. def __iter__(self):
  1086. return iter([]) # actual iterator is empty.
  1087. res = np.fromiter(MyIter(), dtype="d")
  1088. assert res.shape == (0,)
  1089. assert res.dtype == "d"
  1090. def test_too_few_items(self):
  1091. msg = "iterator too short: Expected 10 but iterator had only 3 items."
  1092. with pytest.raises(ValueError, match=msg):
  1093. np.fromiter([1, 2, 3], count=10, dtype=int)
  1094. def test_failed_itemsetting(self):
  1095. with pytest.raises(TypeError):
  1096. np.fromiter([1, None, 3], dtype=int)
  1097. # The following manages to hit somewhat trickier code paths:
  1098. iterable = ((2, 3, 4) for i in range(5))
  1099. with pytest.raises(ValueError):
  1100. np.fromiter(iterable, dtype=np.dtype((int, 2)))
  1101. class TestNonzero:
  1102. def test_nonzero_trivial(self):
  1103. assert_equal(np.count_nonzero(np.array([])), 0)
  1104. assert_equal(np.count_nonzero(np.array([], dtype='?')), 0)
  1105. assert_equal(np.nonzero(np.array([])), ([],))
  1106. assert_equal(np.count_nonzero(np.array([0])), 0)
  1107. assert_equal(np.count_nonzero(np.array([0], dtype='?')), 0)
  1108. assert_equal(np.nonzero(np.array([0])), ([],))
  1109. assert_equal(np.count_nonzero(np.array([1])), 1)
  1110. assert_equal(np.count_nonzero(np.array([1], dtype='?')), 1)
  1111. assert_equal(np.nonzero(np.array([1])), ([0],))
  1112. def test_nonzero_zerod(self):
  1113. assert_equal(np.count_nonzero(np.array(0)), 0)
  1114. assert_equal(np.count_nonzero(np.array(0, dtype='?')), 0)
  1115. with assert_warns(DeprecationWarning):
  1116. assert_equal(np.nonzero(np.array(0)), ([],))
  1117. assert_equal(np.count_nonzero(np.array(1)), 1)
  1118. assert_equal(np.count_nonzero(np.array(1, dtype='?')), 1)
  1119. with assert_warns(DeprecationWarning):
  1120. assert_equal(np.nonzero(np.array(1)), ([0],))
  1121. def test_nonzero_onedim(self):
  1122. x = np.array([1, 0, 2, -1, 0, 0, 8])
  1123. assert_equal(np.count_nonzero(x), 4)
  1124. assert_equal(np.count_nonzero(x), 4)
  1125. assert_equal(np.nonzero(x), ([0, 2, 3, 6],))
  1126. # x = np.array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)],
  1127. # dtype=[('a', 'i4'), ('b', 'i2')])
  1128. x = np.array([(1, 2, -5, -3), (0, 0, 2, 7), (1, 1, 0, 1), (-1, 3, 1, 0), (0, 7, 0, 4)],
  1129. dtype=[('a', 'i4'), ('b', 'i2'), ('c', 'i1'), ('d', 'i8')])
  1130. assert_equal(np.count_nonzero(x['a']), 3)
  1131. assert_equal(np.count_nonzero(x['b']), 4)
  1132. assert_equal(np.count_nonzero(x['c']), 3)
  1133. assert_equal(np.count_nonzero(x['d']), 4)
  1134. assert_equal(np.nonzero(x['a']), ([0, 2, 3],))
  1135. assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],))
  1136. def test_nonzero_twodim(self):
  1137. x = np.array([[0, 1, 0], [2, 0, 3]])
  1138. assert_equal(np.count_nonzero(x.astype('i1')), 3)
  1139. assert_equal(np.count_nonzero(x.astype('i2')), 3)
  1140. assert_equal(np.count_nonzero(x.astype('i4')), 3)
  1141. assert_equal(np.count_nonzero(x.astype('i8')), 3)
  1142. assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2]))
  1143. x = np.eye(3)
  1144. assert_equal(np.count_nonzero(x.astype('i1')), 3)
  1145. assert_equal(np.count_nonzero(x.astype('i2')), 3)
  1146. assert_equal(np.count_nonzero(x.astype('i4')), 3)
  1147. assert_equal(np.count_nonzero(x.astype('i8')), 3)
  1148. assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2]))
  1149. x = np.array([[(0, 1), (0, 0), (1, 11)],
  1150. [(1, 1), (1, 0), (0, 0)],
  1151. [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')])
  1152. assert_equal(np.count_nonzero(x['a']), 4)
  1153. assert_equal(np.count_nonzero(x['b']), 5)
  1154. assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1]))
  1155. assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2]))
  1156. assert_(not x['a'].T.flags.aligned)
  1157. assert_equal(np.count_nonzero(x['a'].T), 4)
  1158. assert_equal(np.count_nonzero(x['b'].T), 5)
  1159. assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0]))
  1160. assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2]))
  1161. def test_sparse(self):
  1162. # test special sparse condition boolean code path
  1163. for i in range(20):
  1164. c = np.zeros(200, dtype=bool)
  1165. c[i::20] = True
  1166. assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20))
  1167. c = np.zeros(400, dtype=bool)
  1168. c[10 + i:20 + i] = True
  1169. c[20 + i*2] = True
  1170. assert_equal(np.nonzero(c)[0],
  1171. np.concatenate((np.arange(10 + i, 20 + i), [20 + i*2])))
  1172. def test_return_type(self):
  1173. class C(np.ndarray):
  1174. pass
  1175. for view in (C, np.ndarray):
  1176. for nd in range(1, 4):
  1177. shape = tuple(range(2, 2+nd))
  1178. x = np.arange(np.prod(shape)).reshape(shape).view(view)
  1179. for nzx in (np.nonzero(x), x.nonzero()):
  1180. for nzx_i in nzx:
  1181. assert_(type(nzx_i) is np.ndarray)
  1182. assert_(nzx_i.flags.writeable)
  1183. def test_count_nonzero_axis(self):
  1184. # Basic check of functionality
  1185. m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
  1186. expected = np.array([1, 1, 1, 1, 1])
  1187. assert_equal(np.count_nonzero(m, axis=0), expected)
  1188. expected = np.array([2, 3])
  1189. assert_equal(np.count_nonzero(m, axis=1), expected)
  1190. assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1))
  1191. assert_raises(TypeError, np.count_nonzero, m, axis='foo')
  1192. assert_raises(np.AxisError, np.count_nonzero, m, axis=3)
  1193. assert_raises(TypeError, np.count_nonzero,
  1194. m, axis=np.array([[1], [2]]))
  1195. def test_count_nonzero_axis_all_dtypes(self):
  1196. # More thorough test that the axis argument is respected
  1197. # for all dtypes and responds correctly when presented with
  1198. # either integer or tuple arguments for axis
  1199. msg = "Mismatch for dtype: %s"
  1200. def assert_equal_w_dt(a, b, err_msg):
  1201. assert_equal(a.dtype, b.dtype, err_msg=err_msg)
  1202. assert_equal(a, b, err_msg=err_msg)
  1203. for dt in np.typecodes['All']:
  1204. err_msg = msg % (np.dtype(dt).name,)
  1205. if dt != 'V':
  1206. if dt != 'M':
  1207. m = np.zeros((3, 3), dtype=dt)
  1208. n = np.ones(1, dtype=dt)
  1209. m[0, 0] = n[0]
  1210. m[1, 0] = n[0]
  1211. else: # np.zeros doesn't work for np.datetime64
  1212. m = np.array(['1970-01-01'] * 9)
  1213. m = m.reshape((3, 3))
  1214. m[0, 0] = '1970-01-12'
  1215. m[1, 0] = '1970-01-12'
  1216. m = m.astype(dt)
  1217. expected = np.array([2, 0, 0], dtype=np.intp)
  1218. assert_equal_w_dt(np.count_nonzero(m, axis=0),
  1219. expected, err_msg=err_msg)
  1220. expected = np.array([1, 1, 0], dtype=np.intp)
  1221. assert_equal_w_dt(np.count_nonzero(m, axis=1),
  1222. expected, err_msg=err_msg)
  1223. expected = np.array(2)
  1224. assert_equal(np.count_nonzero(m, axis=(0, 1)),
  1225. expected, err_msg=err_msg)
  1226. assert_equal(np.count_nonzero(m, axis=None),
  1227. expected, err_msg=err_msg)
  1228. assert_equal(np.count_nonzero(m),
  1229. expected, err_msg=err_msg)
  1230. if dt == 'V':
  1231. # There are no 'nonzero' objects for np.void, so the testing
  1232. # setup is slightly different for this dtype
  1233. m = np.array([np.void(1)] * 6).reshape((2, 3))
  1234. expected = np.array([0, 0, 0], dtype=np.intp)
  1235. assert_equal_w_dt(np.count_nonzero(m, axis=0),
  1236. expected, err_msg=err_msg)
  1237. expected = np.array([0, 0], dtype=np.intp)
  1238. assert_equal_w_dt(np.count_nonzero(m, axis=1),
  1239. expected, err_msg=err_msg)
  1240. expected = np.array(0)
  1241. assert_equal(np.count_nonzero(m, axis=(0, 1)),
  1242. expected, err_msg=err_msg)
  1243. assert_equal(np.count_nonzero(m, axis=None),
  1244. expected, err_msg=err_msg)
  1245. assert_equal(np.count_nonzero(m),
  1246. expected, err_msg=err_msg)
  1247. def test_count_nonzero_axis_consistent(self):
  1248. # Check that the axis behaviour for valid axes in
  1249. # non-special cases is consistent (and therefore
  1250. # correct) by checking it against an integer array
  1251. # that is then casted to the generic object dtype
  1252. from itertools import combinations, permutations
  1253. axis = (0, 1, 2, 3)
  1254. size = (5, 5, 5, 5)
  1255. msg = "Mismatch for axis: %s"
  1256. rng = np.random.RandomState(1234)
  1257. m = rng.randint(-100, 100, size=size)
  1258. n = m.astype(object)
  1259. for length in range(len(axis)):
  1260. for combo in combinations(axis, length):
  1261. for perm in permutations(combo):
  1262. assert_equal(
  1263. np.count_nonzero(m, axis=perm),
  1264. np.count_nonzero(n, axis=perm),
  1265. err_msg=msg % (perm,))
  1266. def test_countnonzero_axis_empty(self):
  1267. a = np.array([[0, 0, 1], [1, 0, 1]])
  1268. assert_equal(np.count_nonzero(a, axis=()), a.astype(bool))
  1269. def test_countnonzero_keepdims(self):
  1270. a = np.array([[0, 0, 1, 0],
  1271. [0, 3, 5, 0],
  1272. [7, 9, 2, 0]])
  1273. assert_equal(np.count_nonzero(a, axis=0, keepdims=True),
  1274. [[1, 2, 3, 0]])
  1275. assert_equal(np.count_nonzero(a, axis=1, keepdims=True),
  1276. [[1], [2], [3]])
  1277. assert_equal(np.count_nonzero(a, keepdims=True),
  1278. [[6]])
  1279. def test_array_method(self):
  1280. # Tests that the array method
  1281. # call to nonzero works
  1282. m = np.array([[1, 0, 0], [4, 0, 6]])
  1283. tgt = [[0, 1, 1], [0, 0, 2]]
  1284. assert_equal(m.nonzero(), tgt)
  1285. def test_nonzero_invalid_object(self):
  1286. # gh-9295
  1287. a = np.array([np.array([1, 2]), 3], dtype=object)
  1288. assert_raises(ValueError, np.nonzero, a)
  1289. class BoolErrors:
  1290. def __bool__(self):
  1291. raise ValueError("Not allowed")
  1292. assert_raises(ValueError, np.nonzero, np.array([BoolErrors()]))
  1293. def test_nonzero_sideeffect_safety(self):
  1294. # gh-13631
  1295. class FalseThenTrue:
  1296. _val = False
  1297. def __bool__(self):
  1298. try:
  1299. return self._val
  1300. finally:
  1301. self._val = True
  1302. class TrueThenFalse:
  1303. _val = True
  1304. def __bool__(self):
  1305. try:
  1306. return self._val
  1307. finally:
  1308. self._val = False
  1309. # result grows on the second pass
  1310. a = np.array([True, FalseThenTrue()])
  1311. assert_raises(RuntimeError, np.nonzero, a)
  1312. a = np.array([[True], [FalseThenTrue()]])
  1313. assert_raises(RuntimeError, np.nonzero, a)
  1314. # result shrinks on the second pass
  1315. a = np.array([False, TrueThenFalse()])
  1316. assert_raises(RuntimeError, np.nonzero, a)
  1317. a = np.array([[False], [TrueThenFalse()]])
  1318. assert_raises(RuntimeError, np.nonzero, a)
  1319. def test_nonzero_sideffects_structured_void(self):
  1320. # Checks that structured void does not mutate alignment flag of
  1321. # original array.
  1322. arr = np.zeros(5, dtype="i1,i8,i8") # `ones` may short-circuit
  1323. assert arr.flags.aligned # structs are considered "aligned"
  1324. assert not arr["f2"].flags.aligned
  1325. # make sure that nonzero/count_nonzero do not flip the flag:
  1326. np.nonzero(arr)
  1327. assert arr.flags.aligned
  1328. np.count_nonzero(arr)
  1329. assert arr.flags.aligned
  1330. def test_nonzero_exception_safe(self):
  1331. # gh-13930
  1332. class ThrowsAfter:
  1333. def __init__(self, iters):
  1334. self.iters_left = iters
  1335. def __bool__(self):
  1336. if self.iters_left == 0:
  1337. raise ValueError("called `iters` times")
  1338. self.iters_left -= 1
  1339. return True
  1340. """
  1341. Test that a ValueError is raised instead of a SystemError
  1342. If the __bool__ function is called after the error state is set,
  1343. Python (cpython) will raise a SystemError.
  1344. """
  1345. # assert that an exception in first pass is handled correctly
  1346. a = np.array([ThrowsAfter(5)]*10)
  1347. assert_raises(ValueError, np.nonzero, a)
  1348. # raise exception in second pass for 1-dimensional loop
  1349. a = np.array([ThrowsAfter(15)]*10)
  1350. assert_raises(ValueError, np.nonzero, a)
  1351. # raise exception in second pass for n-dimensional loop
  1352. a = np.array([[ThrowsAfter(15)]]*10)
  1353. assert_raises(ValueError, np.nonzero, a)
  1354. @pytest.mark.skipif(IS_WASM, reason="wasm doesn't have threads")
  1355. def test_structured_threadsafety(self):
  1356. # Nonzero (and some other functions) should be threadsafe for
  1357. # structured datatypes, see gh-15387. This test can behave randomly.
  1358. from concurrent.futures import ThreadPoolExecutor
  1359. # Create a deeply nested dtype to make a failure more likely:
  1360. dt = np.dtype([("", "f8")])
  1361. dt = np.dtype([("", dt)])
  1362. dt = np.dtype([("", dt)] * 2)
  1363. # The array should be large enough to likely run into threading issues
  1364. arr = np.random.uniform(size=(5000, 4)).view(dt)[:, 0]
  1365. def func(arr):
  1366. arr.nonzero()
  1367. tpe = ThreadPoolExecutor(max_workers=8)
  1368. futures = [tpe.submit(func, arr) for _ in range(10)]
  1369. for f in futures:
  1370. f.result()
  1371. assert arr.dtype is dt
  1372. class TestIndex:
  1373. def test_boolean(self):
  1374. a = rand(3, 5, 8)
  1375. V = rand(5, 8)
  1376. g1 = randint(0, 5, size=15)
  1377. g2 = randint(0, 8, size=15)
  1378. V[g1, g2] = -V[g1, g2]
  1379. assert_((np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all())
  1380. def test_boolean_edgecase(self):
  1381. a = np.array([], dtype='int32')
  1382. b = np.array([], dtype='bool')
  1383. c = a[b]
  1384. assert_equal(c, [])
  1385. assert_equal(c.dtype, np.dtype('int32'))
  1386. class TestBinaryRepr:
  1387. def test_zero(self):
  1388. assert_equal(np.binary_repr(0), '0')
  1389. def test_positive(self):
  1390. assert_equal(np.binary_repr(10), '1010')
  1391. assert_equal(np.binary_repr(12522),
  1392. '11000011101010')
  1393. assert_equal(np.binary_repr(10736848),
  1394. '101000111101010011010000')
  1395. def test_negative(self):
  1396. assert_equal(np.binary_repr(-1), '-1')
  1397. assert_equal(np.binary_repr(-10), '-1010')
  1398. assert_equal(np.binary_repr(-12522),
  1399. '-11000011101010')
  1400. assert_equal(np.binary_repr(-10736848),
  1401. '-101000111101010011010000')
  1402. def test_sufficient_width(self):
  1403. assert_equal(np.binary_repr(0, width=5), '00000')
  1404. assert_equal(np.binary_repr(10, width=7), '0001010')
  1405. assert_equal(np.binary_repr(-5, width=7), '1111011')
  1406. def test_neg_width_boundaries(self):
  1407. # see gh-8670
  1408. # Ensure that the example in the issue does not
  1409. # break before proceeding to a more thorough test.
  1410. assert_equal(np.binary_repr(-128, width=8), '10000000')
  1411. for width in range(1, 11):
  1412. num = -2**(width - 1)
  1413. exp = '1' + (width - 1) * '0'
  1414. assert_equal(np.binary_repr(num, width=width), exp)
  1415. def test_large_neg_int64(self):
  1416. # See gh-14289.
  1417. assert_equal(np.binary_repr(np.int64(-2**62), width=64),
  1418. '11' + '0'*62)
  1419. class TestBaseRepr:
  1420. def test_base3(self):
  1421. assert_equal(np.base_repr(3**5, 3), '100000')
  1422. def test_positive(self):
  1423. assert_equal(np.base_repr(12, 10), '12')
  1424. assert_equal(np.base_repr(12, 10, 4), '000012')
  1425. assert_equal(np.base_repr(12, 4), '30')
  1426. assert_equal(np.base_repr(3731624803700888, 36), '10QR0ROFCEW')
  1427. def test_negative(self):
  1428. assert_equal(np.base_repr(-12, 10), '-12')
  1429. assert_equal(np.base_repr(-12, 10, 4), '-000012')
  1430. assert_equal(np.base_repr(-12, 4), '-30')
  1431. def test_base_range(self):
  1432. with assert_raises(ValueError):
  1433. np.base_repr(1, 1)
  1434. with assert_raises(ValueError):
  1435. np.base_repr(1, 37)
  1436. class TestArrayComparisons:
  1437. def test_array_equal(self):
  1438. res = np.array_equal(np.array([1, 2]), np.array([1, 2]))
  1439. assert_(res)
  1440. assert_(type(res) is bool)
  1441. res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3]))
  1442. assert_(not res)
  1443. assert_(type(res) is bool)
  1444. res = np.array_equal(np.array([1, 2]), np.array([3, 4]))
  1445. assert_(not res)
  1446. assert_(type(res) is bool)
  1447. res = np.array_equal(np.array([1, 2]), np.array([1, 3]))
  1448. assert_(not res)
  1449. assert_(type(res) is bool)
  1450. res = np.array_equal(np.array(['a'], dtype='S1'), np.array(['a'], dtype='S1'))
  1451. assert_(res)
  1452. assert_(type(res) is bool)
  1453. res = np.array_equal(np.array([('a', 1)], dtype='S1,u4'),
  1454. np.array([('a', 1)], dtype='S1,u4'))
  1455. assert_(res)
  1456. assert_(type(res) is bool)
  1457. def test_array_equal_equal_nan(self):
  1458. # Test array_equal with equal_nan kwarg
  1459. a1 = np.array([1, 2, np.nan])
  1460. a2 = np.array([1, np.nan, 2])
  1461. a3 = np.array([1, 2, np.inf])
  1462. # equal_nan=False by default
  1463. assert_(not np.array_equal(a1, a1))
  1464. assert_(np.array_equal(a1, a1, equal_nan=True))
  1465. assert_(not np.array_equal(a1, a2, equal_nan=True))
  1466. # nan's not conflated with inf's
  1467. assert_(not np.array_equal(a1, a3, equal_nan=True))
  1468. # 0-D arrays
  1469. a = np.array(np.nan)
  1470. assert_(not np.array_equal(a, a))
  1471. assert_(np.array_equal(a, a, equal_nan=True))
  1472. # Non-float dtype - equal_nan should have no effect
  1473. a = np.array([1, 2, 3], dtype=int)
  1474. assert_(np.array_equal(a, a))
  1475. assert_(np.array_equal(a, a, equal_nan=True))
  1476. # Multi-dimensional array
  1477. a = np.array([[0, 1], [np.nan, 1]])
  1478. assert_(not np.array_equal(a, a))
  1479. assert_(np.array_equal(a, a, equal_nan=True))
  1480. # Complex values
  1481. a, b = [np.array([1 + 1j])]*2
  1482. a.real, b.imag = np.nan, np.nan
  1483. assert_(not np.array_equal(a, b, equal_nan=False))
  1484. assert_(np.array_equal(a, b, equal_nan=True))
  1485. def test_none_compares_elementwise(self):
  1486. a = np.array([None, 1, None], dtype=object)
  1487. assert_equal(a == None, [True, False, True])
  1488. assert_equal(a != None, [False, True, False])
  1489. a = np.ones(3)
  1490. assert_equal(a == None, [False, False, False])
  1491. assert_equal(a != None, [True, True, True])
  1492. def test_array_equiv(self):
  1493. res = np.array_equiv(np.array([1, 2]), np.array([1, 2]))
  1494. assert_(res)
  1495. assert_(type(res) is bool)
  1496. res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3]))
  1497. assert_(not res)
  1498. assert_(type(res) is bool)
  1499. res = np.array_equiv(np.array([1, 2]), np.array([3, 4]))
  1500. assert_(not res)
  1501. assert_(type(res) is bool)
  1502. res = np.array_equiv(np.array([1, 2]), np.array([1, 3]))
  1503. assert_(not res)
  1504. assert_(type(res) is bool)
  1505. res = np.array_equiv(np.array([1, 1]), np.array([1]))
  1506. assert_(res)
  1507. assert_(type(res) is bool)
  1508. res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]]))
  1509. assert_(res)
  1510. assert_(type(res) is bool)
  1511. res = np.array_equiv(np.array([1, 2]), np.array([2]))
  1512. assert_(not res)
  1513. assert_(type(res) is bool)
  1514. res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]]))
  1515. assert_(not res)
  1516. assert_(type(res) is bool)
  1517. res = np.array_equiv(np.array([1, 2]), np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
  1518. assert_(not res)
  1519. assert_(type(res) is bool)
  1520. @pytest.mark.parametrize("dtype", ["V0", "V3", "V10"])
  1521. def test_compare_unstructured_voids(self, dtype):
  1522. zeros = np.zeros(3, dtype=dtype)
  1523. assert_array_equal(zeros, zeros)
  1524. assert not (zeros != zeros).any()
  1525. if dtype == "V0":
  1526. # Can't test != of actually different data
  1527. return
  1528. nonzeros = np.array([b"1", b"2", b"3"], dtype=dtype)
  1529. assert not (zeros == nonzeros).any()
  1530. assert (zeros != nonzeros).all()
  1531. def assert_array_strict_equal(x, y):
  1532. assert_array_equal(x, y)
  1533. # Check flags, 32 bit arches typically don't provide 16 byte alignment
  1534. if ((x.dtype.alignment <= 8 or
  1535. np.intp().dtype.itemsize != 4) and
  1536. sys.platform != 'win32'):
  1537. assert_(x.flags == y.flags)
  1538. else:
  1539. assert_(x.flags.owndata == y.flags.owndata)
  1540. assert_(x.flags.writeable == y.flags.writeable)
  1541. assert_(x.flags.c_contiguous == y.flags.c_contiguous)
  1542. assert_(x.flags.f_contiguous == y.flags.f_contiguous)
  1543. assert_(x.flags.writebackifcopy == y.flags.writebackifcopy)
  1544. # check endianness
  1545. assert_(x.dtype.isnative == y.dtype.isnative)
  1546. class TestClip:
  1547. def setup_method(self):
  1548. self.nr = 5
  1549. self.nc = 3
  1550. def fastclip(self, a, m, M, out=None, casting=None):
  1551. if out is None:
  1552. if casting is None:
  1553. return a.clip(m, M)
  1554. else:
  1555. return a.clip(m, M, casting=casting)
  1556. else:
  1557. if casting is None:
  1558. return a.clip(m, M, out)
  1559. else:
  1560. return a.clip(m, M, out, casting=casting)
  1561. def clip(self, a, m, M, out=None):
  1562. # use slow-clip
  1563. selector = np.less(a, m) + 2*np.greater(a, M)
  1564. return selector.choose((a, m, M), out=out)
  1565. # Handy functions
  1566. def _generate_data(self, n, m):
  1567. return randn(n, m)
  1568. def _generate_data_complex(self, n, m):
  1569. return randn(n, m) + 1.j * rand(n, m)
  1570. def _generate_flt_data(self, n, m):
  1571. return (randn(n, m)).astype(np.float32)
  1572. def _neg_byteorder(self, a):
  1573. a = np.asarray(a)
  1574. if sys.byteorder == 'little':
  1575. a = a.astype(a.dtype.newbyteorder('>'))
  1576. else:
  1577. a = a.astype(a.dtype.newbyteorder('<'))
  1578. return a
  1579. def _generate_non_native_data(self, n, m):
  1580. data = randn(n, m)
  1581. data = self._neg_byteorder(data)
  1582. assert_(not data.dtype.isnative)
  1583. return data
  1584. def _generate_int_data(self, n, m):
  1585. return (10 * rand(n, m)).astype(np.int64)
  1586. def _generate_int32_data(self, n, m):
  1587. return (10 * rand(n, m)).astype(np.int32)
  1588. # Now the real test cases
  1589. @pytest.mark.parametrize("dtype", '?bhilqpBHILQPefdgFDGO')
  1590. def test_ones_pathological(self, dtype):
  1591. # for preservation of behavior described in
  1592. # gh-12519; amin > amax behavior may still change
  1593. # in the future
  1594. arr = np.ones(10, dtype=dtype)
  1595. expected = np.zeros(10, dtype=dtype)
  1596. actual = np.clip(arr, 1, 0)
  1597. if dtype == 'O':
  1598. assert actual.tolist() == expected.tolist()
  1599. else:
  1600. assert_equal(actual, expected)
  1601. def test_simple_double(self):
  1602. # Test native double input with scalar min/max.
  1603. a = self._generate_data(self.nr, self.nc)
  1604. m = 0.1
  1605. M = 0.6
  1606. ac = self.fastclip(a, m, M)
  1607. act = self.clip(a, m, M)
  1608. assert_array_strict_equal(ac, act)
  1609. def test_simple_int(self):
  1610. # Test native int input with scalar min/max.
  1611. a = self._generate_int_data(self.nr, self.nc)
  1612. a = a.astype(int)
  1613. m = -2
  1614. M = 4
  1615. ac = self.fastclip(a, m, M)
  1616. act = self.clip(a, m, M)
  1617. assert_array_strict_equal(ac, act)
  1618. def test_array_double(self):
  1619. # Test native double input with array min/max.
  1620. a = self._generate_data(self.nr, self.nc)
  1621. m = np.zeros(a.shape)
  1622. M = m + 0.5
  1623. ac = self.fastclip(a, m, M)
  1624. act = self.clip(a, m, M)
  1625. assert_array_strict_equal(ac, act)
  1626. def test_simple_nonnative(self):
  1627. # Test non native double input with scalar min/max.
  1628. # Test native double input with non native double scalar min/max.
  1629. a = self._generate_non_native_data(self.nr, self.nc)
  1630. m = -0.5
  1631. M = 0.6
  1632. ac = self.fastclip(a, m, M)
  1633. act = self.clip(a, m, M)
  1634. assert_array_equal(ac, act)
  1635. # Test native double input with non native double scalar min/max.
  1636. a = self._generate_data(self.nr, self.nc)
  1637. m = -0.5
  1638. M = self._neg_byteorder(0.6)
  1639. assert_(not M.dtype.isnative)
  1640. ac = self.fastclip(a, m, M)
  1641. act = self.clip(a, m, M)
  1642. assert_array_equal(ac, act)
  1643. def test_simple_complex(self):
  1644. # Test native complex input with native double scalar min/max.
  1645. # Test native input with complex double scalar min/max.
  1646. a = 3 * self._generate_data_complex(self.nr, self.nc)
  1647. m = -0.5
  1648. M = 1.
  1649. ac = self.fastclip(a, m, M)
  1650. act = self.clip(a, m, M)
  1651. assert_array_strict_equal(ac, act)
  1652. # Test native input with complex double scalar min/max.
  1653. a = 3 * self._generate_data(self.nr, self.nc)
  1654. m = -0.5 + 1.j
  1655. M = 1. + 2.j
  1656. ac = self.fastclip(a, m, M)
  1657. act = self.clip(a, m, M)
  1658. assert_array_strict_equal(ac, act)
  1659. def test_clip_complex(self):
  1660. # Address Issue gh-5354 for clipping complex arrays
  1661. # Test native complex input without explicit min/max
  1662. # ie, either min=None or max=None
  1663. a = np.ones(10, dtype=complex)
  1664. m = a.min()
  1665. M = a.max()
  1666. am = self.fastclip(a, m, None)
  1667. aM = self.fastclip(a, None, M)
  1668. assert_array_strict_equal(am, a)
  1669. assert_array_strict_equal(aM, a)
  1670. def test_clip_non_contig(self):
  1671. # Test clip for non contiguous native input and native scalar min/max.
  1672. a = self._generate_data(self.nr * 2, self.nc * 3)
  1673. a = a[::2, ::3]
  1674. assert_(not a.flags['F_CONTIGUOUS'])
  1675. assert_(not a.flags['C_CONTIGUOUS'])
  1676. ac = self.fastclip(a, -1.6, 1.7)
  1677. act = self.clip(a, -1.6, 1.7)
  1678. assert_array_strict_equal(ac, act)
  1679. def test_simple_out(self):
  1680. # Test native double input with scalar min/max.
  1681. a = self._generate_data(self.nr, self.nc)
  1682. m = -0.5
  1683. M = 0.6
  1684. ac = np.zeros(a.shape)
  1685. act = np.zeros(a.shape)
  1686. self.fastclip(a, m, M, ac)
  1687. self.clip(a, m, M, act)
  1688. assert_array_strict_equal(ac, act)
  1689. @pytest.mark.parametrize("casting", [None, "unsafe"])
  1690. def test_simple_int32_inout(self, casting):
  1691. # Test native int32 input with double min/max and int32 out.
  1692. a = self._generate_int32_data(self.nr, self.nc)
  1693. m = np.float64(0)
  1694. M = np.float64(2)
  1695. ac = np.zeros(a.shape, dtype=np.int32)
  1696. act = ac.copy()
  1697. if casting is None:
  1698. with assert_warns(DeprecationWarning):
  1699. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1700. self.fastclip(a, m, M, ac, casting=casting)
  1701. else:
  1702. # explicitly passing "unsafe" will silence warning
  1703. self.fastclip(a, m, M, ac, casting=casting)
  1704. self.clip(a, m, M, act)
  1705. assert_array_strict_equal(ac, act)
  1706. def test_simple_int64_out(self):
  1707. # Test native int32 input with int32 scalar min/max and int64 out.
  1708. a = self._generate_int32_data(self.nr, self.nc)
  1709. m = np.int32(-1)
  1710. M = np.int32(1)
  1711. ac = np.zeros(a.shape, dtype=np.int64)
  1712. act = ac.copy()
  1713. self.fastclip(a, m, M, ac)
  1714. self.clip(a, m, M, act)
  1715. assert_array_strict_equal(ac, act)
  1716. def test_simple_int64_inout(self):
  1717. # Test native int32 input with double array min/max and int32 out.
  1718. a = self._generate_int32_data(self.nr, self.nc)
  1719. m = np.zeros(a.shape, np.float64)
  1720. M = np.float64(1)
  1721. ac = np.zeros(a.shape, dtype=np.int32)
  1722. act = ac.copy()
  1723. with assert_warns(DeprecationWarning):
  1724. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1725. self.fastclip(a, m, M, ac)
  1726. self.clip(a, m, M, act)
  1727. assert_array_strict_equal(ac, act)
  1728. def test_simple_int32_out(self):
  1729. # Test native double input with scalar min/max and int out.
  1730. a = self._generate_data(self.nr, self.nc)
  1731. m = -1.0
  1732. M = 2.0
  1733. ac = np.zeros(a.shape, dtype=np.int32)
  1734. act = ac.copy()
  1735. with assert_warns(DeprecationWarning):
  1736. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1737. self.fastclip(a, m, M, ac)
  1738. self.clip(a, m, M, act)
  1739. assert_array_strict_equal(ac, act)
  1740. def test_simple_inplace_01(self):
  1741. # Test native double input with array min/max in-place.
  1742. a = self._generate_data(self.nr, self.nc)
  1743. ac = a.copy()
  1744. m = np.zeros(a.shape)
  1745. M = 1.0
  1746. self.fastclip(a, m, M, a)
  1747. self.clip(a, m, M, ac)
  1748. assert_array_strict_equal(a, ac)
  1749. def test_simple_inplace_02(self):
  1750. # Test native double input with scalar min/max in-place.
  1751. a = self._generate_data(self.nr, self.nc)
  1752. ac = a.copy()
  1753. m = -0.5
  1754. M = 0.6
  1755. self.fastclip(a, m, M, a)
  1756. self.clip(ac, m, M, ac)
  1757. assert_array_strict_equal(a, ac)
  1758. def test_noncontig_inplace(self):
  1759. # Test non contiguous double input with double scalar min/max in-place.
  1760. a = self._generate_data(self.nr * 2, self.nc * 3)
  1761. a = a[::2, ::3]
  1762. assert_(not a.flags['F_CONTIGUOUS'])
  1763. assert_(not a.flags['C_CONTIGUOUS'])
  1764. ac = a.copy()
  1765. m = -0.5
  1766. M = 0.6
  1767. self.fastclip(a, m, M, a)
  1768. self.clip(ac, m, M, ac)
  1769. assert_array_equal(a, ac)
  1770. def test_type_cast_01(self):
  1771. # Test native double input with scalar min/max.
  1772. a = self._generate_data(self.nr, self.nc)
  1773. m = -0.5
  1774. M = 0.6
  1775. ac = self.fastclip(a, m, M)
  1776. act = self.clip(a, m, M)
  1777. assert_array_strict_equal(ac, act)
  1778. def test_type_cast_02(self):
  1779. # Test native int32 input with int32 scalar min/max.
  1780. a = self._generate_int_data(self.nr, self.nc)
  1781. a = a.astype(np.int32)
  1782. m = -2
  1783. M = 4
  1784. ac = self.fastclip(a, m, M)
  1785. act = self.clip(a, m, M)
  1786. assert_array_strict_equal(ac, act)
  1787. def test_type_cast_03(self):
  1788. # Test native int32 input with float64 scalar min/max.
  1789. a = self._generate_int32_data(self.nr, self.nc)
  1790. m = -2
  1791. M = 4
  1792. ac = self.fastclip(a, np.float64(m), np.float64(M))
  1793. act = self.clip(a, np.float64(m), np.float64(M))
  1794. assert_array_strict_equal(ac, act)
  1795. def test_type_cast_04(self):
  1796. # Test native int32 input with float32 scalar min/max.
  1797. a = self._generate_int32_data(self.nr, self.nc)
  1798. m = np.float32(-2)
  1799. M = np.float32(4)
  1800. act = self.fastclip(a, m, M)
  1801. ac = self.clip(a, m, M)
  1802. assert_array_strict_equal(ac, act)
  1803. def test_type_cast_05(self):
  1804. # Test native int32 with double arrays min/max.
  1805. a = self._generate_int_data(self.nr, self.nc)
  1806. m = -0.5
  1807. M = 1.
  1808. ac = self.fastclip(a, m * np.zeros(a.shape), M)
  1809. act = self.clip(a, m * np.zeros(a.shape), M)
  1810. assert_array_strict_equal(ac, act)
  1811. def test_type_cast_06(self):
  1812. # Test native with NON native scalar min/max.
  1813. a = self._generate_data(self.nr, self.nc)
  1814. m = 0.5
  1815. m_s = self._neg_byteorder(m)
  1816. M = 1.
  1817. act = self.clip(a, m_s, M)
  1818. ac = self.fastclip(a, m_s, M)
  1819. assert_array_strict_equal(ac, act)
  1820. def test_type_cast_07(self):
  1821. # Test NON native with native array min/max.
  1822. a = self._generate_data(self.nr, self.nc)
  1823. m = -0.5 * np.ones(a.shape)
  1824. M = 1.
  1825. a_s = self._neg_byteorder(a)
  1826. assert_(not a_s.dtype.isnative)
  1827. act = a_s.clip(m, M)
  1828. ac = self.fastclip(a_s, m, M)
  1829. assert_array_strict_equal(ac, act)
  1830. def test_type_cast_08(self):
  1831. # Test NON native with native scalar min/max.
  1832. a = self._generate_data(self.nr, self.nc)
  1833. m = -0.5
  1834. M = 1.
  1835. a_s = self._neg_byteorder(a)
  1836. assert_(not a_s.dtype.isnative)
  1837. ac = self.fastclip(a_s, m, M)
  1838. act = a_s.clip(m, M)
  1839. assert_array_strict_equal(ac, act)
  1840. def test_type_cast_09(self):
  1841. # Test native with NON native array min/max.
  1842. a = self._generate_data(self.nr, self.nc)
  1843. m = -0.5 * np.ones(a.shape)
  1844. M = 1.
  1845. m_s = self._neg_byteorder(m)
  1846. assert_(not m_s.dtype.isnative)
  1847. ac = self.fastclip(a, m_s, M)
  1848. act = self.clip(a, m_s, M)
  1849. assert_array_strict_equal(ac, act)
  1850. def test_type_cast_10(self):
  1851. # Test native int32 with float min/max and float out for output argument.
  1852. a = self._generate_int_data(self.nr, self.nc)
  1853. b = np.zeros(a.shape, dtype=np.float32)
  1854. m = np.float32(-0.5)
  1855. M = np.float32(1)
  1856. act = self.clip(a, m, M, out=b)
  1857. ac = self.fastclip(a, m, M, out=b)
  1858. assert_array_strict_equal(ac, act)
  1859. def test_type_cast_11(self):
  1860. # Test non native with native scalar, min/max, out non native
  1861. a = self._generate_non_native_data(self.nr, self.nc)
  1862. b = a.copy()
  1863. b = b.astype(b.dtype.newbyteorder('>'))
  1864. bt = b.copy()
  1865. m = -0.5
  1866. M = 1.
  1867. self.fastclip(a, m, M, out=b)
  1868. self.clip(a, m, M, out=bt)
  1869. assert_array_strict_equal(b, bt)
  1870. def test_type_cast_12(self):
  1871. # Test native int32 input and min/max and float out
  1872. a = self._generate_int_data(self.nr, self.nc)
  1873. b = np.zeros(a.shape, dtype=np.float32)
  1874. m = np.int32(0)
  1875. M = np.int32(1)
  1876. act = self.clip(a, m, M, out=b)
  1877. ac = self.fastclip(a, m, M, out=b)
  1878. assert_array_strict_equal(ac, act)
  1879. def test_clip_with_out_simple(self):
  1880. # Test native double input with scalar min/max
  1881. a = self._generate_data(self.nr, self.nc)
  1882. m = -0.5
  1883. M = 0.6
  1884. ac = np.zeros(a.shape)
  1885. act = np.zeros(a.shape)
  1886. self.fastclip(a, m, M, ac)
  1887. self.clip(a, m, M, act)
  1888. assert_array_strict_equal(ac, act)
  1889. def test_clip_with_out_simple2(self):
  1890. # Test native int32 input with double min/max and int32 out
  1891. a = self._generate_int32_data(self.nr, self.nc)
  1892. m = np.float64(0)
  1893. M = np.float64(2)
  1894. ac = np.zeros(a.shape, dtype=np.int32)
  1895. act = ac.copy()
  1896. with assert_warns(DeprecationWarning):
  1897. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1898. self.fastclip(a, m, M, ac)
  1899. self.clip(a, m, M, act)
  1900. assert_array_strict_equal(ac, act)
  1901. def test_clip_with_out_simple_int32(self):
  1902. # Test native int32 input with int32 scalar min/max and int64 out
  1903. a = self._generate_int32_data(self.nr, self.nc)
  1904. m = np.int32(-1)
  1905. M = np.int32(1)
  1906. ac = np.zeros(a.shape, dtype=np.int64)
  1907. act = ac.copy()
  1908. self.fastclip(a, m, M, ac)
  1909. self.clip(a, m, M, act)
  1910. assert_array_strict_equal(ac, act)
  1911. def test_clip_with_out_array_int32(self):
  1912. # Test native int32 input with double array min/max and int32 out
  1913. a = self._generate_int32_data(self.nr, self.nc)
  1914. m = np.zeros(a.shape, np.float64)
  1915. M = np.float64(1)
  1916. ac = np.zeros(a.shape, dtype=np.int32)
  1917. act = ac.copy()
  1918. with assert_warns(DeprecationWarning):
  1919. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1920. self.fastclip(a, m, M, ac)
  1921. self.clip(a, m, M, act)
  1922. assert_array_strict_equal(ac, act)
  1923. def test_clip_with_out_array_outint32(self):
  1924. # Test native double input with scalar min/max and int out
  1925. a = self._generate_data(self.nr, self.nc)
  1926. m = -1.0
  1927. M = 2.0
  1928. ac = np.zeros(a.shape, dtype=np.int32)
  1929. act = ac.copy()
  1930. with assert_warns(DeprecationWarning):
  1931. # NumPy 1.17.0, 2018-02-24 - casting is unsafe
  1932. self.fastclip(a, m, M, ac)
  1933. self.clip(a, m, M, act)
  1934. assert_array_strict_equal(ac, act)
  1935. def test_clip_with_out_transposed(self):
  1936. # Test that the out argument works when transposed
  1937. a = np.arange(16).reshape(4, 4)
  1938. out = np.empty_like(a).T
  1939. a.clip(4, 10, out=out)
  1940. expected = self.clip(a, 4, 10)
  1941. assert_array_equal(out, expected)
  1942. def test_clip_with_out_memory_overlap(self):
  1943. # Test that the out argument works when it has memory overlap
  1944. a = np.arange(16).reshape(4, 4)
  1945. ac = a.copy()
  1946. a[:-1].clip(4, 10, out=a[1:])
  1947. expected = self.clip(ac[:-1], 4, 10)
  1948. assert_array_equal(a[1:], expected)
  1949. def test_clip_inplace_array(self):
  1950. # Test native double input with array min/max
  1951. a = self._generate_data(self.nr, self.nc)
  1952. ac = a.copy()
  1953. m = np.zeros(a.shape)
  1954. M = 1.0
  1955. self.fastclip(a, m, M, a)
  1956. self.clip(a, m, M, ac)
  1957. assert_array_strict_equal(a, ac)
  1958. def test_clip_inplace_simple(self):
  1959. # Test native double input with scalar min/max
  1960. a = self._generate_data(self.nr, self.nc)
  1961. ac = a.copy()
  1962. m = -0.5
  1963. M = 0.6
  1964. self.fastclip(a, m, M, a)
  1965. self.clip(a, m, M, ac)
  1966. assert_array_strict_equal(a, ac)
  1967. def test_clip_func_takes_out(self):
  1968. # Ensure that the clip() function takes an out=argument.
  1969. a = self._generate_data(self.nr, self.nc)
  1970. ac = a.copy()
  1971. m = -0.5
  1972. M = 0.6
  1973. a2 = np.clip(a, m, M, out=a)
  1974. self.clip(a, m, M, ac)
  1975. assert_array_strict_equal(a2, ac)
  1976. assert_(a2 is a)
  1977. def test_clip_nan(self):
  1978. d = np.arange(7.)
  1979. with assert_warns(DeprecationWarning):
  1980. assert_equal(d.clip(min=np.nan), d)
  1981. with assert_warns(DeprecationWarning):
  1982. assert_equal(d.clip(max=np.nan), d)
  1983. with assert_warns(DeprecationWarning):
  1984. assert_equal(d.clip(min=np.nan, max=np.nan), d)
  1985. with assert_warns(DeprecationWarning):
  1986. assert_equal(d.clip(min=-2, max=np.nan), d)
  1987. with assert_warns(DeprecationWarning):
  1988. assert_equal(d.clip(min=np.nan, max=10), d)
  1989. def test_object_clip(self):
  1990. a = np.arange(10, dtype=object)
  1991. actual = np.clip(a, 1, 5)
  1992. expected = np.array([1, 1, 2, 3, 4, 5, 5, 5, 5, 5])
  1993. assert actual.tolist() == expected.tolist()
  1994. def test_clip_all_none(self):
  1995. a = np.arange(10, dtype=object)
  1996. with assert_raises_regex(ValueError, 'max or min'):
  1997. np.clip(a, None, None)
  1998. def test_clip_invalid_casting(self):
  1999. a = np.arange(10, dtype=object)
  2000. with assert_raises_regex(ValueError,
  2001. 'casting must be one of'):
  2002. self.fastclip(a, 1, 8, casting="garbage")
  2003. @pytest.mark.parametrize("amin, amax", [
  2004. # two scalars
  2005. (1, 0),
  2006. # mix scalar and array
  2007. (1, np.zeros(10)),
  2008. # two arrays
  2009. (np.ones(10), np.zeros(10)),
  2010. ])
  2011. def test_clip_value_min_max_flip(self, amin, amax):
  2012. a = np.arange(10, dtype=np.int64)
  2013. # requirement from ufunc_docstrings.py
  2014. expected = np.minimum(np.maximum(a, amin), amax)
  2015. actual = np.clip(a, amin, amax)
  2016. assert_equal(actual, expected)
  2017. @pytest.mark.parametrize("arr, amin, amax, exp", [
  2018. # for a bug in npy_ObjectClip, based on a
  2019. # case produced by hypothesis
  2020. (np.zeros(10, dtype=np.int64),
  2021. 0,
  2022. -2**64+1,
  2023. np.full(10, -2**64+1, dtype=object)),
  2024. # for bugs in NPY_TIMEDELTA_MAX, based on a case
  2025. # produced by hypothesis
  2026. (np.zeros(10, dtype='m8') - 1,
  2027. 0,
  2028. 0,
  2029. np.zeros(10, dtype='m8')),
  2030. ])
  2031. def test_clip_problem_cases(self, arr, amin, amax, exp):
  2032. actual = np.clip(arr, amin, amax)
  2033. assert_equal(actual, exp)
  2034. @pytest.mark.xfail(reason="no scalar nan propagation yet",
  2035. raises=AssertionError,
  2036. strict=True)
  2037. @pytest.mark.parametrize("arr, amin, amax", [
  2038. # problematic scalar nan case from hypothesis
  2039. (np.zeros(10, dtype=np.int64),
  2040. np.array(np.nan),
  2041. np.zeros(10, dtype=np.int32)),
  2042. ])
  2043. @pytest.mark.filterwarnings("ignore::DeprecationWarning")
  2044. def test_clip_scalar_nan_propagation(self, arr, amin, amax):
  2045. # enforcement of scalar nan propagation for comparisons
  2046. # called through clip()
  2047. expected = np.minimum(np.maximum(arr, amin), amax)
  2048. actual = np.clip(arr, amin, amax)
  2049. assert_equal(actual, expected)
  2050. @pytest.mark.xfail(reason="propagation doesn't match spec")
  2051. @pytest.mark.parametrize("arr, amin, amax", [
  2052. (np.array([1] * 10, dtype='m8'),
  2053. np.timedelta64('NaT'),
  2054. np.zeros(10, dtype=np.int32)),
  2055. ])
  2056. @pytest.mark.filterwarnings("ignore::DeprecationWarning")
  2057. def test_NaT_propagation(self, arr, amin, amax):
  2058. # NOTE: the expected function spec doesn't
  2059. # propagate NaT, but clip() now does
  2060. expected = np.minimum(np.maximum(arr, amin), amax)
  2061. actual = np.clip(arr, amin, amax)
  2062. assert_equal(actual, expected)
  2063. @given(
  2064. data=st.data(),
  2065. arr=hynp.arrays(
  2066. dtype=hynp.integer_dtypes() | hynp.floating_dtypes(),
  2067. shape=hynp.array_shapes()
  2068. )
  2069. )
  2070. def test_clip_property(self, data, arr):
  2071. """A property-based test using Hypothesis.
  2072. This aims for maximum generality: it could in principle generate *any*
  2073. valid inputs to np.clip, and in practice generates much more varied
  2074. inputs than human testers come up with.
  2075. Because many of the inputs have tricky dependencies - compatible dtypes
  2076. and mutually-broadcastable shapes - we use `st.data()` strategy draw
  2077. values *inside* the test function, from strategies we construct based
  2078. on previous values. An alternative would be to define a custom strategy
  2079. with `@st.composite`, but until we have duplicated code inline is fine.
  2080. That accounts for most of the function; the actual test is just three
  2081. lines to calculate and compare actual vs expected results!
  2082. """
  2083. numeric_dtypes = hynp.integer_dtypes() | hynp.floating_dtypes()
  2084. # Generate shapes for the bounds which can be broadcast with each other
  2085. # and with the base shape. Below, we might decide to use scalar bounds,
  2086. # but it's clearer to generate these shapes unconditionally in advance.
  2087. in_shapes, result_shape = data.draw(
  2088. hynp.mutually_broadcastable_shapes(
  2089. num_shapes=2, base_shape=arr.shape
  2090. )
  2091. )
  2092. # Scalar `nan` is deprecated due to the differing behaviour it shows.
  2093. s = numeric_dtypes.flatmap(
  2094. lambda x: hynp.from_dtype(x, allow_nan=False))
  2095. amin = data.draw(s | hynp.arrays(dtype=numeric_dtypes,
  2096. shape=in_shapes[0], elements={"allow_nan": False}))
  2097. amax = data.draw(s | hynp.arrays(dtype=numeric_dtypes,
  2098. shape=in_shapes[1], elements={"allow_nan": False}))
  2099. # Then calculate our result and expected result and check that they're
  2100. # equal! See gh-12519 and gh-19457 for discussion deciding on this
  2101. # property and the result_type argument.
  2102. result = np.clip(arr, amin, amax)
  2103. t = np.result_type(arr, amin, amax)
  2104. expected = np.minimum(amax, np.maximum(arr, amin, dtype=t), dtype=t)
  2105. assert result.dtype == t
  2106. assert_array_equal(result, expected)
  2107. class TestAllclose:
  2108. rtol = 1e-5
  2109. atol = 1e-8
  2110. def setup_method(self):
  2111. self.olderr = np.seterr(invalid='ignore')
  2112. def teardown_method(self):
  2113. np.seterr(**self.olderr)
  2114. def tst_allclose(self, x, y):
  2115. assert_(np.allclose(x, y), "%s and %s not close" % (x, y))
  2116. def tst_not_allclose(self, x, y):
  2117. assert_(not np.allclose(x, y), "%s and %s shouldn't be close" % (x, y))
  2118. def test_ip_allclose(self):
  2119. # Parametric test factory.
  2120. arr = np.array([100, 1000])
  2121. aran = np.arange(125).reshape((5, 5, 5))
  2122. atol = self.atol
  2123. rtol = self.rtol
  2124. data = [([1, 0], [1, 0]),
  2125. ([atol], [0]),
  2126. ([1], [1+rtol+atol]),
  2127. (arr, arr + arr*rtol),
  2128. (arr, arr + arr*rtol + atol*2),
  2129. (aran, aran + aran*rtol),
  2130. (np.inf, np.inf),
  2131. (np.inf, [np.inf])]
  2132. for (x, y) in data:
  2133. self.tst_allclose(x, y)
  2134. def test_ip_not_allclose(self):
  2135. # Parametric test factory.
  2136. aran = np.arange(125).reshape((5, 5, 5))
  2137. atol = self.atol
  2138. rtol = self.rtol
  2139. data = [([np.inf, 0], [1, np.inf]),
  2140. ([np.inf, 0], [1, 0]),
  2141. ([np.inf, np.inf], [1, np.inf]),
  2142. ([np.inf, np.inf], [1, 0]),
  2143. ([-np.inf, 0], [np.inf, 0]),
  2144. ([np.nan, 0], [np.nan, 0]),
  2145. ([atol*2], [0]),
  2146. ([1], [1+rtol+atol*2]),
  2147. (aran, aran + aran*atol + atol*2),
  2148. (np.array([np.inf, 1]), np.array([0, np.inf]))]
  2149. for (x, y) in data:
  2150. self.tst_not_allclose(x, y)
  2151. def test_no_parameter_modification(self):
  2152. x = np.array([np.inf, 1])
  2153. y = np.array([0, np.inf])
  2154. np.allclose(x, y)
  2155. assert_array_equal(x, np.array([np.inf, 1]))
  2156. assert_array_equal(y, np.array([0, np.inf]))
  2157. def test_min_int(self):
  2158. # Could make problems because of abs(min_int) == min_int
  2159. min_int = np.iinfo(np.int_).min
  2160. a = np.array([min_int], dtype=np.int_)
  2161. assert_(np.allclose(a, a))
  2162. def test_equalnan(self):
  2163. x = np.array([1.0, np.nan])
  2164. assert_(np.allclose(x, x, equal_nan=True))
  2165. def test_return_class_is_ndarray(self):
  2166. # Issue gh-6475
  2167. # Check that allclose does not preserve subtypes
  2168. class Foo(np.ndarray):
  2169. def __new__(cls, *args, **kwargs):
  2170. return np.array(*args, **kwargs).view(cls)
  2171. a = Foo([1])
  2172. assert_(type(np.allclose(a, a)) is bool)
  2173. class TestIsclose:
  2174. rtol = 1e-5
  2175. atol = 1e-8
  2176. def _setup(self):
  2177. atol = self.atol
  2178. rtol = self.rtol
  2179. arr = np.array([100, 1000])
  2180. aran = np.arange(125).reshape((5, 5, 5))
  2181. self.all_close_tests = [
  2182. ([1, 0], [1, 0]),
  2183. ([atol], [0]),
  2184. ([1], [1 + rtol + atol]),
  2185. (arr, arr + arr*rtol),
  2186. (arr, arr + arr*rtol + atol),
  2187. (aran, aran + aran*rtol),
  2188. (np.inf, np.inf),
  2189. (np.inf, [np.inf]),
  2190. ([np.inf, -np.inf], [np.inf, -np.inf]),
  2191. ]
  2192. self.none_close_tests = [
  2193. ([np.inf, 0], [1, np.inf]),
  2194. ([np.inf, -np.inf], [1, 0]),
  2195. ([np.inf, np.inf], [1, -np.inf]),
  2196. ([np.inf, np.inf], [1, 0]),
  2197. ([np.nan, 0], [np.nan, -np.inf]),
  2198. ([atol*2], [0]),
  2199. ([1], [1 + rtol + atol*2]),
  2200. (aran, aran + rtol*1.1*aran + atol*1.1),
  2201. (np.array([np.inf, 1]), np.array([0, np.inf])),
  2202. ]
  2203. self.some_close_tests = [
  2204. ([np.inf, 0], [np.inf, atol*2]),
  2205. ([atol, 1, 1e6*(1 + 2*rtol) + atol], [0, np.nan, 1e6]),
  2206. (np.arange(3), [0, 1, 2.1]),
  2207. (np.nan, [np.nan, np.nan, np.nan]),
  2208. ([0], [atol, np.inf, -np.inf, np.nan]),
  2209. (0, [atol, np.inf, -np.inf, np.nan]),
  2210. ]
  2211. self.some_close_results = [
  2212. [True, False],
  2213. [True, False, False],
  2214. [True, True, False],
  2215. [False, False, False],
  2216. [True, False, False, False],
  2217. [True, False, False, False],
  2218. ]
  2219. def test_ip_isclose(self):
  2220. self._setup()
  2221. tests = self.some_close_tests
  2222. results = self.some_close_results
  2223. for (x, y), result in zip(tests, results):
  2224. assert_array_equal(np.isclose(x, y), result)
  2225. def tst_all_isclose(self, x, y):
  2226. assert_(np.all(np.isclose(x, y)), "%s and %s not close" % (x, y))
  2227. def tst_none_isclose(self, x, y):
  2228. msg = "%s and %s shouldn't be close"
  2229. assert_(not np.any(np.isclose(x, y)), msg % (x, y))
  2230. def tst_isclose_allclose(self, x, y):
  2231. msg = "isclose.all() and allclose aren't same for %s and %s"
  2232. msg2 = "isclose and allclose aren't same for %s and %s"
  2233. if np.isscalar(x) and np.isscalar(y):
  2234. assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y))
  2235. else:
  2236. assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y))
  2237. def test_ip_all_isclose(self):
  2238. self._setup()
  2239. for (x, y) in self.all_close_tests:
  2240. self.tst_all_isclose(x, y)
  2241. def test_ip_none_isclose(self):
  2242. self._setup()
  2243. for (x, y) in self.none_close_tests:
  2244. self.tst_none_isclose(x, y)
  2245. def test_ip_isclose_allclose(self):
  2246. self._setup()
  2247. tests = (self.all_close_tests + self.none_close_tests +
  2248. self.some_close_tests)
  2249. for (x, y) in tests:
  2250. self.tst_isclose_allclose(x, y)
  2251. def test_equal_nan(self):
  2252. assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True])
  2253. arr = np.array([1.0, np.nan])
  2254. assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True])
  2255. def test_masked_arrays(self):
  2256. # Make sure to test the output type when arguments are interchanged.
  2257. x = np.ma.masked_where([True, True, False], np.arange(3))
  2258. assert_(type(x) is type(np.isclose(2, x)))
  2259. assert_(type(x) is type(np.isclose(x, 2)))
  2260. x = np.ma.masked_where([True, True, False], [np.nan, np.inf, np.nan])
  2261. assert_(type(x) is type(np.isclose(np.inf, x)))
  2262. assert_(type(x) is type(np.isclose(x, np.inf)))
  2263. x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])
  2264. y = np.isclose(np.nan, x, equal_nan=True)
  2265. assert_(type(x) is type(y))
  2266. # Ensure that the mask isn't modified...
  2267. assert_array_equal([True, True, False], y.mask)
  2268. y = np.isclose(x, np.nan, equal_nan=True)
  2269. assert_(type(x) is type(y))
  2270. # Ensure that the mask isn't modified...
  2271. assert_array_equal([True, True, False], y.mask)
  2272. x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])
  2273. y = np.isclose(x, x, equal_nan=True)
  2274. assert_(type(x) is type(y))
  2275. # Ensure that the mask isn't modified...
  2276. assert_array_equal([True, True, False], y.mask)
  2277. def test_scalar_return(self):
  2278. assert_(np.isscalar(np.isclose(1, 1)))
  2279. def test_no_parameter_modification(self):
  2280. x = np.array([np.inf, 1])
  2281. y = np.array([0, np.inf])
  2282. np.isclose(x, y)
  2283. assert_array_equal(x, np.array([np.inf, 1]))
  2284. assert_array_equal(y, np.array([0, np.inf]))
  2285. def test_non_finite_scalar(self):
  2286. # GH7014, when two scalars are compared the output should also be a
  2287. # scalar
  2288. assert_(np.isclose(np.inf, -np.inf) is np.False_)
  2289. assert_(np.isclose(0, np.inf) is np.False_)
  2290. assert_(type(np.isclose(0, np.inf)) is np.bool_)
  2291. def test_timedelta(self):
  2292. # Allclose currently works for timedelta64 as long as `atol` is
  2293. # an integer or also a timedelta64
  2294. a = np.array([[1, 2, 3, "NaT"]], dtype="m8[ns]")
  2295. assert np.isclose(a, a, atol=0, equal_nan=True).all()
  2296. assert np.isclose(a, a, atol=np.timedelta64(1, "ns"), equal_nan=True).all()
  2297. assert np.allclose(a, a, atol=0, equal_nan=True)
  2298. assert np.allclose(a, a, atol=np.timedelta64(1, "ns"), equal_nan=True)
  2299. class TestStdVar:
  2300. def setup_method(self):
  2301. self.A = np.array([1, -1, 1, -1])
  2302. self.real_var = 1
  2303. def test_basic(self):
  2304. assert_almost_equal(np.var(self.A), self.real_var)
  2305. assert_almost_equal(np.std(self.A)**2, self.real_var)
  2306. def test_scalars(self):
  2307. assert_equal(np.var(1), 0)
  2308. assert_equal(np.std(1), 0)
  2309. def test_ddof1(self):
  2310. assert_almost_equal(np.var(self.A, ddof=1),
  2311. self.real_var * len(self.A) / (len(self.A) - 1))
  2312. assert_almost_equal(np.std(self.A, ddof=1)**2,
  2313. self.real_var*len(self.A) / (len(self.A) - 1))
  2314. def test_ddof2(self):
  2315. assert_almost_equal(np.var(self.A, ddof=2),
  2316. self.real_var * len(self.A) / (len(self.A) - 2))
  2317. assert_almost_equal(np.std(self.A, ddof=2)**2,
  2318. self.real_var * len(self.A) / (len(self.A) - 2))
  2319. def test_out_scalar(self):
  2320. d = np.arange(10)
  2321. out = np.array(0.)
  2322. r = np.std(d, out=out)
  2323. assert_(r is out)
  2324. assert_array_equal(r, out)
  2325. r = np.var(d, out=out)
  2326. assert_(r is out)
  2327. assert_array_equal(r, out)
  2328. r = np.mean(d, out=out)
  2329. assert_(r is out)
  2330. assert_array_equal(r, out)
  2331. class TestStdVarComplex:
  2332. def test_basic(self):
  2333. A = np.array([1, 1.j, -1, -1.j])
  2334. real_var = 1
  2335. assert_almost_equal(np.var(A), real_var)
  2336. assert_almost_equal(np.std(A)**2, real_var)
  2337. def test_scalars(self):
  2338. assert_equal(np.var(1j), 0)
  2339. assert_equal(np.std(1j), 0)
  2340. class TestCreationFuncs:
  2341. # Test ones, zeros, empty and full.
  2342. def setup_method(self):
  2343. dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())}
  2344. # void, bytes, str
  2345. variable_sized = {tp for tp in dtypes if tp.str.endswith('0')}
  2346. self.dtypes = sorted(dtypes - variable_sized |
  2347. {np.dtype(tp.str.replace("0", str(i)))
  2348. for tp in variable_sized for i in range(1, 10)},
  2349. key=lambda dtype: dtype.str)
  2350. self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}
  2351. self.ndims = 10
  2352. def check_function(self, func, fill_value=None):
  2353. par = ((0, 1, 2),
  2354. range(self.ndims),
  2355. self.orders,
  2356. self.dtypes)
  2357. fill_kwarg = {}
  2358. if fill_value is not None:
  2359. fill_kwarg = {'fill_value': fill_value}
  2360. for size, ndims, order, dtype in itertools.product(*par):
  2361. shape = ndims * [size]
  2362. # do not fill void type
  2363. if fill_kwarg and dtype.str.startswith('|V'):
  2364. continue
  2365. arr = func(shape, order=order, dtype=dtype,
  2366. **fill_kwarg)
  2367. assert_equal(arr.dtype, dtype)
  2368. assert_(getattr(arr.flags, self.orders[order]))
  2369. if fill_value is not None:
  2370. if dtype.str.startswith('|S'):
  2371. val = str(fill_value)
  2372. else:
  2373. val = fill_value
  2374. assert_equal(arr, dtype.type(val))
  2375. def test_zeros(self):
  2376. self.check_function(np.zeros)
  2377. def test_ones(self):
  2378. self.check_function(np.ones)
  2379. def test_empty(self):
  2380. self.check_function(np.empty)
  2381. def test_full(self):
  2382. self.check_function(np.full, 0)
  2383. self.check_function(np.full, 1)
  2384. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2385. def test_for_reference_leak(self):
  2386. # Make sure we have an object for reference
  2387. dim = 1
  2388. beg = sys.getrefcount(dim)
  2389. np.zeros([dim]*10)
  2390. assert_(sys.getrefcount(dim) == beg)
  2391. np.ones([dim]*10)
  2392. assert_(sys.getrefcount(dim) == beg)
  2393. np.empty([dim]*10)
  2394. assert_(sys.getrefcount(dim) == beg)
  2395. np.full([dim]*10, 0)
  2396. assert_(sys.getrefcount(dim) == beg)
  2397. class TestLikeFuncs:
  2398. '''Test ones_like, zeros_like, empty_like and full_like'''
  2399. def setup_method(self):
  2400. self.data = [
  2401. # Array scalars
  2402. (np.array(3.), None),
  2403. (np.array(3), 'f8'),
  2404. # 1D arrays
  2405. (np.arange(6, dtype='f4'), None),
  2406. (np.arange(6), 'c16'),
  2407. # 2D C-layout arrays
  2408. (np.arange(6).reshape(2, 3), None),
  2409. (np.arange(6).reshape(3, 2), 'i1'),
  2410. # 2D F-layout arrays
  2411. (np.arange(6).reshape((2, 3), order='F'), None),
  2412. (np.arange(6).reshape((3, 2), order='F'), 'i1'),
  2413. # 3D C-layout arrays
  2414. (np.arange(24).reshape(2, 3, 4), None),
  2415. (np.arange(24).reshape(4, 3, 2), 'f4'),
  2416. # 3D F-layout arrays
  2417. (np.arange(24).reshape((2, 3, 4), order='F'), None),
  2418. (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'),
  2419. # 3D non-C/F-layout arrays
  2420. (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),
  2421. (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'),
  2422. ]
  2423. self.shapes = [(), (5,), (5,6,), (5,6,7,)]
  2424. def compare_array_value(self, dz, value, fill_value):
  2425. if value is not None:
  2426. if fill_value:
  2427. # Conversion is close to what np.full_like uses
  2428. # but we may want to convert directly in the future
  2429. # which may result in errors (where this does not).
  2430. z = np.array(value).astype(dz.dtype)
  2431. assert_(np.all(dz == z))
  2432. else:
  2433. assert_(np.all(dz == value))
  2434. def check_like_function(self, like_function, value, fill_value=False):
  2435. if fill_value:
  2436. fill_kwarg = {'fill_value': value}
  2437. else:
  2438. fill_kwarg = {}
  2439. for d, dtype in self.data:
  2440. # default (K) order, dtype
  2441. dz = like_function(d, dtype=dtype, **fill_kwarg)
  2442. assert_equal(dz.shape, d.shape)
  2443. assert_equal(np.array(dz.strides)*d.dtype.itemsize,
  2444. np.array(d.strides)*dz.dtype.itemsize)
  2445. assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous)
  2446. assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous)
  2447. if dtype is None:
  2448. assert_equal(dz.dtype, d.dtype)
  2449. else:
  2450. assert_equal(dz.dtype, np.dtype(dtype))
  2451. self.compare_array_value(dz, value, fill_value)
  2452. # C order, default dtype
  2453. dz = like_function(d, order='C', dtype=dtype, **fill_kwarg)
  2454. assert_equal(dz.shape, d.shape)
  2455. assert_(dz.flags.c_contiguous)
  2456. if dtype is None:
  2457. assert_equal(dz.dtype, d.dtype)
  2458. else:
  2459. assert_equal(dz.dtype, np.dtype(dtype))
  2460. self.compare_array_value(dz, value, fill_value)
  2461. # F order, default dtype
  2462. dz = like_function(d, order='F', dtype=dtype, **fill_kwarg)
  2463. assert_equal(dz.shape, d.shape)
  2464. assert_(dz.flags.f_contiguous)
  2465. if dtype is None:
  2466. assert_equal(dz.dtype, d.dtype)
  2467. else:
  2468. assert_equal(dz.dtype, np.dtype(dtype))
  2469. self.compare_array_value(dz, value, fill_value)
  2470. # A order
  2471. dz = like_function(d, order='A', dtype=dtype, **fill_kwarg)
  2472. assert_equal(dz.shape, d.shape)
  2473. if d.flags.f_contiguous:
  2474. assert_(dz.flags.f_contiguous)
  2475. else:
  2476. assert_(dz.flags.c_contiguous)
  2477. if dtype is None:
  2478. assert_equal(dz.dtype, d.dtype)
  2479. else:
  2480. assert_equal(dz.dtype, np.dtype(dtype))
  2481. self.compare_array_value(dz, value, fill_value)
  2482. # Test the 'shape' parameter
  2483. for s in self.shapes:
  2484. for o in 'CFA':
  2485. sz = like_function(d, dtype=dtype, shape=s, order=o,
  2486. **fill_kwarg)
  2487. assert_equal(sz.shape, s)
  2488. if dtype is None:
  2489. assert_equal(sz.dtype, d.dtype)
  2490. else:
  2491. assert_equal(sz.dtype, np.dtype(dtype))
  2492. if o == 'C' or (o == 'A' and d.flags.c_contiguous):
  2493. assert_(sz.flags.c_contiguous)
  2494. elif o == 'F' or (o == 'A' and d.flags.f_contiguous):
  2495. assert_(sz.flags.f_contiguous)
  2496. self.compare_array_value(sz, value, fill_value)
  2497. if (d.ndim != len(s)):
  2498. assert_equal(np.argsort(like_function(d, dtype=dtype,
  2499. shape=s, order='K',
  2500. **fill_kwarg).strides),
  2501. np.argsort(np.empty(s, dtype=dtype,
  2502. order='C').strides))
  2503. else:
  2504. assert_equal(np.argsort(like_function(d, dtype=dtype,
  2505. shape=s, order='K',
  2506. **fill_kwarg).strides),
  2507. np.argsort(d.strides))
  2508. # Test the 'subok' parameter
  2509. class MyNDArray(np.ndarray):
  2510. pass
  2511. a = np.array([[1, 2], [3, 4]]).view(MyNDArray)
  2512. b = like_function(a, **fill_kwarg)
  2513. assert_(type(b) is MyNDArray)
  2514. b = like_function(a, subok=False, **fill_kwarg)
  2515. assert_(type(b) is not MyNDArray)
  2516. def test_ones_like(self):
  2517. self.check_like_function(np.ones_like, 1)
  2518. def test_zeros_like(self):
  2519. self.check_like_function(np.zeros_like, 0)
  2520. def test_empty_like(self):
  2521. self.check_like_function(np.empty_like, None)
  2522. def test_filled_like(self):
  2523. self.check_like_function(np.full_like, 0, True)
  2524. self.check_like_function(np.full_like, 1, True)
  2525. self.check_like_function(np.full_like, 1000, True)
  2526. self.check_like_function(np.full_like, 123.456, True)
  2527. # Inf to integer casts cause invalid-value errors: ignore them.
  2528. with np.errstate(invalid="ignore"):
  2529. self.check_like_function(np.full_like, np.inf, True)
  2530. @pytest.mark.parametrize('likefunc', [np.empty_like, np.full_like,
  2531. np.zeros_like, np.ones_like])
  2532. @pytest.mark.parametrize('dtype', [str, bytes])
  2533. def test_dtype_str_bytes(self, likefunc, dtype):
  2534. # Regression test for gh-19860
  2535. a = np.arange(16).reshape(2, 8)
  2536. b = a[:, ::2] # Ensure b is not contiguous.
  2537. kwargs = {'fill_value': ''} if likefunc == np.full_like else {}
  2538. result = likefunc(b, dtype=dtype, **kwargs)
  2539. if dtype == str:
  2540. assert result.strides == (16, 4)
  2541. else:
  2542. # dtype is bytes
  2543. assert result.strides == (4, 1)
  2544. class TestCorrelate:
  2545. def _setup(self, dt):
  2546. self.x = np.array([1, 2, 3, 4, 5], dtype=dt)
  2547. self.xs = np.arange(1, 20)[::3]
  2548. self.y = np.array([-1, -2, -3], dtype=dt)
  2549. self.z1 = np.array([-3., -8., -14., -20., -26., -14., -5.], dtype=dt)
  2550. self.z1_4 = np.array([-2., -5., -8., -11., -14., -5.], dtype=dt)
  2551. self.z1r = np.array([-15., -22., -22., -16., -10., -4., -1.], dtype=dt)
  2552. self.z2 = np.array([-5., -14., -26., -20., -14., -8., -3.], dtype=dt)
  2553. self.z2r = np.array([-1., -4., -10., -16., -22., -22., -15.], dtype=dt)
  2554. self.zs = np.array([-3., -14., -30., -48., -66., -84.,
  2555. -102., -54., -19.], dtype=dt)
  2556. def test_float(self):
  2557. self._setup(float)
  2558. z = np.correlate(self.x, self.y, 'full')
  2559. assert_array_almost_equal(z, self.z1)
  2560. z = np.correlate(self.x, self.y[:-1], 'full')
  2561. assert_array_almost_equal(z, self.z1_4)
  2562. z = np.correlate(self.y, self.x, 'full')
  2563. assert_array_almost_equal(z, self.z2)
  2564. z = np.correlate(self.x[::-1], self.y, 'full')
  2565. assert_array_almost_equal(z, self.z1r)
  2566. z = np.correlate(self.y, self.x[::-1], 'full')
  2567. assert_array_almost_equal(z, self.z2r)
  2568. z = np.correlate(self.xs, self.y, 'full')
  2569. assert_array_almost_equal(z, self.zs)
  2570. def test_object(self):
  2571. self._setup(Decimal)
  2572. z = np.correlate(self.x, self.y, 'full')
  2573. assert_array_almost_equal(z, self.z1)
  2574. z = np.correlate(self.y, self.x, 'full')
  2575. assert_array_almost_equal(z, self.z2)
  2576. def test_no_overwrite(self):
  2577. d = np.ones(100)
  2578. k = np.ones(3)
  2579. np.correlate(d, k)
  2580. assert_array_equal(d, np.ones(100))
  2581. assert_array_equal(k, np.ones(3))
  2582. def test_complex(self):
  2583. x = np.array([1, 2, 3, 4+1j], dtype=complex)
  2584. y = np.array([-1, -2j, 3+1j], dtype=complex)
  2585. r_z = np.array([3-1j, 6, 8+1j, 11+5j, -5+8j, -4-1j], dtype=complex)
  2586. r_z = r_z[::-1].conjugate()
  2587. z = np.correlate(y, x, mode='full')
  2588. assert_array_almost_equal(z, r_z)
  2589. def test_zero_size(self):
  2590. with pytest.raises(ValueError):
  2591. np.correlate(np.array([]), np.ones(1000), mode='full')
  2592. with pytest.raises(ValueError):
  2593. np.correlate(np.ones(1000), np.array([]), mode='full')
  2594. def test_mode(self):
  2595. d = np.ones(100)
  2596. k = np.ones(3)
  2597. default_mode = np.correlate(d, k, mode='valid')
  2598. with assert_warns(DeprecationWarning):
  2599. valid_mode = np.correlate(d, k, mode='v')
  2600. assert_array_equal(valid_mode, default_mode)
  2601. # integer mode
  2602. with assert_raises(ValueError):
  2603. np.correlate(d, k, mode=-1)
  2604. assert_array_equal(np.correlate(d, k, mode=0), valid_mode)
  2605. # illegal arguments
  2606. with assert_raises(TypeError):
  2607. np.correlate(d, k, mode=None)
  2608. class TestConvolve:
  2609. def test_object(self):
  2610. d = [1.] * 100
  2611. k = [1.] * 3
  2612. assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))
  2613. def test_no_overwrite(self):
  2614. d = np.ones(100)
  2615. k = np.ones(3)
  2616. np.convolve(d, k)
  2617. assert_array_equal(d, np.ones(100))
  2618. assert_array_equal(k, np.ones(3))
  2619. def test_mode(self):
  2620. d = np.ones(100)
  2621. k = np.ones(3)
  2622. default_mode = np.convolve(d, k, mode='full')
  2623. with assert_warns(DeprecationWarning):
  2624. full_mode = np.convolve(d, k, mode='f')
  2625. assert_array_equal(full_mode, default_mode)
  2626. # integer mode
  2627. with assert_raises(ValueError):
  2628. np.convolve(d, k, mode=-1)
  2629. assert_array_equal(np.convolve(d, k, mode=2), full_mode)
  2630. # illegal arguments
  2631. with assert_raises(TypeError):
  2632. np.convolve(d, k, mode=None)
  2633. class TestArgwhere:
  2634. @pytest.mark.parametrize('nd', [0, 1, 2])
  2635. def test_nd(self, nd):
  2636. # get an nd array with multiple elements in every dimension
  2637. x = np.empty((2,)*nd, bool)
  2638. # none
  2639. x[...] = False
  2640. assert_equal(np.argwhere(x).shape, (0, nd))
  2641. # only one
  2642. x[...] = False
  2643. x.flat[0] = True
  2644. assert_equal(np.argwhere(x).shape, (1, nd))
  2645. # all but one
  2646. x[...] = True
  2647. x.flat[0] = False
  2648. assert_equal(np.argwhere(x).shape, (x.size - 1, nd))
  2649. # all
  2650. x[...] = True
  2651. assert_equal(np.argwhere(x).shape, (x.size, nd))
  2652. def test_2D(self):
  2653. x = np.arange(6).reshape((2, 3))
  2654. assert_array_equal(np.argwhere(x > 1),
  2655. [[0, 2],
  2656. [1, 0],
  2657. [1, 1],
  2658. [1, 2]])
  2659. def test_list(self):
  2660. assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]])
  2661. class TestStringFunction:
  2662. def test_set_string_function(self):
  2663. a = np.array([1])
  2664. np.set_string_function(lambda x: "FOO", repr=True)
  2665. assert_equal(repr(a), "FOO")
  2666. np.set_string_function(None, repr=True)
  2667. assert_equal(repr(a), "array([1])")
  2668. np.set_string_function(lambda x: "FOO", repr=False)
  2669. assert_equal(str(a), "FOO")
  2670. np.set_string_function(None, repr=False)
  2671. assert_equal(str(a), "[1]")
  2672. class TestRoll:
  2673. def test_roll1d(self):
  2674. x = np.arange(10)
  2675. xr = np.roll(x, 2)
  2676. assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]))
  2677. def test_roll2d(self):
  2678. x2 = np.reshape(np.arange(10), (2, 5))
  2679. x2r = np.roll(x2, 1)
  2680. assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]))
  2681. x2r = np.roll(x2, 1, axis=0)
  2682. assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
  2683. x2r = np.roll(x2, 1, axis=1)
  2684. assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
  2685. # Roll multiple axes at once.
  2686. x2r = np.roll(x2, 1, axis=(0, 1))
  2687. assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
  2688. x2r = np.roll(x2, (1, 0), axis=(0, 1))
  2689. assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
  2690. x2r = np.roll(x2, (-1, 0), axis=(0, 1))
  2691. assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
  2692. x2r = np.roll(x2, (0, 1), axis=(0, 1))
  2693. assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
  2694. x2r = np.roll(x2, (0, -1), axis=(0, 1))
  2695. assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]))
  2696. x2r = np.roll(x2, (1, 1), axis=(0, 1))
  2697. assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
  2698. x2r = np.roll(x2, (-1, -1), axis=(0, 1))
  2699. assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]]))
  2700. # Roll the same axis multiple times.
  2701. x2r = np.roll(x2, 1, axis=(0, 0))
  2702. assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]))
  2703. x2r = np.roll(x2, 1, axis=(1, 1))
  2704. assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]))
  2705. # Roll more than one turn in either direction.
  2706. x2r = np.roll(x2, 6, axis=1)
  2707. assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
  2708. x2r = np.roll(x2, -4, axis=1)
  2709. assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
  2710. def test_roll_empty(self):
  2711. x = np.array([])
  2712. assert_equal(np.roll(x, 1), np.array([]))
  2713. class TestRollaxis:
  2714. # expected shape indexed by (axis, start) for array of
  2715. # shape (1, 2, 3, 4)
  2716. tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4),
  2717. (0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4),
  2718. (0, 4): (2, 3, 4, 1),
  2719. (1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4),
  2720. (1, 2): (1, 2, 3, 4), (1, 3): (1, 3, 2, 4),
  2721. (1, 4): (1, 3, 4, 2),
  2722. (2, 0): (3, 1, 2, 4), (2, 1): (1, 3, 2, 4),
  2723. (2, 2): (1, 2, 3, 4), (2, 3): (1, 2, 3, 4),
  2724. (2, 4): (1, 2, 4, 3),
  2725. (3, 0): (4, 1, 2, 3), (3, 1): (1, 4, 2, 3),
  2726. (3, 2): (1, 2, 4, 3), (3, 3): (1, 2, 3, 4),
  2727. (3, 4): (1, 2, 3, 4)}
  2728. def test_exceptions(self):
  2729. a = np.arange(1*2*3*4).reshape(1, 2, 3, 4)
  2730. assert_raises(np.AxisError, np.rollaxis, a, -5, 0)
  2731. assert_raises(np.AxisError, np.rollaxis, a, 0, -5)
  2732. assert_raises(np.AxisError, np.rollaxis, a, 4, 0)
  2733. assert_raises(np.AxisError, np.rollaxis, a, 0, 5)
  2734. def test_results(self):
  2735. a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()
  2736. aind = np.indices(a.shape)
  2737. assert_(a.flags['OWNDATA'])
  2738. for (i, j) in self.tgtshape:
  2739. # positive axis, positive start
  2740. res = np.rollaxis(a, axis=i, start=j)
  2741. i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
  2742. assert_(np.all(res[i0, i1, i2, i3] == a))
  2743. assert_(res.shape == self.tgtshape[(i, j)], str((i,j)))
  2744. assert_(not res.flags['OWNDATA'])
  2745. # negative axis, positive start
  2746. ip = i + 1
  2747. res = np.rollaxis(a, axis=-ip, start=j)
  2748. i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
  2749. assert_(np.all(res[i0, i1, i2, i3] == a))
  2750. assert_(res.shape == self.tgtshape[(4 - ip, j)])
  2751. assert_(not res.flags['OWNDATA'])
  2752. # positive axis, negative start
  2753. jp = j + 1 if j < 4 else j
  2754. res = np.rollaxis(a, axis=i, start=-jp)
  2755. i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
  2756. assert_(np.all(res[i0, i1, i2, i3] == a))
  2757. assert_(res.shape == self.tgtshape[(i, 4 - jp)])
  2758. assert_(not res.flags['OWNDATA'])
  2759. # negative axis, negative start
  2760. ip = i + 1
  2761. jp = j + 1 if j < 4 else j
  2762. res = np.rollaxis(a, axis=-ip, start=-jp)
  2763. i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
  2764. assert_(np.all(res[i0, i1, i2, i3] == a))
  2765. assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)])
  2766. assert_(not res.flags['OWNDATA'])
  2767. class TestMoveaxis:
  2768. def test_move_to_end(self):
  2769. x = np.random.randn(5, 6, 7)
  2770. for source, expected in [(0, (6, 7, 5)),
  2771. (1, (5, 7, 6)),
  2772. (2, (5, 6, 7)),
  2773. (-1, (5, 6, 7))]:
  2774. actual = np.moveaxis(x, source, -1).shape
  2775. assert_(actual, expected)
  2776. def test_move_new_position(self):
  2777. x = np.random.randn(1, 2, 3, 4)
  2778. for source, destination, expected in [
  2779. (0, 1, (2, 1, 3, 4)),
  2780. (1, 2, (1, 3, 2, 4)),
  2781. (1, -1, (1, 3, 4, 2)),
  2782. ]:
  2783. actual = np.moveaxis(x, source, destination).shape
  2784. assert_(actual, expected)
  2785. def test_preserve_order(self):
  2786. x = np.zeros((1, 2, 3, 4))
  2787. for source, destination in [
  2788. (0, 0),
  2789. (3, -1),
  2790. (-1, 3),
  2791. ([0, -1], [0, -1]),
  2792. ([2, 0], [2, 0]),
  2793. (range(4), range(4)),
  2794. ]:
  2795. actual = np.moveaxis(x, source, destination).shape
  2796. assert_(actual, (1, 2, 3, 4))
  2797. def test_move_multiples(self):
  2798. x = np.zeros((0, 1, 2, 3))
  2799. for source, destination, expected in [
  2800. ([0, 1], [2, 3], (2, 3, 0, 1)),
  2801. ([2, 3], [0, 1], (2, 3, 0, 1)),
  2802. ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)),
  2803. ([3, 0], [1, 0], (0, 3, 1, 2)),
  2804. ([0, 3], [0, 1], (0, 3, 1, 2)),
  2805. ]:
  2806. actual = np.moveaxis(x, source, destination).shape
  2807. assert_(actual, expected)
  2808. def test_errors(self):
  2809. x = np.random.randn(1, 2, 3)
  2810. assert_raises_regex(np.AxisError, 'source.*out of bounds',
  2811. np.moveaxis, x, 3, 0)
  2812. assert_raises_regex(np.AxisError, 'source.*out of bounds',
  2813. np.moveaxis, x, -4, 0)
  2814. assert_raises_regex(np.AxisError, 'destination.*out of bounds',
  2815. np.moveaxis, x, 0, 5)
  2816. assert_raises_regex(ValueError, 'repeated axis in `source`',
  2817. np.moveaxis, x, [0, 0], [0, 1])
  2818. assert_raises_regex(ValueError, 'repeated axis in `destination`',
  2819. np.moveaxis, x, [0, 1], [1, 1])
  2820. assert_raises_regex(ValueError, 'must have the same number',
  2821. np.moveaxis, x, 0, [0, 1])
  2822. assert_raises_regex(ValueError, 'must have the same number',
  2823. np.moveaxis, x, [0, 1], [0])
  2824. def test_array_likes(self):
  2825. x = np.ma.zeros((1, 2, 3))
  2826. result = np.moveaxis(x, 0, 0)
  2827. assert_(x.shape, result.shape)
  2828. assert_(isinstance(result, np.ma.MaskedArray))
  2829. x = [1, 2, 3]
  2830. result = np.moveaxis(x, 0, 0)
  2831. assert_(x, list(result))
  2832. assert_(isinstance(result, np.ndarray))
  2833. class TestCross:
  2834. def test_2x2(self):
  2835. u = [1, 2]
  2836. v = [3, 4]
  2837. z = -2
  2838. cp = np.cross(u, v)
  2839. assert_equal(cp, z)
  2840. cp = np.cross(v, u)
  2841. assert_equal(cp, -z)
  2842. def test_2x3(self):
  2843. u = [1, 2]
  2844. v = [3, 4, 5]
  2845. z = np.array([10, -5, -2])
  2846. cp = np.cross(u, v)
  2847. assert_equal(cp, z)
  2848. cp = np.cross(v, u)
  2849. assert_equal(cp, -z)
  2850. def test_3x3(self):
  2851. u = [1, 2, 3]
  2852. v = [4, 5, 6]
  2853. z = np.array([-3, 6, -3])
  2854. cp = np.cross(u, v)
  2855. assert_equal(cp, z)
  2856. cp = np.cross(v, u)
  2857. assert_equal(cp, -z)
  2858. def test_broadcasting(self):
  2859. # Ticket #2624 (Trac #2032)
  2860. u = np.tile([1, 2], (11, 1))
  2861. v = np.tile([3, 4], (11, 1))
  2862. z = -2
  2863. assert_equal(np.cross(u, v), z)
  2864. assert_equal(np.cross(v, u), -z)
  2865. assert_equal(np.cross(u, u), 0)
  2866. u = np.tile([1, 2], (11, 1)).T
  2867. v = np.tile([3, 4, 5], (11, 1))
  2868. z = np.tile([10, -5, -2], (11, 1))
  2869. assert_equal(np.cross(u, v, axisa=0), z)
  2870. assert_equal(np.cross(v, u.T), -z)
  2871. assert_equal(np.cross(v, v), 0)
  2872. u = np.tile([1, 2, 3], (11, 1)).T
  2873. v = np.tile([3, 4], (11, 1)).T
  2874. z = np.tile([-12, 9, -2], (11, 1))
  2875. assert_equal(np.cross(u, v, axisa=0, axisb=0), z)
  2876. assert_equal(np.cross(v.T, u.T), -z)
  2877. assert_equal(np.cross(u.T, u.T), 0)
  2878. u = np.tile([1, 2, 3], (5, 1))
  2879. v = np.tile([4, 5, 6], (5, 1)).T
  2880. z = np.tile([-3, 6, -3], (5, 1))
  2881. assert_equal(np.cross(u, v, axisb=0), z)
  2882. assert_equal(np.cross(v.T, u), -z)
  2883. assert_equal(np.cross(u, u), 0)
  2884. def test_broadcasting_shapes(self):
  2885. u = np.ones((2, 1, 3))
  2886. v = np.ones((5, 3))
  2887. assert_equal(np.cross(u, v).shape, (2, 5, 3))
  2888. u = np.ones((10, 3, 5))
  2889. v = np.ones((2, 5))
  2890. assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3))
  2891. assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=2)
  2892. assert_raises(np.AxisError, np.cross, u, v, axisa=3, axisb=0)
  2893. u = np.ones((10, 3, 5, 7))
  2894. v = np.ones((5, 7, 2))
  2895. assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7))
  2896. assert_raises(np.AxisError, np.cross, u, v, axisa=-5, axisb=2)
  2897. assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=-4)
  2898. # gh-5885
  2899. u = np.ones((3, 4, 2))
  2900. for axisc in range(-2, 2):
  2901. assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4))
  2902. def test_uint8_int32_mixed_dtypes(self):
  2903. # regression test for gh-19138
  2904. u = np.array([[195, 8, 9]], np.uint8)
  2905. v = np.array([250, 166, 68], np.int32)
  2906. z = np.array([[950, 11010, -30370]], dtype=np.int32)
  2907. assert_equal(np.cross(v, u), z)
  2908. assert_equal(np.cross(u, v), -z)
  2909. def test_outer_out_param():
  2910. arr1 = np.ones((5,))
  2911. arr2 = np.ones((2,))
  2912. arr3 = np.linspace(-2, 2, 5)
  2913. out1 = np.ndarray(shape=(5,5))
  2914. out2 = np.ndarray(shape=(2, 5))
  2915. res1 = np.outer(arr1, arr3, out1)
  2916. assert_equal(res1, out1)
  2917. assert_equal(np.outer(arr2, arr3, out2), out2)
  2918. class TestIndices:
  2919. def test_simple(self):
  2920. [x, y] = np.indices((4, 3))
  2921. assert_array_equal(x, np.array([[0, 0, 0],
  2922. [1, 1, 1],
  2923. [2, 2, 2],
  2924. [3, 3, 3]]))
  2925. assert_array_equal(y, np.array([[0, 1, 2],
  2926. [0, 1, 2],
  2927. [0, 1, 2],
  2928. [0, 1, 2]]))
  2929. def test_single_input(self):
  2930. [x] = np.indices((4,))
  2931. assert_array_equal(x, np.array([0, 1, 2, 3]))
  2932. [x] = np.indices((4,), sparse=True)
  2933. assert_array_equal(x, np.array([0, 1, 2, 3]))
  2934. def test_scalar_input(self):
  2935. assert_array_equal([], np.indices(()))
  2936. assert_array_equal([], np.indices((), sparse=True))
  2937. assert_array_equal([[]], np.indices((0,)))
  2938. assert_array_equal([[]], np.indices((0,), sparse=True))
  2939. def test_sparse(self):
  2940. [x, y] = np.indices((4,3), sparse=True)
  2941. assert_array_equal(x, np.array([[0], [1], [2], [3]]))
  2942. assert_array_equal(y, np.array([[0, 1, 2]]))
  2943. @pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64])
  2944. @pytest.mark.parametrize("dims", [(), (0,), (4, 3)])
  2945. def test_return_type(self, dtype, dims):
  2946. inds = np.indices(dims, dtype=dtype)
  2947. assert_(inds.dtype == dtype)
  2948. for arr in np.indices(dims, dtype=dtype, sparse=True):
  2949. assert_(arr.dtype == dtype)
  2950. class TestRequire:
  2951. flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS',
  2952. 'F', 'F_CONTIGUOUS', 'FORTRAN',
  2953. 'A', 'ALIGNED',
  2954. 'W', 'WRITEABLE',
  2955. 'O', 'OWNDATA']
  2956. def generate_all_false(self, dtype):
  2957. arr = np.zeros((2, 2), [('junk', 'i1'), ('a', dtype)])
  2958. arr.setflags(write=False)
  2959. a = arr['a']
  2960. assert_(not a.flags['C'])
  2961. assert_(not a.flags['F'])
  2962. assert_(not a.flags['O'])
  2963. assert_(not a.flags['W'])
  2964. assert_(not a.flags['A'])
  2965. return a
  2966. def set_and_check_flag(self, flag, dtype, arr):
  2967. if dtype is None:
  2968. dtype = arr.dtype
  2969. b = np.require(arr, dtype, [flag])
  2970. assert_(b.flags[flag])
  2971. assert_(b.dtype == dtype)
  2972. # a further call to np.require ought to return the same array
  2973. # unless OWNDATA is specified.
  2974. c = np.require(b, None, [flag])
  2975. if flag[0] != 'O':
  2976. assert_(c is b)
  2977. else:
  2978. assert_(c.flags[flag])
  2979. def test_require_each(self):
  2980. id = ['f8', 'i4']
  2981. fd = [None, 'f8', 'c16']
  2982. for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names):
  2983. a = self.generate_all_false(idtype)
  2984. self.set_and_check_flag(flag, fdtype, a)
  2985. def test_unknown_requirement(self):
  2986. a = self.generate_all_false('f8')
  2987. assert_raises(KeyError, np.require, a, None, 'Q')
  2988. def test_non_array_input(self):
  2989. a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
  2990. assert_(a.flags['O'])
  2991. assert_(a.flags['C'])
  2992. assert_(a.flags['A'])
  2993. assert_(a.dtype == 'i4')
  2994. assert_equal(a, [1, 2, 3, 4])
  2995. def test_C_and_F_simul(self):
  2996. a = self.generate_all_false('f8')
  2997. assert_raises(ValueError, np.require, a, None, ['C', 'F'])
  2998. def test_ensure_array(self):
  2999. class ArraySubclass(np.ndarray):
  3000. pass
  3001. a = ArraySubclass((2, 2))
  3002. b = np.require(a, None, ['E'])
  3003. assert_(type(b) is np.ndarray)
  3004. def test_preserve_subtype(self):
  3005. class ArraySubclass(np.ndarray):
  3006. pass
  3007. for flag in self.flag_names:
  3008. a = ArraySubclass((2, 2))
  3009. self.set_and_check_flag(flag, None, a)
  3010. class TestBroadcast:
  3011. def test_broadcast_in_args(self):
  3012. # gh-5881
  3013. arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),
  3014. np.empty((5, 1, 7))]
  3015. mits = [np.broadcast(*arrs),
  3016. np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])),
  3017. np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])),
  3018. np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])),
  3019. np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])]
  3020. for mit in mits:
  3021. assert_equal(mit.shape, (5, 6, 7))
  3022. assert_equal(mit.ndim, 3)
  3023. assert_equal(mit.nd, 3)
  3024. assert_equal(mit.numiter, 4)
  3025. for a, ia in zip(arrs, mit.iters):
  3026. assert_(a is ia.base)
  3027. def test_broadcast_single_arg(self):
  3028. # gh-6899
  3029. arrs = [np.empty((5, 6, 7))]
  3030. mit = np.broadcast(*arrs)
  3031. assert_equal(mit.shape, (5, 6, 7))
  3032. assert_equal(mit.ndim, 3)
  3033. assert_equal(mit.nd, 3)
  3034. assert_equal(mit.numiter, 1)
  3035. assert_(arrs[0] is mit.iters[0].base)
  3036. def test_number_of_arguments(self):
  3037. arr = np.empty((5,))
  3038. for j in range(35):
  3039. arrs = [arr] * j
  3040. if j > 32:
  3041. assert_raises(ValueError, np.broadcast, *arrs)
  3042. else:
  3043. mit = np.broadcast(*arrs)
  3044. assert_equal(mit.numiter, j)
  3045. def test_broadcast_error_kwargs(self):
  3046. #gh-13455
  3047. arrs = [np.empty((5, 6, 7))]
  3048. mit = np.broadcast(*arrs)
  3049. mit2 = np.broadcast(*arrs, **{})
  3050. assert_equal(mit.shape, mit2.shape)
  3051. assert_equal(mit.ndim, mit2.ndim)
  3052. assert_equal(mit.nd, mit2.nd)
  3053. assert_equal(mit.numiter, mit2.numiter)
  3054. assert_(mit.iters[0].base is mit2.iters[0].base)
  3055. assert_raises(ValueError, np.broadcast, 1, **{'x': 1})
  3056. def test_shape_mismatch_error_message(self):
  3057. with pytest.raises(ValueError, match=r"arg 0 with shape \(1, 3\) and "
  3058. r"arg 2 with shape \(2,\)"):
  3059. np.broadcast([[1, 2, 3]], [[4], [5]], [6, 7])
  3060. class TestKeepdims:
  3061. class sub_array(np.ndarray):
  3062. def sum(self, axis=None, dtype=None, out=None):
  3063. return np.ndarray.sum(self, axis, dtype, out, keepdims=True)
  3064. def test_raise(self):
  3065. sub_class = self.sub_array
  3066. x = np.arange(30).view(sub_class)
  3067. assert_raises(TypeError, np.sum, x, keepdims=True)
  3068. class TestTensordot:
  3069. def test_zero_dimension(self):
  3070. # Test resolution to issue #5663
  3071. a = np.ndarray((3,0))
  3072. b = np.ndarray((0,4))
  3073. td = np.tensordot(a, b, (1, 0))
  3074. assert_array_equal(td, np.dot(a, b))
  3075. assert_array_equal(td, np.einsum('ij,jk', a, b))
  3076. def test_zero_dimensional(self):
  3077. # gh-12130
  3078. arr_0d = np.array(1)
  3079. ret = np.tensordot(arr_0d, arr_0d, ([], [])) # contracting no axes is well defined
  3080. assert_array_equal(ret, arr_0d)