test_umath.py 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473
  1. import platform
  2. import warnings
  3. import fnmatch
  4. import itertools
  5. import pytest
  6. import sys
  7. from fractions import Fraction
  8. import numpy.core.umath as ncu
  9. from numpy.core import _umath_tests as ncu_tests
  10. import numpy as np
  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_array_max_ulp, assert_allclose, assert_no_warnings, suppress_warnings,
  15. _gen_alignment_data, assert_array_almost_equal_nulp, assert_warns
  16. )
  17. def on_powerpc():
  18. """ True if we are running on a Power PC platform."""
  19. return platform.processor() == 'powerpc' or \
  20. platform.machine().startswith('ppc')
  21. def bad_arcsinh():
  22. """The blocklisted trig functions are not accurate on aarch64 for
  23. complex256. Rather than dig through the actual problem skip the
  24. test. This should be fixed when we can move past glibc2.17
  25. which is the version in manylinux2014
  26. """
  27. x = 1.78e-10
  28. v1 = np.arcsinh(np.float128(x))
  29. v2 = np.arcsinh(np.complex256(x)).real
  30. # The eps for float128 is 1-e33, so this is way bigger
  31. return abs((v1 / v2) - 1.0) > 1e-23
  32. if platform.machine() == 'aarch64' and bad_arcsinh():
  33. skip_longcomplex_msg = ('Trig functions of np.longcomplex values known to be '
  34. 'inaccurate on aarch64 for some compilation '
  35. 'configurations, should be fixed by building on a '
  36. 'platform using glibc>2.17')
  37. else:
  38. skip_longcomplex_msg = ''
  39. class _FilterInvalids:
  40. def setup(self):
  41. self.olderr = np.seterr(invalid='ignore')
  42. def teardown(self):
  43. np.seterr(**self.olderr)
  44. class TestConstants:
  45. def test_pi(self):
  46. assert_allclose(ncu.pi, 3.141592653589793, 1e-15)
  47. def test_e(self):
  48. assert_allclose(ncu.e, 2.718281828459045, 1e-15)
  49. def test_euler_gamma(self):
  50. assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15)
  51. class TestOut:
  52. def test_out_subok(self):
  53. for subok in (True, False):
  54. a = np.array(0.5)
  55. o = np.empty(())
  56. r = np.add(a, 2, o, subok=subok)
  57. assert_(r is o)
  58. r = np.add(a, 2, out=o, subok=subok)
  59. assert_(r is o)
  60. r = np.add(a, 2, out=(o,), subok=subok)
  61. assert_(r is o)
  62. d = np.array(5.7)
  63. o1 = np.empty(())
  64. o2 = np.empty((), dtype=np.int32)
  65. r1, r2 = np.frexp(d, o1, None, subok=subok)
  66. assert_(r1 is o1)
  67. r1, r2 = np.frexp(d, None, o2, subok=subok)
  68. assert_(r2 is o2)
  69. r1, r2 = np.frexp(d, o1, o2, subok=subok)
  70. assert_(r1 is o1)
  71. assert_(r2 is o2)
  72. r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
  73. assert_(r1 is o1)
  74. r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
  75. assert_(r2 is o2)
  76. r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
  77. assert_(r1 is o1)
  78. assert_(r2 is o2)
  79. with assert_raises(TypeError):
  80. # Out argument must be tuple, since there are multiple outputs.
  81. r1, r2 = np.frexp(d, out=o1, subok=subok)
  82. assert_raises(ValueError, np.add, a, 2, o, o, subok=subok)
  83. assert_raises(ValueError, np.add, a, 2, o, out=o, subok=subok)
  84. assert_raises(ValueError, np.add, a, 2, None, out=o, subok=subok)
  85. assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
  86. assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
  87. assert_raises(TypeError, np.add, a, 2, [], subok=subok)
  88. assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
  89. assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
  90. o.flags.writeable = False
  91. assert_raises(ValueError, np.add, a, 2, o, subok=subok)
  92. assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
  93. assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok)
  94. def test_out_wrap_subok(self):
  95. class ArrayWrap(np.ndarray):
  96. __array_priority__ = 10
  97. def __new__(cls, arr):
  98. return np.asarray(arr).view(cls).copy()
  99. def __array_wrap__(self, arr, context):
  100. return arr.view(type(self))
  101. for subok in (True, False):
  102. a = ArrayWrap([0.5])
  103. r = np.add(a, 2, subok=subok)
  104. if subok:
  105. assert_(isinstance(r, ArrayWrap))
  106. else:
  107. assert_(type(r) == np.ndarray)
  108. r = np.add(a, 2, None, subok=subok)
  109. if subok:
  110. assert_(isinstance(r, ArrayWrap))
  111. else:
  112. assert_(type(r) == np.ndarray)
  113. r = np.add(a, 2, out=None, subok=subok)
  114. if subok:
  115. assert_(isinstance(r, ArrayWrap))
  116. else:
  117. assert_(type(r) == np.ndarray)
  118. r = np.add(a, 2, out=(None,), subok=subok)
  119. if subok:
  120. assert_(isinstance(r, ArrayWrap))
  121. else:
  122. assert_(type(r) == np.ndarray)
  123. d = ArrayWrap([5.7])
  124. o1 = np.empty((1,))
  125. o2 = np.empty((1,), dtype=np.int32)
  126. r1, r2 = np.frexp(d, o1, subok=subok)
  127. if subok:
  128. assert_(isinstance(r2, ArrayWrap))
  129. else:
  130. assert_(type(r2) == np.ndarray)
  131. r1, r2 = np.frexp(d, o1, None, subok=subok)
  132. if subok:
  133. assert_(isinstance(r2, ArrayWrap))
  134. else:
  135. assert_(type(r2) == np.ndarray)
  136. r1, r2 = np.frexp(d, None, o2, subok=subok)
  137. if subok:
  138. assert_(isinstance(r1, ArrayWrap))
  139. else:
  140. assert_(type(r1) == np.ndarray)
  141. r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
  142. if subok:
  143. assert_(isinstance(r2, ArrayWrap))
  144. else:
  145. assert_(type(r2) == np.ndarray)
  146. r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
  147. if subok:
  148. assert_(isinstance(r1, ArrayWrap))
  149. else:
  150. assert_(type(r1) == np.ndarray)
  151. with assert_raises(TypeError):
  152. # Out argument must be tuple, since there are multiple outputs.
  153. r1, r2 = np.frexp(d, out=o1, subok=subok)
  154. class TestComparisons:
  155. def test_ignore_object_identity_in_equal(self):
  156. # Check comparing identical objects whose comparison
  157. # is not a simple boolean, e.g., arrays that are compared elementwise.
  158. a = np.array([np.array([1, 2, 3]), None], dtype=object)
  159. assert_raises(ValueError, np.equal, a, a)
  160. # Check error raised when comparing identical non-comparable objects.
  161. class FunkyType:
  162. def __eq__(self, other):
  163. raise TypeError("I won't compare")
  164. a = np.array([FunkyType()])
  165. assert_raises(TypeError, np.equal, a, a)
  166. # Check identity doesn't override comparison mismatch.
  167. a = np.array([np.nan], dtype=object)
  168. assert_equal(np.equal(a, a), [False])
  169. def test_ignore_object_identity_in_not_equal(self):
  170. # Check comparing identical objects whose comparison
  171. # is not a simple boolean, e.g., arrays that are compared elementwise.
  172. a = np.array([np.array([1, 2, 3]), None], dtype=object)
  173. assert_raises(ValueError, np.not_equal, a, a)
  174. # Check error raised when comparing identical non-comparable objects.
  175. class FunkyType:
  176. def __ne__(self, other):
  177. raise TypeError("I won't compare")
  178. a = np.array([FunkyType()])
  179. assert_raises(TypeError, np.not_equal, a, a)
  180. # Check identity doesn't override comparison mismatch.
  181. a = np.array([np.nan], dtype=object)
  182. assert_equal(np.not_equal(a, a), [True])
  183. class TestAdd:
  184. def test_reduce_alignment(self):
  185. # gh-9876
  186. # make sure arrays with weird strides work with the optimizations in
  187. # pairwise_sum_@TYPE@. On x86, the 'b' field will count as aligned at a
  188. # 4 byte offset, even though its itemsize is 8.
  189. a = np.zeros(2, dtype=[('a', np.int32), ('b', np.float64)])
  190. a['a'] = -1
  191. assert_equal(a['b'].sum(), 0)
  192. class TestDivision:
  193. def test_division_int(self):
  194. # int division should follow Python
  195. x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120])
  196. if 5 / 10 == 0.5:
  197. assert_equal(x / 100, [0.05, 0.1, 0.9, 1,
  198. -0.05, -0.1, -0.9, -1, -1.2])
  199. else:
  200. assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
  201. assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
  202. assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80])
  203. def test_division_complex(self):
  204. # check that implementation is correct
  205. msg = "Complex division implementation check"
  206. x = np.array([1. + 1.*1j, 1. + .5*1j, 1. + 2.*1j], dtype=np.complex128)
  207. assert_almost_equal(x**2/x, x, err_msg=msg)
  208. # check overflow, underflow
  209. msg = "Complex division overflow/underflow check"
  210. x = np.array([1.e+110, 1.e-110], dtype=np.complex128)
  211. y = x**2/x
  212. assert_almost_equal(y/x, [1, 1], err_msg=msg)
  213. def test_zero_division_complex(self):
  214. with np.errstate(invalid="ignore", divide="ignore"):
  215. x = np.array([0.0], dtype=np.complex128)
  216. y = 1.0/x
  217. assert_(np.isinf(y)[0])
  218. y = complex(np.inf, np.nan)/x
  219. assert_(np.isinf(y)[0])
  220. y = complex(np.nan, np.inf)/x
  221. assert_(np.isinf(y)[0])
  222. y = complex(np.inf, np.inf)/x
  223. assert_(np.isinf(y)[0])
  224. y = 0.0/x
  225. assert_(np.isnan(y)[0])
  226. def test_floor_division_complex(self):
  227. # check that implementation is correct
  228. msg = "Complex floor division implementation check"
  229. x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128)
  230. y = np.array([0., -1., 0., 0.], dtype=np.complex128)
  231. assert_equal(np.floor_divide(x**2, x), y, err_msg=msg)
  232. # check overflow, underflow
  233. msg = "Complex floor division overflow/underflow check"
  234. x = np.array([1.e+110, 1.e-110], dtype=np.complex128)
  235. y = np.floor_divide(x**2, x)
  236. assert_equal(y, [1.e+110, 0], err_msg=msg)
  237. def test_floor_division_signed_zero(self):
  238. # Check that the sign bit is correctly set when dividing positive and
  239. # negative zero by one.
  240. x = np.zeros(10)
  241. assert_equal(np.signbit(x//1), 0)
  242. assert_equal(np.signbit((-x)//1), 1)
  243. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  244. def test_floor_division_errors(self, dtype):
  245. fnan = np.array(np.nan, dtype=dtype)
  246. fone = np.array(1.0, dtype=dtype)
  247. fzer = np.array(0.0, dtype=dtype)
  248. finf = np.array(np.inf, dtype=dtype)
  249. # divide by zero error check
  250. with np.errstate(divide='raise', invalid='ignore'):
  251. assert_raises(FloatingPointError, np.floor_divide, fone, fzer)
  252. with np.errstate(invalid='raise'):
  253. assert_raises(FloatingPointError, np.floor_divide, fnan, fone)
  254. assert_raises(FloatingPointError, np.floor_divide, fone, fnan)
  255. assert_raises(FloatingPointError, np.floor_divide, fnan, fzer)
  256. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  257. def test_floor_division_corner_cases(self, dtype):
  258. # test corner cases like 1.0//0.0 for errors and return vals
  259. x = np.zeros(10, dtype=dtype)
  260. y = np.ones(10, dtype=dtype)
  261. fnan = np.array(np.nan, dtype=dtype)
  262. fone = np.array(1.0, dtype=dtype)
  263. fzer = np.array(0.0, dtype=dtype)
  264. finf = np.array(np.inf, dtype=dtype)
  265. with suppress_warnings() as sup:
  266. sup.filter(RuntimeWarning, "invalid value encountered in floor_divide")
  267. div = np.floor_divide(fnan, fone)
  268. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  269. div = np.floor_divide(fone, fnan)
  270. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  271. div = np.floor_divide(fnan, fzer)
  272. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  273. # verify 1.0//0.0 computations return inf
  274. with np.errstate(divide='ignore'):
  275. z = np.floor_divide(y, x)
  276. assert_(np.isinf(z).all())
  277. def floor_divide_and_remainder(x, y):
  278. return (np.floor_divide(x, y), np.remainder(x, y))
  279. def _signs(dt):
  280. if dt in np.typecodes['UnsignedInteger']:
  281. return (+1,)
  282. else:
  283. return (+1, -1)
  284. class TestRemainder:
  285. def test_remainder_basic(self):
  286. dt = np.typecodes['AllInteger'] + np.typecodes['Float']
  287. for op in [floor_divide_and_remainder, np.divmod]:
  288. for dt1, dt2 in itertools.product(dt, dt):
  289. for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
  290. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  291. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  292. a = np.array(sg1*71, dtype=dt1)
  293. b = np.array(sg2*19, dtype=dt2)
  294. div, rem = op(a, b)
  295. assert_equal(div*b + rem, a, err_msg=msg)
  296. if sg2 == -1:
  297. assert_(b < rem <= 0, msg)
  298. else:
  299. assert_(b > rem >= 0, msg)
  300. def test_float_remainder_exact(self):
  301. # test that float results are exact for small integers. This also
  302. # holds for the same integers scaled by powers of two.
  303. nlst = list(range(-127, 0))
  304. plst = list(range(1, 128))
  305. dividend = nlst + [0] + plst
  306. divisor = nlst + plst
  307. arg = list(itertools.product(dividend, divisor))
  308. tgt = list(divmod(*t) for t in arg)
  309. a, b = np.array(arg, dtype=int).T
  310. # convert exact integer results from Python to float so that
  311. # signed zero can be used, it is checked.
  312. tgtdiv, tgtrem = np.array(tgt, dtype=float).T
  313. tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
  314. tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
  315. for op in [floor_divide_and_remainder, np.divmod]:
  316. for dt in np.typecodes['Float']:
  317. msg = 'op: %s, dtype: %s' % (op.__name__, dt)
  318. fa = a.astype(dt)
  319. fb = b.astype(dt)
  320. div, rem = op(fa, fb)
  321. assert_equal(div, tgtdiv, err_msg=msg)
  322. assert_equal(rem, tgtrem, err_msg=msg)
  323. def test_float_remainder_roundoff(self):
  324. # gh-6127
  325. dt = np.typecodes['Float']
  326. for op in [floor_divide_and_remainder, np.divmod]:
  327. for dt1, dt2 in itertools.product(dt, dt):
  328. for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
  329. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  330. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  331. a = np.array(sg1*78*6e-8, dtype=dt1)
  332. b = np.array(sg2*6e-8, dtype=dt2)
  333. div, rem = op(a, b)
  334. # Equal assertion should hold when fmod is used
  335. assert_equal(div*b + rem, a, err_msg=msg)
  336. if sg2 == -1:
  337. assert_(b < rem <= 0, msg)
  338. else:
  339. assert_(b > rem >= 0, msg)
  340. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  341. def test_float_divmod_errors(self, dtype):
  342. # Check valid errors raised for divmod and remainder
  343. fzero = np.array(0.0, dtype=dtype)
  344. fone = np.array(1.0, dtype=dtype)
  345. finf = np.array(np.inf, dtype=dtype)
  346. fnan = np.array(np.nan, dtype=dtype)
  347. # since divmod is combination of both remainder and divide
  348. # ops it will set both dividebyzero and invalid flags
  349. with np.errstate(divide='raise', invalid='ignore'):
  350. assert_raises(FloatingPointError, np.divmod, fone, fzero)
  351. with np.errstate(divide='ignore', invalid='raise'):
  352. assert_raises(FloatingPointError, np.divmod, fone, fzero)
  353. with np.errstate(invalid='raise'):
  354. assert_raises(FloatingPointError, np.divmod, fzero, fzero)
  355. with np.errstate(invalid='raise'):
  356. assert_raises(FloatingPointError, np.divmod, finf, finf)
  357. with np.errstate(divide='ignore', invalid='raise'):
  358. assert_raises(FloatingPointError, np.divmod, finf, fzero)
  359. with np.errstate(divide='raise', invalid='ignore'):
  360. assert_raises(FloatingPointError, np.divmod, finf, fzero)
  361. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  362. @pytest.mark.parametrize('fn', [np.fmod, np.remainder])
  363. def test_float_remainder_errors(self, dtype, fn):
  364. fzero = np.array(0.0, dtype=dtype)
  365. fone = np.array(1.0, dtype=dtype)
  366. finf = np.array(np.inf, dtype=dtype)
  367. fnan = np.array(np.nan, dtype=dtype)
  368. with np.errstate(invalid='raise'):
  369. assert_raises(FloatingPointError, fn, fone, fzero)
  370. assert_raises(FloatingPointError, fn, fnan, fzero)
  371. assert_raises(FloatingPointError, fn, fone, fnan)
  372. assert_raises(FloatingPointError, fn, fnan, fone)
  373. def test_float_remainder_overflow(self):
  374. a = np.finfo(np.float64).tiny
  375. with np.errstate(over='ignore', invalid='ignore'):
  376. div, mod = np.divmod(4, a)
  377. np.isinf(div)
  378. assert_(mod == 0)
  379. with np.errstate(over='raise', invalid='ignore'):
  380. assert_raises(FloatingPointError, np.divmod, 4, a)
  381. with np.errstate(invalid='raise', over='ignore'):
  382. assert_raises(FloatingPointError, np.divmod, 4, a)
  383. def test_float_divmod_corner_cases(self):
  384. # check nan cases
  385. for dt in np.typecodes['Float']:
  386. fnan = np.array(np.nan, dtype=dt)
  387. fone = np.array(1.0, dtype=dt)
  388. fzer = np.array(0.0, dtype=dt)
  389. finf = np.array(np.inf, dtype=dt)
  390. with suppress_warnings() as sup:
  391. sup.filter(RuntimeWarning, "invalid value encountered in divmod")
  392. sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
  393. div, rem = np.divmod(fone, fzer)
  394. assert(np.isinf(div)), 'dt: %s, div: %s' % (dt, rem)
  395. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  396. div, rem = np.divmod(fzer, fzer)
  397. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  398. assert_(np.isnan(div)), 'dt: %s, rem: %s' % (dt, rem)
  399. div, rem = np.divmod(finf, finf)
  400. assert(np.isnan(div)), 'dt: %s, rem: %s' % (dt, rem)
  401. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  402. div, rem = np.divmod(finf, fzer)
  403. assert(np.isinf(div)), 'dt: %s, rem: %s' % (dt, rem)
  404. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  405. div, rem = np.divmod(fnan, fone)
  406. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  407. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  408. div, rem = np.divmod(fone, fnan)
  409. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  410. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  411. div, rem = np.divmod(fnan, fzer)
  412. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  413. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  414. def test_float_remainder_corner_cases(self):
  415. # Check remainder magnitude.
  416. for dt in np.typecodes['Float']:
  417. fone = np.array(1.0, dtype=dt)
  418. fzer = np.array(0.0, dtype=dt)
  419. fnan = np.array(np.nan, dtype=dt)
  420. b = np.array(1.0, dtype=dt)
  421. a = np.nextafter(np.array(0.0, dtype=dt), -b)
  422. rem = np.remainder(a, b)
  423. assert_(rem <= b, 'dt: %s' % dt)
  424. rem = np.remainder(-a, -b)
  425. assert_(rem >= -b, 'dt: %s' % dt)
  426. # Check nans, inf
  427. with suppress_warnings() as sup:
  428. sup.filter(RuntimeWarning, "invalid value encountered in remainder")
  429. sup.filter(RuntimeWarning, "invalid value encountered in fmod")
  430. for dt in np.typecodes['Float']:
  431. fone = np.array(1.0, dtype=dt)
  432. fzer = np.array(0.0, dtype=dt)
  433. finf = np.array(np.inf, dtype=dt)
  434. fnan = np.array(np.nan, dtype=dt)
  435. rem = np.remainder(fone, fzer)
  436. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  437. # MSVC 2008 returns NaN here, so disable the check.
  438. #rem = np.remainder(fone, finf)
  439. #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
  440. rem = np.remainder(finf, fone)
  441. fmod = np.fmod(finf, fone)
  442. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  443. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  444. rem = np.remainder(finf, finf)
  445. fmod = np.fmod(finf, fone)
  446. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  447. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  448. rem = np.remainder(finf, fzer)
  449. fmod = np.fmod(finf, fzer)
  450. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  451. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  452. rem = np.remainder(fone, fnan)
  453. fmod = np.fmod(fone, fnan)
  454. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  455. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  456. rem = np.remainder(fnan, fzer)
  457. fmod = np.fmod(fnan, fzer)
  458. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  459. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
  460. rem = np.remainder(fnan, fone)
  461. fmod = np.fmod(fnan, fone)
  462. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  463. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
  464. class TestCbrt:
  465. def test_cbrt_scalar(self):
  466. assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5)
  467. def test_cbrt(self):
  468. x = np.array([1., 2., -3., np.inf, -np.inf])
  469. assert_almost_equal(np.cbrt(x**3), x)
  470. assert_(np.isnan(np.cbrt(np.nan)))
  471. assert_equal(np.cbrt(np.inf), np.inf)
  472. assert_equal(np.cbrt(-np.inf), -np.inf)
  473. class TestPower:
  474. def test_power_float(self):
  475. x = np.array([1., 2., 3.])
  476. assert_equal(x**0, [1., 1., 1.])
  477. assert_equal(x**1, x)
  478. assert_equal(x**2, [1., 4., 9.])
  479. y = x.copy()
  480. y **= 2
  481. assert_equal(y, [1., 4., 9.])
  482. assert_almost_equal(x**(-1), [1., 0.5, 1./3])
  483. assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
  484. for out, inp, msg in _gen_alignment_data(dtype=np.float32,
  485. type='unary',
  486. max_size=11):
  487. exp = [ncu.sqrt(i) for i in inp]
  488. assert_almost_equal(inp**(0.5), exp, err_msg=msg)
  489. np.sqrt(inp, out=out)
  490. assert_equal(out, exp, err_msg=msg)
  491. for out, inp, msg in _gen_alignment_data(dtype=np.float64,
  492. type='unary',
  493. max_size=7):
  494. exp = [ncu.sqrt(i) for i in inp]
  495. assert_almost_equal(inp**(0.5), exp, err_msg=msg)
  496. np.sqrt(inp, out=out)
  497. assert_equal(out, exp, err_msg=msg)
  498. def test_power_complex(self):
  499. x = np.array([1+2j, 2+3j, 3+4j])
  500. assert_equal(x**0, [1., 1., 1.])
  501. assert_equal(x**1, x)
  502. assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j])
  503. assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])
  504. assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])
  505. assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)])
  506. assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2])
  507. assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197,
  508. (-117-44j)/15625])
  509. assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j),
  510. ncu.sqrt(3+4j)])
  511. norm = 1./((x**14)[0])
  512. assert_almost_equal(x**14 * norm,
  513. [i * norm for i in [-76443+16124j, 23161315+58317492j,
  514. 5583548873 + 2465133864j]])
  515. # Ticket #836
  516. def assert_complex_equal(x, y):
  517. assert_array_equal(x.real, y.real)
  518. assert_array_equal(x.imag, y.imag)
  519. for z in [complex(0, np.inf), complex(1, np.inf)]:
  520. z = np.array([z], dtype=np.complex_)
  521. with np.errstate(invalid="ignore"):
  522. assert_complex_equal(z**1, z)
  523. assert_complex_equal(z**2, z*z)
  524. assert_complex_equal(z**3, z*z*z)
  525. def test_power_zero(self):
  526. # ticket #1271
  527. zero = np.array([0j])
  528. one = np.array([1+0j])
  529. cnan = np.array([complex(np.nan, np.nan)])
  530. # FIXME cinf not tested.
  531. #cinf = np.array([complex(np.inf, 0)])
  532. def assert_complex_equal(x, y):
  533. x, y = np.asarray(x), np.asarray(y)
  534. assert_array_equal(x.real, y.real)
  535. assert_array_equal(x.imag, y.imag)
  536. # positive powers
  537. for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
  538. assert_complex_equal(np.power(zero, p), zero)
  539. # zero power
  540. assert_complex_equal(np.power(zero, 0), one)
  541. with np.errstate(invalid="ignore"):
  542. assert_complex_equal(np.power(zero, 0+1j), cnan)
  543. # negative power
  544. for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
  545. assert_complex_equal(np.power(zero, -p), cnan)
  546. assert_complex_equal(np.power(zero, -1+0.2j), cnan)
  547. def test_fast_power(self):
  548. x = np.array([1, 2, 3], np.int16)
  549. res = x**2.0
  550. assert_((x**2.00001).dtype is res.dtype)
  551. assert_array_equal(res, [1, 4, 9])
  552. # check the inplace operation on the casted copy doesn't mess with x
  553. assert_(not np.may_share_memory(res, x))
  554. assert_array_equal(x, [1, 2, 3])
  555. # Check that the fast path ignores 1-element not 0-d arrays
  556. res = x ** np.array([[[2]]])
  557. assert_equal(res.shape, (1, 1, 3))
  558. def test_integer_power(self):
  559. a = np.array([15, 15], 'i8')
  560. b = np.power(a, a)
  561. assert_equal(b, [437893890380859375, 437893890380859375])
  562. def test_integer_power_with_integer_zero_exponent(self):
  563. dtypes = np.typecodes['Integer']
  564. for dt in dtypes:
  565. arr = np.arange(-10, 10, dtype=dt)
  566. assert_equal(np.power(arr, 0), np.ones_like(arr))
  567. dtypes = np.typecodes['UnsignedInteger']
  568. for dt in dtypes:
  569. arr = np.arange(10, dtype=dt)
  570. assert_equal(np.power(arr, 0), np.ones_like(arr))
  571. def test_integer_power_of_1(self):
  572. dtypes = np.typecodes['AllInteger']
  573. for dt in dtypes:
  574. arr = np.arange(10, dtype=dt)
  575. assert_equal(np.power(1, arr), np.ones_like(arr))
  576. def test_integer_power_of_zero(self):
  577. dtypes = np.typecodes['AllInteger']
  578. for dt in dtypes:
  579. arr = np.arange(1, 10, dtype=dt)
  580. assert_equal(np.power(0, arr), np.zeros_like(arr))
  581. def test_integer_to_negative_power(self):
  582. dtypes = np.typecodes['Integer']
  583. for dt in dtypes:
  584. a = np.array([0, 1, 2, 3], dtype=dt)
  585. b = np.array([0, 1, 2, -3], dtype=dt)
  586. one = np.array(1, dtype=dt)
  587. minusone = np.array(-1, dtype=dt)
  588. assert_raises(ValueError, np.power, a, b)
  589. assert_raises(ValueError, np.power, a, minusone)
  590. assert_raises(ValueError, np.power, one, b)
  591. assert_raises(ValueError, np.power, one, minusone)
  592. class TestFloat_power:
  593. def test_type_conversion(self):
  594. arg_type = '?bhilBHILefdgFDG'
  595. res_type = 'ddddddddddddgDDG'
  596. for dtin, dtout in zip(arg_type, res_type):
  597. msg = "dtin: %s, dtout: %s" % (dtin, dtout)
  598. arg = np.ones(1, dtype=dtin)
  599. res = np.float_power(arg, arg)
  600. assert_(res.dtype.name == np.dtype(dtout).name, msg)
  601. class TestLog2:
  602. def test_log2_values(self):
  603. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  604. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  605. for dt in ['f', 'd', 'g']:
  606. xf = np.array(x, dtype=dt)
  607. yf = np.array(y, dtype=dt)
  608. assert_almost_equal(np.log2(xf), yf)
  609. def test_log2_ints(self):
  610. # a good log2 implementation should provide this,
  611. # might fail on OS with bad libm
  612. for i in range(1, 65):
  613. v = np.log2(2.**i)
  614. assert_equal(v, float(i), err_msg='at exponent %d' % i)
  615. def test_log2_special(self):
  616. assert_equal(np.log2(1.), 0.)
  617. assert_equal(np.log2(np.inf), np.inf)
  618. assert_(np.isnan(np.log2(np.nan)))
  619. with warnings.catch_warnings(record=True) as w:
  620. warnings.filterwarnings('always', '', RuntimeWarning)
  621. assert_(np.isnan(np.log2(-1.)))
  622. assert_(np.isnan(np.log2(-np.inf)))
  623. assert_equal(np.log2(0.), -np.inf)
  624. assert_(w[0].category is RuntimeWarning)
  625. assert_(w[1].category is RuntimeWarning)
  626. assert_(w[2].category is RuntimeWarning)
  627. class TestExp2:
  628. def test_exp2_values(self):
  629. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  630. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  631. for dt in ['f', 'd', 'g']:
  632. xf = np.array(x, dtype=dt)
  633. yf = np.array(y, dtype=dt)
  634. assert_almost_equal(np.exp2(yf), xf)
  635. class TestLogAddExp2(_FilterInvalids):
  636. # Need test for intermediate precisions
  637. def test_logaddexp2_values(self):
  638. x = [1, 2, 3, 4, 5]
  639. y = [5, 4, 3, 2, 1]
  640. z = [6, 6, 6, 6, 6]
  641. for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
  642. xf = np.log2(np.array(x, dtype=dt))
  643. yf = np.log2(np.array(y, dtype=dt))
  644. zf = np.log2(np.array(z, dtype=dt))
  645. assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec_)
  646. def test_logaddexp2_range(self):
  647. x = [1000000, -1000000, 1000200, -1000200]
  648. y = [1000200, -1000200, 1000000, -1000000]
  649. z = [1000200, -1000000, 1000200, -1000000]
  650. for dt in ['f', 'd', 'g']:
  651. logxf = np.array(x, dtype=dt)
  652. logyf = np.array(y, dtype=dt)
  653. logzf = np.array(z, dtype=dt)
  654. assert_almost_equal(np.logaddexp2(logxf, logyf), logzf)
  655. def test_inf(self):
  656. inf = np.inf
  657. x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
  658. y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
  659. z = [inf, inf, inf, -inf, inf, inf, 1, 1]
  660. with np.errstate(invalid='raise'):
  661. for dt in ['f', 'd', 'g']:
  662. logxf = np.array(x, dtype=dt)
  663. logyf = np.array(y, dtype=dt)
  664. logzf = np.array(z, dtype=dt)
  665. assert_equal(np.logaddexp2(logxf, logyf), logzf)
  666. def test_nan(self):
  667. assert_(np.isnan(np.logaddexp2(np.nan, np.inf)))
  668. assert_(np.isnan(np.logaddexp2(np.inf, np.nan)))
  669. assert_(np.isnan(np.logaddexp2(np.nan, 0)))
  670. assert_(np.isnan(np.logaddexp2(0, np.nan)))
  671. assert_(np.isnan(np.logaddexp2(np.nan, np.nan)))
  672. def test_reduce(self):
  673. assert_equal(np.logaddexp2.identity, -np.inf)
  674. assert_equal(np.logaddexp2.reduce([]), -np.inf)
  675. assert_equal(np.logaddexp2.reduce([-np.inf]), -np.inf)
  676. assert_equal(np.logaddexp2.reduce([-np.inf, 0]), 0)
  677. class TestLog:
  678. def test_log_values(self):
  679. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  680. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  681. for dt in ['f', 'd', 'g']:
  682. log2_ = 0.69314718055994530943
  683. xf = np.array(x, dtype=dt)
  684. yf = np.array(y, dtype=dt)*log2_
  685. assert_almost_equal(np.log(xf), yf)
  686. # test aliasing(issue #17761)
  687. x = np.array([2, 0.937500, 3, 0.947500, 1.054697])
  688. xf = np.log(x)
  689. assert_almost_equal(np.log(x, out=x), xf)
  690. def test_log_strides(self):
  691. np.random.seed(42)
  692. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  693. sizes = np.arange(2,100)
  694. for ii in sizes:
  695. x_f64 = np.float64(np.random.uniform(low=0.01, high=100.0,size=ii))
  696. x_special = x_f64.copy()
  697. x_special[3:-1:4] = 1.0
  698. y_true = np.log(x_f64)
  699. y_special = np.log(x_special)
  700. for jj in strides:
  701. assert_array_almost_equal_nulp(np.log(x_f64[::jj]), y_true[::jj], nulp=2)
  702. assert_array_almost_equal_nulp(np.log(x_special[::jj]), y_special[::jj], nulp=2)
  703. class TestExp:
  704. def test_exp_values(self):
  705. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  706. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  707. for dt in ['f', 'd', 'g']:
  708. log2_ = 0.69314718055994530943
  709. xf = np.array(x, dtype=dt)
  710. yf = np.array(y, dtype=dt)*log2_
  711. assert_almost_equal(np.exp(yf), xf)
  712. def test_exp_strides(self):
  713. np.random.seed(42)
  714. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  715. sizes = np.arange(2,100)
  716. for ii in sizes:
  717. x_f64 = np.float64(np.random.uniform(low=0.01, high=709.1,size=ii))
  718. y_true = np.exp(x_f64)
  719. for jj in strides:
  720. assert_array_almost_equal_nulp(np.exp(x_f64[::jj]), y_true[::jj], nulp=2)
  721. class TestSpecialFloats:
  722. def test_exp_values(self):
  723. x = [np.nan, np.nan, np.inf, 0.]
  724. y = [np.nan, -np.nan, np.inf, -np.inf]
  725. for dt in ['f', 'd', 'g']:
  726. xf = np.array(x, dtype=dt)
  727. yf = np.array(y, dtype=dt)
  728. assert_equal(np.exp(yf), xf)
  729. with np.errstate(over='raise'):
  730. assert_raises(FloatingPointError, np.exp, np.float32(100.))
  731. assert_raises(FloatingPointError, np.exp, np.float32(1E19))
  732. assert_raises(FloatingPointError, np.exp, np.float64(800.))
  733. assert_raises(FloatingPointError, np.exp, np.float64(1E19))
  734. def test_log_values(self):
  735. with np.errstate(all='ignore'):
  736. x = [np.nan, np.nan, np.inf, np.nan, -np.inf, np.nan]
  737. y = [np.nan, -np.nan, np.inf, -np.inf, 0., -1.0]
  738. for dt in ['f', 'd', 'g']:
  739. xf = np.array(x, dtype=dt)
  740. yf = np.array(y, dtype=dt)
  741. assert_equal(np.log(yf), xf)
  742. with np.errstate(divide='raise'):
  743. assert_raises(FloatingPointError, np.log, np.float32(0.))
  744. with np.errstate(invalid='raise'):
  745. assert_raises(FloatingPointError, np.log, np.float32(-np.inf))
  746. assert_raises(FloatingPointError, np.log, np.float32(-1.0))
  747. # See https://github.com/numpy/numpy/issues/18005
  748. with assert_no_warnings():
  749. a = np.array(1e9, dtype='float32')
  750. np.log(a)
  751. def test_sincos_values(self):
  752. with np.errstate(all='ignore'):
  753. x = [np.nan, np.nan, np.nan, np.nan]
  754. y = [np.nan, -np.nan, np.inf, -np.inf]
  755. for dt in ['f', 'd', 'g']:
  756. xf = np.array(x, dtype=dt)
  757. yf = np.array(y, dtype=dt)
  758. assert_equal(np.sin(yf), xf)
  759. assert_equal(np.cos(yf), xf)
  760. with np.errstate(invalid='raise'):
  761. assert_raises(FloatingPointError, np.sin, np.float32(-np.inf))
  762. assert_raises(FloatingPointError, np.sin, np.float32(np.inf))
  763. assert_raises(FloatingPointError, np.cos, np.float32(-np.inf))
  764. assert_raises(FloatingPointError, np.cos, np.float32(np.inf))
  765. def test_sqrt_values(self):
  766. with np.errstate(all='ignore'):
  767. x = [np.nan, np.nan, np.inf, np.nan, 0.]
  768. y = [np.nan, -np.nan, np.inf, -np.inf, 0.]
  769. for dt in ['f', 'd', 'g']:
  770. xf = np.array(x, dtype=dt)
  771. yf = np.array(y, dtype=dt)
  772. assert_equal(np.sqrt(yf), xf)
  773. #with np.errstate(invalid='raise'):
  774. # for dt in ['f', 'd', 'g']:
  775. # assert_raises(FloatingPointError, np.sqrt, np.array(-100., dtype=dt))
  776. def test_abs_values(self):
  777. x = [np.nan, np.nan, np.inf, np.inf, 0., 0., 1.0, 1.0]
  778. y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0., -1.0, 1.0]
  779. for dt in ['f', 'd', 'g']:
  780. xf = np.array(x, dtype=dt)
  781. yf = np.array(y, dtype=dt)
  782. assert_equal(np.abs(yf), xf)
  783. def test_square_values(self):
  784. x = [np.nan, np.nan, np.inf, np.inf]
  785. y = [np.nan, -np.nan, np.inf, -np.inf]
  786. with np.errstate(all='ignore'):
  787. for dt in ['f', 'd', 'g']:
  788. xf = np.array(x, dtype=dt)
  789. yf = np.array(y, dtype=dt)
  790. assert_equal(np.square(yf), xf)
  791. with np.errstate(over='raise'):
  792. assert_raises(FloatingPointError, np.square, np.array(1E32, dtype='f'))
  793. assert_raises(FloatingPointError, np.square, np.array(1E200, dtype='d'))
  794. def test_reciprocal_values(self):
  795. with np.errstate(all='ignore'):
  796. x = [np.nan, np.nan, 0.0, -0.0, np.inf, -np.inf]
  797. y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0.]
  798. for dt in ['f', 'd', 'g']:
  799. xf = np.array(x, dtype=dt)
  800. yf = np.array(y, dtype=dt)
  801. assert_equal(np.reciprocal(yf), xf)
  802. with np.errstate(divide='raise'):
  803. for dt in ['f', 'd', 'g']:
  804. assert_raises(FloatingPointError, np.reciprocal, np.array(-0.0, dtype=dt))
  805. class TestFPClass:
  806. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  807. def test_fpclass(self, stride):
  808. arr_f64 = np.array([np.nan, -np.nan, np.inf, -np.inf, -1.0, 1.0, -0.0, 0.0, 2.2251e-308, -2.2251e-308], dtype='d')
  809. arr_f32 = np.array([np.nan, -np.nan, np.inf, -np.inf, -1.0, 1.0, -0.0, 0.0, 1.4013e-045, -1.4013e-045], dtype='f')
  810. nan = np.array([True, True, False, False, False, False, False, False, False, False])
  811. inf = np.array([False, False, True, True, False, False, False, False, False, False])
  812. sign = np.array([False, True, False, True, True, False, True, False, False, True])
  813. finite = np.array([False, False, False, False, True, True, True, True, True, True])
  814. assert_equal(np.isnan(arr_f32[::stride]), nan[::stride])
  815. assert_equal(np.isnan(arr_f64[::stride]), nan[::stride])
  816. assert_equal(np.isinf(arr_f32[::stride]), inf[::stride])
  817. assert_equal(np.isinf(arr_f64[::stride]), inf[::stride])
  818. assert_equal(np.signbit(arr_f32[::stride]), sign[::stride])
  819. assert_equal(np.signbit(arr_f64[::stride]), sign[::stride])
  820. assert_equal(np.isfinite(arr_f32[::stride]), finite[::stride])
  821. assert_equal(np.isfinite(arr_f64[::stride]), finite[::stride])
  822. class TestLDExp:
  823. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  824. @pytest.mark.parametrize("dtype", ['f', 'd'])
  825. def test_ldexp(self, dtype, stride):
  826. mant = np.array([0.125, 0.25, 0.5, 1., 1., 2., 4., 8.], dtype=dtype)
  827. exp = np.array([3, 2, 1, 0, 0, -1, -2, -3], dtype='i')
  828. out = np.zeros(8, dtype=dtype)
  829. assert_equal(np.ldexp(mant[::stride], exp[::stride], out=out[::stride]), np.ones(8, dtype=dtype)[::stride])
  830. assert_equal(out[::stride], np.ones(8, dtype=dtype)[::stride])
  831. class TestFRExp:
  832. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  833. @pytest.mark.parametrize("dtype", ['f', 'd'])
  834. @pytest.mark.skipif(not sys.platform.startswith('linux'),
  835. reason="np.frexp gives different answers for NAN/INF on windows and linux")
  836. def test_frexp(self, dtype, stride):
  837. arr = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 1.0, -1.0], dtype=dtype)
  838. mant_true = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 0.5, -0.5], dtype=dtype)
  839. exp_true = np.array([0, 0, 0, 0, 0, 0, 1, 1], dtype='i')
  840. out_mant = np.ones(8, dtype=dtype)
  841. out_exp = 2*np.ones(8, dtype='i')
  842. mant, exp = np.frexp(arr[::stride], out=(out_mant[::stride], out_exp[::stride]))
  843. assert_equal(mant_true[::stride], mant)
  844. assert_equal(exp_true[::stride], exp)
  845. assert_equal(out_mant[::stride], mant_true[::stride])
  846. assert_equal(out_exp[::stride], exp_true[::stride])
  847. # func : [maxulperror, low, high]
  848. avx_ufuncs = {'sqrt' :[1, 0., 100.],
  849. 'absolute' :[0, -100., 100.],
  850. 'reciprocal' :[1, 1., 100.],
  851. 'square' :[1, -100., 100.],
  852. 'rint' :[0, -100., 100.],
  853. 'floor' :[0, -100., 100.],
  854. 'ceil' :[0, -100., 100.],
  855. 'trunc' :[0, -100., 100.]}
  856. class TestAVXUfuncs:
  857. def test_avx_based_ufunc(self):
  858. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  859. np.random.seed(42)
  860. for func, prop in avx_ufuncs.items():
  861. maxulperr = prop[0]
  862. minval = prop[1]
  863. maxval = prop[2]
  864. # various array sizes to ensure masking in AVX is tested
  865. for size in range(1,32):
  866. myfunc = getattr(np, func)
  867. x_f32 = np.float32(np.random.uniform(low=minval, high=maxval,
  868. size=size))
  869. x_f64 = np.float64(x_f32)
  870. x_f128 = np.longdouble(x_f32)
  871. y_true128 = myfunc(x_f128)
  872. if maxulperr == 0:
  873. assert_equal(myfunc(x_f32), np.float32(y_true128))
  874. assert_equal(myfunc(x_f64), np.float64(y_true128))
  875. else:
  876. assert_array_max_ulp(myfunc(x_f32), np.float32(y_true128),
  877. maxulp=maxulperr)
  878. assert_array_max_ulp(myfunc(x_f64), np.float64(y_true128),
  879. maxulp=maxulperr)
  880. # various strides to test gather instruction
  881. if size > 1:
  882. y_true32 = myfunc(x_f32)
  883. y_true64 = myfunc(x_f64)
  884. for jj in strides:
  885. assert_equal(myfunc(x_f64[::jj]), y_true64[::jj])
  886. assert_equal(myfunc(x_f32[::jj]), y_true32[::jj])
  887. class TestAVXFloat32Transcendental:
  888. def test_exp_float32(self):
  889. np.random.seed(42)
  890. x_f32 = np.float32(np.random.uniform(low=0.0,high=88.1,size=1000000))
  891. x_f64 = np.float64(x_f32)
  892. assert_array_max_ulp(np.exp(x_f32), np.float32(np.exp(x_f64)), maxulp=3)
  893. def test_log_float32(self):
  894. np.random.seed(42)
  895. x_f32 = np.float32(np.random.uniform(low=0.0,high=1000,size=1000000))
  896. x_f64 = np.float64(x_f32)
  897. assert_array_max_ulp(np.log(x_f32), np.float32(np.log(x_f64)), maxulp=4)
  898. def test_sincos_float32(self):
  899. np.random.seed(42)
  900. N = 1000000
  901. M = np.int_(N/20)
  902. index = np.random.randint(low=0, high=N, size=M)
  903. x_f32 = np.float32(np.random.uniform(low=-100.,high=100.,size=N))
  904. # test coverage for elements > 117435.992f for which glibc is used
  905. x_f32[index] = np.float32(10E+10*np.random.rand(M))
  906. x_f64 = np.float64(x_f32)
  907. assert_array_max_ulp(np.sin(x_f32), np.float32(np.sin(x_f64)), maxulp=2)
  908. assert_array_max_ulp(np.cos(x_f32), np.float32(np.cos(x_f64)), maxulp=2)
  909. # test aliasing(issue #17761)
  910. tx_f32 = x_f32.copy()
  911. assert_array_max_ulp(np.sin(x_f32, out=x_f32), np.float32(np.sin(x_f64)), maxulp=2)
  912. assert_array_max_ulp(np.cos(tx_f32, out=tx_f32), np.float32(np.cos(x_f64)), maxulp=2)
  913. def test_strided_float32(self):
  914. np.random.seed(42)
  915. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  916. sizes = np.arange(2,100)
  917. for ii in sizes:
  918. x_f32 = np.float32(np.random.uniform(low=0.01,high=88.1,size=ii))
  919. x_f32_large = x_f32.copy()
  920. x_f32_large[3:-1:4] = 120000.0
  921. exp_true = np.exp(x_f32)
  922. log_true = np.log(x_f32)
  923. sin_true = np.sin(x_f32_large)
  924. cos_true = np.cos(x_f32_large)
  925. for jj in strides:
  926. assert_array_almost_equal_nulp(np.exp(x_f32[::jj]), exp_true[::jj], nulp=2)
  927. assert_array_almost_equal_nulp(np.log(x_f32[::jj]), log_true[::jj], nulp=2)
  928. assert_array_almost_equal_nulp(np.sin(x_f32_large[::jj]), sin_true[::jj], nulp=2)
  929. assert_array_almost_equal_nulp(np.cos(x_f32_large[::jj]), cos_true[::jj], nulp=2)
  930. class TestLogAddExp(_FilterInvalids):
  931. def test_logaddexp_values(self):
  932. x = [1, 2, 3, 4, 5]
  933. y = [5, 4, 3, 2, 1]
  934. z = [6, 6, 6, 6, 6]
  935. for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
  936. xf = np.log(np.array(x, dtype=dt))
  937. yf = np.log(np.array(y, dtype=dt))
  938. zf = np.log(np.array(z, dtype=dt))
  939. assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_)
  940. def test_logaddexp_range(self):
  941. x = [1000000, -1000000, 1000200, -1000200]
  942. y = [1000200, -1000200, 1000000, -1000000]
  943. z = [1000200, -1000000, 1000200, -1000000]
  944. for dt in ['f', 'd', 'g']:
  945. logxf = np.array(x, dtype=dt)
  946. logyf = np.array(y, dtype=dt)
  947. logzf = np.array(z, dtype=dt)
  948. assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
  949. def test_inf(self):
  950. inf = np.inf
  951. x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
  952. y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
  953. z = [inf, inf, inf, -inf, inf, inf, 1, 1]
  954. with np.errstate(invalid='raise'):
  955. for dt in ['f', 'd', 'g']:
  956. logxf = np.array(x, dtype=dt)
  957. logyf = np.array(y, dtype=dt)
  958. logzf = np.array(z, dtype=dt)
  959. assert_equal(np.logaddexp(logxf, logyf), logzf)
  960. def test_nan(self):
  961. assert_(np.isnan(np.logaddexp(np.nan, np.inf)))
  962. assert_(np.isnan(np.logaddexp(np.inf, np.nan)))
  963. assert_(np.isnan(np.logaddexp(np.nan, 0)))
  964. assert_(np.isnan(np.logaddexp(0, np.nan)))
  965. assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
  966. def test_reduce(self):
  967. assert_equal(np.logaddexp.identity, -np.inf)
  968. assert_equal(np.logaddexp.reduce([]), -np.inf)
  969. class TestLog1p:
  970. def test_log1p(self):
  971. assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))
  972. assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6))
  973. def test_special(self):
  974. with np.errstate(invalid="ignore", divide="ignore"):
  975. assert_equal(ncu.log1p(np.nan), np.nan)
  976. assert_equal(ncu.log1p(np.inf), np.inf)
  977. assert_equal(ncu.log1p(-1.), -np.inf)
  978. assert_equal(ncu.log1p(-2.), np.nan)
  979. assert_equal(ncu.log1p(-np.inf), np.nan)
  980. class TestExpm1:
  981. def test_expm1(self):
  982. assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1)
  983. assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1)
  984. def test_special(self):
  985. assert_equal(ncu.expm1(np.inf), np.inf)
  986. assert_equal(ncu.expm1(0.), 0.)
  987. assert_equal(ncu.expm1(-0.), -0.)
  988. assert_equal(ncu.expm1(np.inf), np.inf)
  989. assert_equal(ncu.expm1(-np.inf), -1.)
  990. def test_complex(self):
  991. x = np.asarray(1e-12)
  992. assert_allclose(x, ncu.expm1(x))
  993. x = x.astype(np.complex128)
  994. assert_allclose(x, ncu.expm1(x))
  995. class TestHypot:
  996. def test_simple(self):
  997. assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2))
  998. assert_almost_equal(ncu.hypot(0, 0), 0)
  999. def test_reduce(self):
  1000. assert_almost_equal(ncu.hypot.reduce([3.0, 4.0]), 5.0)
  1001. assert_almost_equal(ncu.hypot.reduce([3.0, 4.0, 0]), 5.0)
  1002. assert_almost_equal(ncu.hypot.reduce([9.0, 12.0, 20.0]), 25.0)
  1003. assert_equal(ncu.hypot.reduce([]), 0.0)
  1004. def assert_hypot_isnan(x, y):
  1005. with np.errstate(invalid='ignore'):
  1006. assert_(np.isnan(ncu.hypot(x, y)),
  1007. "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y)))
  1008. def assert_hypot_isinf(x, y):
  1009. with np.errstate(invalid='ignore'):
  1010. assert_(np.isinf(ncu.hypot(x, y)),
  1011. "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
  1012. class TestHypotSpecialValues:
  1013. def test_nan_outputs(self):
  1014. assert_hypot_isnan(np.nan, np.nan)
  1015. assert_hypot_isnan(np.nan, 1)
  1016. def test_nan_outputs2(self):
  1017. assert_hypot_isinf(np.nan, np.inf)
  1018. assert_hypot_isinf(np.inf, np.nan)
  1019. assert_hypot_isinf(np.inf, 0)
  1020. assert_hypot_isinf(0, np.inf)
  1021. assert_hypot_isinf(np.inf, np.inf)
  1022. assert_hypot_isinf(np.inf, 23.0)
  1023. def test_no_fpe(self):
  1024. assert_no_warnings(ncu.hypot, np.inf, 0)
  1025. def assert_arctan2_isnan(x, y):
  1026. assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y)))
  1027. def assert_arctan2_ispinf(x, y):
  1028. assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y)))
  1029. def assert_arctan2_isninf(x, y):
  1030. assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y)))
  1031. def assert_arctan2_ispzero(x, y):
  1032. assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y)))
  1033. def assert_arctan2_isnzero(x, y):
  1034. assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y)))
  1035. class TestArctan2SpecialValues:
  1036. def test_one_one(self):
  1037. # atan2(1, 1) returns pi/4.
  1038. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi)
  1039. assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi)
  1040. assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi)
  1041. def test_zero_nzero(self):
  1042. # atan2(+-0, -0) returns +-pi.
  1043. assert_almost_equal(ncu.arctan2(np.PZERO, np.NZERO), np.pi)
  1044. assert_almost_equal(ncu.arctan2(np.NZERO, np.NZERO), -np.pi)
  1045. def test_zero_pzero(self):
  1046. # atan2(+-0, +0) returns +-0.
  1047. assert_arctan2_ispzero(np.PZERO, np.PZERO)
  1048. assert_arctan2_isnzero(np.NZERO, np.PZERO)
  1049. def test_zero_negative(self):
  1050. # atan2(+-0, x) returns +-pi for x < 0.
  1051. assert_almost_equal(ncu.arctan2(np.PZERO, -1), np.pi)
  1052. assert_almost_equal(ncu.arctan2(np.NZERO, -1), -np.pi)
  1053. def test_zero_positive(self):
  1054. # atan2(+-0, x) returns +-0 for x > 0.
  1055. assert_arctan2_ispzero(np.PZERO, 1)
  1056. assert_arctan2_isnzero(np.NZERO, 1)
  1057. def test_positive_zero(self):
  1058. # atan2(y, +-0) returns +pi/2 for y > 0.
  1059. assert_almost_equal(ncu.arctan2(1, np.PZERO), 0.5 * np.pi)
  1060. assert_almost_equal(ncu.arctan2(1, np.NZERO), 0.5 * np.pi)
  1061. def test_negative_zero(self):
  1062. # atan2(y, +-0) returns -pi/2 for y < 0.
  1063. assert_almost_equal(ncu.arctan2(-1, np.PZERO), -0.5 * np.pi)
  1064. assert_almost_equal(ncu.arctan2(-1, np.NZERO), -0.5 * np.pi)
  1065. def test_any_ninf(self):
  1066. # atan2(+-y, -infinity) returns +-pi for finite y > 0.
  1067. assert_almost_equal(ncu.arctan2(1, np.NINF), np.pi)
  1068. assert_almost_equal(ncu.arctan2(-1, np.NINF), -np.pi)
  1069. def test_any_pinf(self):
  1070. # atan2(+-y, +infinity) returns +-0 for finite y > 0.
  1071. assert_arctan2_ispzero(1, np.inf)
  1072. assert_arctan2_isnzero(-1, np.inf)
  1073. def test_inf_any(self):
  1074. # atan2(+-infinity, x) returns +-pi/2 for finite x.
  1075. assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi)
  1076. assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi)
  1077. def test_inf_ninf(self):
  1078. # atan2(+-infinity, -infinity) returns +-3*pi/4.
  1079. assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi)
  1080. assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi)
  1081. def test_inf_pinf(self):
  1082. # atan2(+-infinity, +infinity) returns +-pi/4.
  1083. assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi)
  1084. assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi)
  1085. def test_nan_any(self):
  1086. # atan2(nan, x) returns nan for any x, including inf
  1087. assert_arctan2_isnan(np.nan, np.inf)
  1088. assert_arctan2_isnan(np.inf, np.nan)
  1089. assert_arctan2_isnan(np.nan, np.nan)
  1090. class TestLdexp:
  1091. def _check_ldexp(self, tp):
  1092. assert_almost_equal(ncu.ldexp(np.array(2., np.float32),
  1093. np.array(3, tp)), 16.)
  1094. assert_almost_equal(ncu.ldexp(np.array(2., np.float64),
  1095. np.array(3, tp)), 16.)
  1096. assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble),
  1097. np.array(3, tp)), 16.)
  1098. def test_ldexp(self):
  1099. # The default Python int type should work
  1100. assert_almost_equal(ncu.ldexp(2., 3), 16.)
  1101. # The following int types should all be accepted
  1102. self._check_ldexp(np.int8)
  1103. self._check_ldexp(np.int16)
  1104. self._check_ldexp(np.int32)
  1105. self._check_ldexp('i')
  1106. self._check_ldexp('l')
  1107. def test_ldexp_overflow(self):
  1108. # silence warning emitted on overflow
  1109. with np.errstate(over="ignore"):
  1110. imax = np.iinfo(np.dtype('l')).max
  1111. imin = np.iinfo(np.dtype('l')).min
  1112. assert_equal(ncu.ldexp(2., imax), np.inf)
  1113. assert_equal(ncu.ldexp(2., imin), 0)
  1114. class TestMaximum(_FilterInvalids):
  1115. def test_reduce(self):
  1116. dflt = np.typecodes['AllFloat']
  1117. dint = np.typecodes['AllInteger']
  1118. seq1 = np.arange(11)
  1119. seq2 = seq1[::-1]
  1120. func = np.maximum.reduce
  1121. for dt in dint:
  1122. tmp1 = seq1.astype(dt)
  1123. tmp2 = seq2.astype(dt)
  1124. assert_equal(func(tmp1), 10)
  1125. assert_equal(func(tmp2), 10)
  1126. for dt in dflt:
  1127. tmp1 = seq1.astype(dt)
  1128. tmp2 = seq2.astype(dt)
  1129. assert_equal(func(tmp1), 10)
  1130. assert_equal(func(tmp2), 10)
  1131. tmp1[::2] = np.nan
  1132. tmp2[::2] = np.nan
  1133. assert_equal(func(tmp1), np.nan)
  1134. assert_equal(func(tmp2), np.nan)
  1135. def test_reduce_complex(self):
  1136. assert_equal(np.maximum.reduce([1, 2j]), 1)
  1137. assert_equal(np.maximum.reduce([1+3j, 2j]), 1+3j)
  1138. def test_float_nans(self):
  1139. nan = np.nan
  1140. arg1 = np.array([0, nan, nan])
  1141. arg2 = np.array([nan, 0, nan])
  1142. out = np.array([nan, nan, nan])
  1143. assert_equal(np.maximum(arg1, arg2), out)
  1144. def test_object_nans(self):
  1145. # Multiple checks to give this a chance to
  1146. # fail if cmp is used instead of rich compare.
  1147. # Failure cannot be guaranteed.
  1148. for i in range(1):
  1149. x = np.array(float('nan'), object)
  1150. y = 1.0
  1151. z = np.array(float('nan'), object)
  1152. assert_(np.maximum(x, y) == 1.0)
  1153. assert_(np.maximum(z, y) == 1.0)
  1154. def test_complex_nans(self):
  1155. nan = np.nan
  1156. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1157. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1158. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1159. out = np.array([nan, nan, nan], dtype=complex)
  1160. assert_equal(np.maximum(arg1, arg2), out)
  1161. def test_object_array(self):
  1162. arg1 = np.arange(5, dtype=object)
  1163. arg2 = arg1 + 1
  1164. assert_equal(np.maximum(arg1, arg2), arg2)
  1165. def test_strided_array(self):
  1166. arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
  1167. arr2 = np.array([-2.0,-1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
  1168. maxtrue = np.array([-2.0, 1.0, np.nan, 1.0, np.nan, np.nan, np.inf, -3.0])
  1169. out = np.ones(8)
  1170. out_maxtrue = np.array([-2.0, 1.0, 1.0, 10.0, 1.0, 1.0, np.nan, 1.0])
  1171. assert_equal(np.maximum(arr1,arr2), maxtrue)
  1172. assert_equal(np.maximum(arr1[::2],arr2[::2]), maxtrue[::2])
  1173. assert_equal(np.maximum(arr1[:4:], arr2[::2]), np.array([-2.0, np.nan, 10.0, 1.0]))
  1174. assert_equal(np.maximum(arr1[::3], arr2[:3:]), np.array([-2.0, 0.0, np.nan]))
  1175. assert_equal(np.maximum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-2.0, 10., np.nan]))
  1176. assert_equal(out, out_maxtrue)
  1177. class TestMinimum(_FilterInvalids):
  1178. def test_reduce(self):
  1179. dflt = np.typecodes['AllFloat']
  1180. dint = np.typecodes['AllInteger']
  1181. seq1 = np.arange(11)
  1182. seq2 = seq1[::-1]
  1183. func = np.minimum.reduce
  1184. for dt in dint:
  1185. tmp1 = seq1.astype(dt)
  1186. tmp2 = seq2.astype(dt)
  1187. assert_equal(func(tmp1), 0)
  1188. assert_equal(func(tmp2), 0)
  1189. for dt in dflt:
  1190. tmp1 = seq1.astype(dt)
  1191. tmp2 = seq2.astype(dt)
  1192. assert_equal(func(tmp1), 0)
  1193. assert_equal(func(tmp2), 0)
  1194. tmp1[::2] = np.nan
  1195. tmp2[::2] = np.nan
  1196. assert_equal(func(tmp1), np.nan)
  1197. assert_equal(func(tmp2), np.nan)
  1198. def test_reduce_complex(self):
  1199. assert_equal(np.minimum.reduce([1, 2j]), 2j)
  1200. assert_equal(np.minimum.reduce([1+3j, 2j]), 2j)
  1201. def test_float_nans(self):
  1202. nan = np.nan
  1203. arg1 = np.array([0, nan, nan])
  1204. arg2 = np.array([nan, 0, nan])
  1205. out = np.array([nan, nan, nan])
  1206. assert_equal(np.minimum(arg1, arg2), out)
  1207. def test_object_nans(self):
  1208. # Multiple checks to give this a chance to
  1209. # fail if cmp is used instead of rich compare.
  1210. # Failure cannot be guaranteed.
  1211. for i in range(1):
  1212. x = np.array(float('nan'), object)
  1213. y = 1.0
  1214. z = np.array(float('nan'), object)
  1215. assert_(np.minimum(x, y) == 1.0)
  1216. assert_(np.minimum(z, y) == 1.0)
  1217. def test_complex_nans(self):
  1218. nan = np.nan
  1219. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1220. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1221. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1222. out = np.array([nan, nan, nan], dtype=complex)
  1223. assert_equal(np.minimum(arg1, arg2), out)
  1224. def test_object_array(self):
  1225. arg1 = np.arange(5, dtype=object)
  1226. arg2 = arg1 + 1
  1227. assert_equal(np.minimum(arg1, arg2), arg1)
  1228. def test_strided_array(self):
  1229. arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
  1230. arr2 = np.array([-2.0,-1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
  1231. mintrue = np.array([-4.0, -1.0, np.nan, 0.0, np.nan, np.nan, 1.0, -np.inf])
  1232. out = np.ones(8)
  1233. out_mintrue = np.array([-4.0, 1.0, 1.0, 1.0, 1.0, 1.0, np.nan, 1.0])
  1234. assert_equal(np.minimum(arr1,arr2), mintrue)
  1235. assert_equal(np.minimum(arr1[::2],arr2[::2]), mintrue[::2])
  1236. assert_equal(np.minimum(arr1[:4:], arr2[::2]), np.array([-4.0, np.nan, 0.0, 0.0]))
  1237. assert_equal(np.minimum(arr1[::3], arr2[:3:]), np.array([-4.0, -1.0, np.nan]))
  1238. assert_equal(np.minimum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-4.0, 1.0, np.nan]))
  1239. assert_equal(out, out_mintrue)
  1240. class TestFmax(_FilterInvalids):
  1241. def test_reduce(self):
  1242. dflt = np.typecodes['AllFloat']
  1243. dint = np.typecodes['AllInteger']
  1244. seq1 = np.arange(11)
  1245. seq2 = seq1[::-1]
  1246. func = np.fmax.reduce
  1247. for dt in dint:
  1248. tmp1 = seq1.astype(dt)
  1249. tmp2 = seq2.astype(dt)
  1250. assert_equal(func(tmp1), 10)
  1251. assert_equal(func(tmp2), 10)
  1252. for dt in dflt:
  1253. tmp1 = seq1.astype(dt)
  1254. tmp2 = seq2.astype(dt)
  1255. assert_equal(func(tmp1), 10)
  1256. assert_equal(func(tmp2), 10)
  1257. tmp1[::2] = np.nan
  1258. tmp2[::2] = np.nan
  1259. assert_equal(func(tmp1), 9)
  1260. assert_equal(func(tmp2), 9)
  1261. def test_reduce_complex(self):
  1262. assert_equal(np.fmax.reduce([1, 2j]), 1)
  1263. assert_equal(np.fmax.reduce([1+3j, 2j]), 1+3j)
  1264. def test_float_nans(self):
  1265. nan = np.nan
  1266. arg1 = np.array([0, nan, nan])
  1267. arg2 = np.array([nan, 0, nan])
  1268. out = np.array([0, 0, nan])
  1269. assert_equal(np.fmax(arg1, arg2), out)
  1270. def test_complex_nans(self):
  1271. nan = np.nan
  1272. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1273. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1274. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1275. out = np.array([0, 0, nan], dtype=complex)
  1276. assert_equal(np.fmax(arg1, arg2), out)
  1277. class TestFmin(_FilterInvalids):
  1278. def test_reduce(self):
  1279. dflt = np.typecodes['AllFloat']
  1280. dint = np.typecodes['AllInteger']
  1281. seq1 = np.arange(11)
  1282. seq2 = seq1[::-1]
  1283. func = np.fmin.reduce
  1284. for dt in dint:
  1285. tmp1 = seq1.astype(dt)
  1286. tmp2 = seq2.astype(dt)
  1287. assert_equal(func(tmp1), 0)
  1288. assert_equal(func(tmp2), 0)
  1289. for dt in dflt:
  1290. tmp1 = seq1.astype(dt)
  1291. tmp2 = seq2.astype(dt)
  1292. assert_equal(func(tmp1), 0)
  1293. assert_equal(func(tmp2), 0)
  1294. tmp1[::2] = np.nan
  1295. tmp2[::2] = np.nan
  1296. assert_equal(func(tmp1), 1)
  1297. assert_equal(func(tmp2), 1)
  1298. def test_reduce_complex(self):
  1299. assert_equal(np.fmin.reduce([1, 2j]), 2j)
  1300. assert_equal(np.fmin.reduce([1+3j, 2j]), 2j)
  1301. def test_float_nans(self):
  1302. nan = np.nan
  1303. arg1 = np.array([0, nan, nan])
  1304. arg2 = np.array([nan, 0, nan])
  1305. out = np.array([0, 0, nan])
  1306. assert_equal(np.fmin(arg1, arg2), out)
  1307. def test_complex_nans(self):
  1308. nan = np.nan
  1309. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1310. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1311. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1312. out = np.array([0, 0, nan], dtype=complex)
  1313. assert_equal(np.fmin(arg1, arg2), out)
  1314. class TestBool:
  1315. def test_exceptions(self):
  1316. a = np.ones(1, dtype=np.bool_)
  1317. assert_raises(TypeError, np.negative, a)
  1318. assert_raises(TypeError, np.positive, a)
  1319. assert_raises(TypeError, np.subtract, a, a)
  1320. def test_truth_table_logical(self):
  1321. # 2, 3 and 4 serves as true values
  1322. input1 = [0, 0, 3, 2]
  1323. input2 = [0, 4, 0, 2]
  1324. typecodes = (np.typecodes['AllFloat']
  1325. + np.typecodes['AllInteger']
  1326. + '?') # boolean
  1327. for dtype in map(np.dtype, typecodes):
  1328. arg1 = np.asarray(input1, dtype=dtype)
  1329. arg2 = np.asarray(input2, dtype=dtype)
  1330. # OR
  1331. out = [False, True, True, True]
  1332. for func in (np.logical_or, np.maximum):
  1333. assert_equal(func(arg1, arg2).astype(bool), out)
  1334. # AND
  1335. out = [False, False, False, True]
  1336. for func in (np.logical_and, np.minimum):
  1337. assert_equal(func(arg1, arg2).astype(bool), out)
  1338. # XOR
  1339. out = [False, True, True, False]
  1340. for func in (np.logical_xor, np.not_equal):
  1341. assert_equal(func(arg1, arg2).astype(bool), out)
  1342. def test_truth_table_bitwise(self):
  1343. arg1 = [False, False, True, True]
  1344. arg2 = [False, True, False, True]
  1345. out = [False, True, True, True]
  1346. assert_equal(np.bitwise_or(arg1, arg2), out)
  1347. out = [False, False, False, True]
  1348. assert_equal(np.bitwise_and(arg1, arg2), out)
  1349. out = [False, True, True, False]
  1350. assert_equal(np.bitwise_xor(arg1, arg2), out)
  1351. def test_reduce(self):
  1352. none = np.array([0, 0, 0, 0], bool)
  1353. some = np.array([1, 0, 1, 1], bool)
  1354. every = np.array([1, 1, 1, 1], bool)
  1355. empty = np.array([], bool)
  1356. arrs = [none, some, every, empty]
  1357. for arr in arrs:
  1358. assert_equal(np.logical_and.reduce(arr), all(arr))
  1359. for arr in arrs:
  1360. assert_equal(np.logical_or.reduce(arr), any(arr))
  1361. for arr in arrs:
  1362. assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1)
  1363. class TestBitwiseUFuncs:
  1364. bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O']
  1365. def test_values(self):
  1366. for dt in self.bitwise_types:
  1367. zeros = np.array([0], dtype=dt)
  1368. ones = np.array([-1], dtype=dt)
  1369. msg = "dt = '%s'" % dt.char
  1370. assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
  1371. assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
  1372. assert_equal(np.bitwise_or(zeros, zeros), zeros, err_msg=msg)
  1373. assert_equal(np.bitwise_or(zeros, ones), ones, err_msg=msg)
  1374. assert_equal(np.bitwise_or(ones, zeros), ones, err_msg=msg)
  1375. assert_equal(np.bitwise_or(ones, ones), ones, err_msg=msg)
  1376. assert_equal(np.bitwise_xor(zeros, zeros), zeros, err_msg=msg)
  1377. assert_equal(np.bitwise_xor(zeros, ones), ones, err_msg=msg)
  1378. assert_equal(np.bitwise_xor(ones, zeros), ones, err_msg=msg)
  1379. assert_equal(np.bitwise_xor(ones, ones), zeros, err_msg=msg)
  1380. assert_equal(np.bitwise_and(zeros, zeros), zeros, err_msg=msg)
  1381. assert_equal(np.bitwise_and(zeros, ones), zeros, err_msg=msg)
  1382. assert_equal(np.bitwise_and(ones, zeros), zeros, err_msg=msg)
  1383. assert_equal(np.bitwise_and(ones, ones), ones, err_msg=msg)
  1384. def test_types(self):
  1385. for dt in self.bitwise_types:
  1386. zeros = np.array([0], dtype=dt)
  1387. ones = np.array([-1], dtype=dt)
  1388. msg = "dt = '%s'" % dt.char
  1389. assert_(np.bitwise_not(zeros).dtype == dt, msg)
  1390. assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
  1391. assert_(np.bitwise_xor(zeros, zeros).dtype == dt, msg)
  1392. assert_(np.bitwise_and(zeros, zeros).dtype == dt, msg)
  1393. def test_identity(self):
  1394. assert_(np.bitwise_or.identity == 0, 'bitwise_or')
  1395. assert_(np.bitwise_xor.identity == 0, 'bitwise_xor')
  1396. assert_(np.bitwise_and.identity == -1, 'bitwise_and')
  1397. def test_reduction(self):
  1398. binary_funcs = (np.bitwise_or, np.bitwise_xor, np.bitwise_and)
  1399. for dt in self.bitwise_types:
  1400. zeros = np.array([0], dtype=dt)
  1401. ones = np.array([-1], dtype=dt)
  1402. for f in binary_funcs:
  1403. msg = "dt: '%s', f: '%s'" % (dt, f)
  1404. assert_equal(f.reduce(zeros), zeros, err_msg=msg)
  1405. assert_equal(f.reduce(ones), ones, err_msg=msg)
  1406. # Test empty reduction, no object dtype
  1407. for dt in self.bitwise_types[:-1]:
  1408. # No object array types
  1409. empty = np.array([], dtype=dt)
  1410. for f in binary_funcs:
  1411. msg = "dt: '%s', f: '%s'" % (dt, f)
  1412. tgt = np.array(f.identity, dtype=dt)
  1413. res = f.reduce(empty)
  1414. assert_equal(res, tgt, err_msg=msg)
  1415. assert_(res.dtype == tgt.dtype, msg)
  1416. # Empty object arrays use the identity. Note that the types may
  1417. # differ, the actual type used is determined by the assign_identity
  1418. # function and is not the same as the type returned by the identity
  1419. # method.
  1420. for f in binary_funcs:
  1421. msg = "dt: '%s'" % (f,)
  1422. empty = np.array([], dtype=object)
  1423. tgt = f.identity
  1424. res = f.reduce(empty)
  1425. assert_equal(res, tgt, err_msg=msg)
  1426. # Non-empty object arrays do not use the identity
  1427. for f in binary_funcs:
  1428. msg = "dt: '%s'" % (f,)
  1429. btype = np.array([True], dtype=object)
  1430. assert_(type(f.reduce(btype)) is bool, msg)
  1431. class TestInt:
  1432. def test_logical_not(self):
  1433. x = np.ones(10, dtype=np.int16)
  1434. o = np.ones(10 * 2, dtype=bool)
  1435. tgt = o.copy()
  1436. tgt[::2] = False
  1437. os = o[::2]
  1438. assert_array_equal(np.logical_not(x, out=os), False)
  1439. assert_array_equal(o, tgt)
  1440. class TestFloatingPoint:
  1441. def test_floating_point(self):
  1442. assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
  1443. class TestDegrees:
  1444. def test_degrees(self):
  1445. assert_almost_equal(ncu.degrees(np.pi), 180.0)
  1446. assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0)
  1447. class TestRadians:
  1448. def test_radians(self):
  1449. assert_almost_equal(ncu.radians(180.0), np.pi)
  1450. assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi)
  1451. class TestHeavside:
  1452. def test_heaviside(self):
  1453. x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]])
  1454. expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]])
  1455. expected1 = expectedhalf.copy()
  1456. expected1[0, 2] = 1
  1457. h = ncu.heaviside(x, 0.5)
  1458. assert_equal(h, expectedhalf)
  1459. h = ncu.heaviside(x, 1.0)
  1460. assert_equal(h, expected1)
  1461. x = x.astype(np.float32)
  1462. h = ncu.heaviside(x, np.float32(0.5))
  1463. assert_equal(h, expectedhalf.astype(np.float32))
  1464. h = ncu.heaviside(x, np.float32(1.0))
  1465. assert_equal(h, expected1.astype(np.float32))
  1466. class TestSign:
  1467. def test_sign(self):
  1468. a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
  1469. out = np.zeros(a.shape)
  1470. tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
  1471. with np.errstate(invalid='ignore'):
  1472. res = ncu.sign(a)
  1473. assert_equal(res, tgt)
  1474. res = ncu.sign(a, out)
  1475. assert_equal(res, tgt)
  1476. assert_equal(out, tgt)
  1477. def test_sign_dtype_object(self):
  1478. # In reference to github issue #6229
  1479. foo = np.array([-.1, 0, .1])
  1480. a = np.sign(foo.astype(object))
  1481. b = np.sign(foo)
  1482. assert_array_equal(a, b)
  1483. def test_sign_dtype_nan_object(self):
  1484. # In reference to github issue #6229
  1485. def test_nan():
  1486. foo = np.array([np.nan])
  1487. # FIXME: a not used
  1488. a = np.sign(foo.astype(object))
  1489. assert_raises(TypeError, test_nan)
  1490. class TestMinMax:
  1491. def test_minmax_blocked(self):
  1492. # simd tests on max/min, test all alignments, slow but important
  1493. # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once)
  1494. for dt, sz in [(np.float32, 15), (np.float64, 7)]:
  1495. for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
  1496. max_size=sz):
  1497. for i in range(inp.size):
  1498. inp[:] = np.arange(inp.size, dtype=dt)
  1499. inp[i] = np.nan
  1500. emsg = lambda: '%r\n%s' % (inp, msg)
  1501. with suppress_warnings() as sup:
  1502. sup.filter(RuntimeWarning,
  1503. "invalid value encountered in reduce")
  1504. assert_(np.isnan(inp.max()), msg=emsg)
  1505. assert_(np.isnan(inp.min()), msg=emsg)
  1506. inp[i] = 1e10
  1507. assert_equal(inp.max(), 1e10, err_msg=msg)
  1508. inp[i] = -1e10
  1509. assert_equal(inp.min(), -1e10, err_msg=msg)
  1510. def test_lower_align(self):
  1511. # check data that is not aligned to element size
  1512. # i.e doubles are aligned to 4 bytes on i386
  1513. d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  1514. assert_equal(d.max(), d[0])
  1515. assert_equal(d.min(), d[0])
  1516. def test_reduce_reorder(self):
  1517. # gh 10370, 11029 Some compilers reorder the call to npy_getfloatstatus
  1518. # and put it before the call to an intrisic function that causes
  1519. # invalid status to be set. Also make sure warnings are not emitted
  1520. for n in (2, 4, 8, 16, 32):
  1521. for dt in (np.float32, np.float16, np.complex64):
  1522. for r in np.diagflat(np.array([np.nan] * n, dtype=dt)):
  1523. assert_equal(np.min(r), np.nan)
  1524. def test_minimize_no_warns(self):
  1525. a = np.minimum(np.nan, 1)
  1526. assert_equal(a, np.nan)
  1527. class TestAbsoluteNegative:
  1528. def test_abs_neg_blocked(self):
  1529. # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1
  1530. for dt, sz in [(np.float32, 11), (np.float64, 5)]:
  1531. for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
  1532. max_size=sz):
  1533. tgt = [ncu.absolute(i) for i in inp]
  1534. np.absolute(inp, out=out)
  1535. assert_equal(out, tgt, err_msg=msg)
  1536. assert_((out >= 0).all())
  1537. tgt = [-1*(i) for i in inp]
  1538. np.negative(inp, out=out)
  1539. assert_equal(out, tgt, err_msg=msg)
  1540. for v in [np.nan, -np.inf, np.inf]:
  1541. for i in range(inp.size):
  1542. d = np.arange(inp.size, dtype=dt)
  1543. inp[:] = -d
  1544. inp[i] = v
  1545. d[i] = -v if v == -np.inf else v
  1546. assert_array_equal(np.abs(inp), d, err_msg=msg)
  1547. np.abs(inp, out=out)
  1548. assert_array_equal(out, d, err_msg=msg)
  1549. assert_array_equal(-inp, -1*inp, err_msg=msg)
  1550. d = -1 * inp
  1551. np.negative(inp, out=out)
  1552. assert_array_equal(out, d, err_msg=msg)
  1553. def test_lower_align(self):
  1554. # check data that is not aligned to element size
  1555. # i.e doubles are aligned to 4 bytes on i386
  1556. d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  1557. assert_equal(np.abs(d), d)
  1558. assert_equal(np.negative(d), -d)
  1559. np.negative(d, out=d)
  1560. np.negative(np.ones_like(d), out=d)
  1561. np.abs(d, out=d)
  1562. np.abs(np.ones_like(d), out=d)
  1563. class TestPositive:
  1564. def test_valid(self):
  1565. valid_dtypes = [int, float, complex, object]
  1566. for dtype in valid_dtypes:
  1567. x = np.arange(5, dtype=dtype)
  1568. result = np.positive(x)
  1569. assert_equal(x, result, err_msg=str(dtype))
  1570. def test_invalid(self):
  1571. with assert_raises(TypeError):
  1572. np.positive(True)
  1573. with assert_raises(TypeError):
  1574. np.positive(np.datetime64('2000-01-01'))
  1575. with assert_raises(TypeError):
  1576. np.positive(np.array(['foo'], dtype=str))
  1577. with assert_raises(TypeError):
  1578. np.positive(np.array(['bar'], dtype=object))
  1579. class TestSpecialMethods:
  1580. def test_wrap(self):
  1581. class with_wrap:
  1582. def __array__(self):
  1583. return np.zeros(1)
  1584. def __array_wrap__(self, arr, context):
  1585. r = with_wrap()
  1586. r.arr = arr
  1587. r.context = context
  1588. return r
  1589. a = with_wrap()
  1590. x = ncu.minimum(a, a)
  1591. assert_equal(x.arr, np.zeros(1))
  1592. func, args, i = x.context
  1593. assert_(func is ncu.minimum)
  1594. assert_equal(len(args), 2)
  1595. assert_equal(args[0], a)
  1596. assert_equal(args[1], a)
  1597. assert_equal(i, 0)
  1598. def test_wrap_and_prepare_out(self):
  1599. # Calling convention for out should not affect how special methods are
  1600. # called
  1601. class StoreArrayPrepareWrap(np.ndarray):
  1602. _wrap_args = None
  1603. _prepare_args = None
  1604. def __new__(cls):
  1605. return np.empty(()).view(cls)
  1606. def __array_wrap__(self, obj, context):
  1607. self._wrap_args = context[1]
  1608. return obj
  1609. def __array_prepare__(self, obj, context):
  1610. self._prepare_args = context[1]
  1611. return obj
  1612. @property
  1613. def args(self):
  1614. # We need to ensure these are fetched at the same time, before
  1615. # any other ufuncs are called by the assertions
  1616. return (self._prepare_args, self._wrap_args)
  1617. def __repr__(self):
  1618. return "a" # for short test output
  1619. def do_test(f_call, f_expected):
  1620. a = StoreArrayPrepareWrap()
  1621. f_call(a)
  1622. p, w = a.args
  1623. expected = f_expected(a)
  1624. try:
  1625. assert_equal(p, expected)
  1626. assert_equal(w, expected)
  1627. except AssertionError as e:
  1628. # assert_equal produces truly useless error messages
  1629. raise AssertionError("\n".join([
  1630. "Bad arguments passed in ufunc call",
  1631. " expected: {}".format(expected),
  1632. " __array_prepare__ got: {}".format(p),
  1633. " __array_wrap__ got: {}".format(w)
  1634. ]))
  1635. # method not on the out argument
  1636. do_test(lambda a: np.add(a, 0), lambda a: (a, 0))
  1637. do_test(lambda a: np.add(a, 0, None), lambda a: (a, 0))
  1638. do_test(lambda a: np.add(a, 0, out=None), lambda a: (a, 0))
  1639. do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))
  1640. # method on the out argument
  1641. do_test(lambda a: np.add(0, 0, a), lambda a: (0, 0, a))
  1642. do_test(lambda a: np.add(0, 0, out=a), lambda a: (0, 0, a))
  1643. do_test(lambda a: np.add(0, 0, out=(a,)), lambda a: (0, 0, a))
  1644. def test_wrap_with_iterable(self):
  1645. # test fix for bug #1026:
  1646. class with_wrap(np.ndarray):
  1647. __array_priority__ = 10
  1648. def __new__(cls):
  1649. return np.asarray(1).view(cls).copy()
  1650. def __array_wrap__(self, arr, context):
  1651. return arr.view(type(self))
  1652. a = with_wrap()
  1653. x = ncu.multiply(a, (1, 2, 3))
  1654. assert_(isinstance(x, with_wrap))
  1655. assert_array_equal(x, np.array((1, 2, 3)))
  1656. def test_priority_with_scalar(self):
  1657. # test fix for bug #826:
  1658. class A(np.ndarray):
  1659. __array_priority__ = 10
  1660. def __new__(cls):
  1661. return np.asarray(1.0, 'float64').view(cls).copy()
  1662. a = A()
  1663. x = np.float64(1)*a
  1664. assert_(isinstance(x, A))
  1665. assert_array_equal(x, np.array(1))
  1666. def test_old_wrap(self):
  1667. class with_wrap:
  1668. def __array__(self):
  1669. return np.zeros(1)
  1670. def __array_wrap__(self, arr):
  1671. r = with_wrap()
  1672. r.arr = arr
  1673. return r
  1674. a = with_wrap()
  1675. x = ncu.minimum(a, a)
  1676. assert_equal(x.arr, np.zeros(1))
  1677. def test_priority(self):
  1678. class A:
  1679. def __array__(self):
  1680. return np.zeros(1)
  1681. def __array_wrap__(self, arr, context):
  1682. r = type(self)()
  1683. r.arr = arr
  1684. r.context = context
  1685. return r
  1686. class B(A):
  1687. __array_priority__ = 20.
  1688. class C(A):
  1689. __array_priority__ = 40.
  1690. x = np.zeros(1)
  1691. a = A()
  1692. b = B()
  1693. c = C()
  1694. f = ncu.minimum
  1695. assert_(type(f(x, x)) is np.ndarray)
  1696. assert_(type(f(x, a)) is A)
  1697. assert_(type(f(x, b)) is B)
  1698. assert_(type(f(x, c)) is C)
  1699. assert_(type(f(a, x)) is A)
  1700. assert_(type(f(b, x)) is B)
  1701. assert_(type(f(c, x)) is C)
  1702. assert_(type(f(a, a)) is A)
  1703. assert_(type(f(a, b)) is B)
  1704. assert_(type(f(b, a)) is B)
  1705. assert_(type(f(b, b)) is B)
  1706. assert_(type(f(b, c)) is C)
  1707. assert_(type(f(c, b)) is C)
  1708. assert_(type(f(c, c)) is C)
  1709. assert_(type(ncu.exp(a) is A))
  1710. assert_(type(ncu.exp(b) is B))
  1711. assert_(type(ncu.exp(c) is C))
  1712. def test_failing_wrap(self):
  1713. class A:
  1714. def __array__(self):
  1715. return np.zeros(2)
  1716. def __array_wrap__(self, arr, context):
  1717. raise RuntimeError
  1718. a = A()
  1719. assert_raises(RuntimeError, ncu.maximum, a, a)
  1720. assert_raises(RuntimeError, ncu.maximum.reduce, a)
  1721. def test_failing_out_wrap(self):
  1722. singleton = np.array([1.0])
  1723. class Ok(np.ndarray):
  1724. def __array_wrap__(self, obj):
  1725. return singleton
  1726. class Bad(np.ndarray):
  1727. def __array_wrap__(self, obj):
  1728. raise RuntimeError
  1729. ok = np.empty(1).view(Ok)
  1730. bad = np.empty(1).view(Bad)
  1731. # double-free (segfault) of "ok" if "bad" raises an exception
  1732. for i in range(10):
  1733. assert_raises(RuntimeError, ncu.frexp, 1, ok, bad)
  1734. def test_none_wrap(self):
  1735. # Tests that issue #8507 is resolved. Previously, this would segfault
  1736. class A:
  1737. def __array__(self):
  1738. return np.zeros(1)
  1739. def __array_wrap__(self, arr, context=None):
  1740. return None
  1741. a = A()
  1742. assert_equal(ncu.maximum(a, a), None)
  1743. def test_default_prepare(self):
  1744. class with_wrap:
  1745. __array_priority__ = 10
  1746. def __array__(self):
  1747. return np.zeros(1)
  1748. def __array_wrap__(self, arr, context):
  1749. return arr
  1750. a = with_wrap()
  1751. x = ncu.minimum(a, a)
  1752. assert_equal(x, np.zeros(1))
  1753. assert_equal(type(x), np.ndarray)
  1754. def test_prepare(self):
  1755. class with_prepare(np.ndarray):
  1756. __array_priority__ = 10
  1757. def __array_prepare__(self, arr, context):
  1758. # make sure we can return a new
  1759. return np.array(arr).view(type=with_prepare)
  1760. a = np.array(1).view(type=with_prepare)
  1761. x = np.add(a, a)
  1762. assert_equal(x, np.array(2))
  1763. assert_equal(type(x), with_prepare)
  1764. def test_prepare_out(self):
  1765. class with_prepare(np.ndarray):
  1766. __array_priority__ = 10
  1767. def __array_prepare__(self, arr, context):
  1768. return np.array(arr).view(type=with_prepare)
  1769. a = np.array([1]).view(type=with_prepare)
  1770. x = np.add(a, a, a)
  1771. # Returned array is new, because of the strange
  1772. # __array_prepare__ above
  1773. assert_(not np.shares_memory(x, a))
  1774. assert_equal(x, np.array([2]))
  1775. assert_equal(type(x), with_prepare)
  1776. def test_failing_prepare(self):
  1777. class A:
  1778. def __array__(self):
  1779. return np.zeros(1)
  1780. def __array_prepare__(self, arr, context=None):
  1781. raise RuntimeError
  1782. a = A()
  1783. assert_raises(RuntimeError, ncu.maximum, a, a)
  1784. def test_array_too_many_args(self):
  1785. class A(object):
  1786. def __array__(self, dtype, context):
  1787. return np.zeros(1)
  1788. a = A()
  1789. assert_raises_regex(TypeError, '2 required positional', np.sum, a)
  1790. def test_ufunc_override(self):
  1791. # check override works even with instance with high priority.
  1792. class A:
  1793. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1794. return self, func, method, inputs, kwargs
  1795. class MyNDArray(np.ndarray):
  1796. __array_priority__ = 100
  1797. a = A()
  1798. b = np.array([1]).view(MyNDArray)
  1799. res0 = np.multiply(a, b)
  1800. res1 = np.multiply(b, b, out=a)
  1801. # self
  1802. assert_equal(res0[0], a)
  1803. assert_equal(res1[0], a)
  1804. assert_equal(res0[1], np.multiply)
  1805. assert_equal(res1[1], np.multiply)
  1806. assert_equal(res0[2], '__call__')
  1807. assert_equal(res1[2], '__call__')
  1808. assert_equal(res0[3], (a, b))
  1809. assert_equal(res1[3], (b, b))
  1810. assert_equal(res0[4], {})
  1811. assert_equal(res1[4], {'out': (a,)})
  1812. def test_ufunc_override_mro(self):
  1813. # Some multi arg functions for testing.
  1814. def tres_mul(a, b, c):
  1815. return a * b * c
  1816. def quatro_mul(a, b, c, d):
  1817. return a * b * c * d
  1818. # Make these into ufuncs.
  1819. three_mul_ufunc = np.frompyfunc(tres_mul, 3, 1)
  1820. four_mul_ufunc = np.frompyfunc(quatro_mul, 4, 1)
  1821. class A:
  1822. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1823. return "A"
  1824. class ASub(A):
  1825. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1826. return "ASub"
  1827. class B:
  1828. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1829. return "B"
  1830. class C:
  1831. def __init__(self):
  1832. self.count = 0
  1833. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1834. self.count += 1
  1835. return NotImplemented
  1836. class CSub(C):
  1837. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  1838. self.count += 1
  1839. return NotImplemented
  1840. a = A()
  1841. a_sub = ASub()
  1842. b = B()
  1843. c = C()
  1844. # Standard
  1845. res = np.multiply(a, a_sub)
  1846. assert_equal(res, "ASub")
  1847. res = np.multiply(a_sub, b)
  1848. assert_equal(res, "ASub")
  1849. # With 1 NotImplemented
  1850. res = np.multiply(c, a)
  1851. assert_equal(res, "A")
  1852. assert_equal(c.count, 1)
  1853. # Check our counter works, so we can trust tests below.
  1854. res = np.multiply(c, a)
  1855. assert_equal(c.count, 2)
  1856. # Both NotImplemented.
  1857. c = C()
  1858. c_sub = CSub()
  1859. assert_raises(TypeError, np.multiply, c, c_sub)
  1860. assert_equal(c.count, 1)
  1861. assert_equal(c_sub.count, 1)
  1862. c.count = c_sub.count = 0
  1863. assert_raises(TypeError, np.multiply, c_sub, c)
  1864. assert_equal(c.count, 1)
  1865. assert_equal(c_sub.count, 1)
  1866. c.count = 0
  1867. assert_raises(TypeError, np.multiply, c, c)
  1868. assert_equal(c.count, 1)
  1869. c.count = 0
  1870. assert_raises(TypeError, np.multiply, 2, c)
  1871. assert_equal(c.count, 1)
  1872. # Ternary testing.
  1873. assert_equal(three_mul_ufunc(a, 1, 2), "A")
  1874. assert_equal(three_mul_ufunc(1, a, 2), "A")
  1875. assert_equal(three_mul_ufunc(1, 2, a), "A")
  1876. assert_equal(three_mul_ufunc(a, a, 6), "A")
  1877. assert_equal(three_mul_ufunc(a, 2, a), "A")
  1878. assert_equal(three_mul_ufunc(a, 2, b), "A")
  1879. assert_equal(three_mul_ufunc(a, 2, a_sub), "ASub")
  1880. assert_equal(three_mul_ufunc(a, a_sub, 3), "ASub")
  1881. c.count = 0
  1882. assert_equal(three_mul_ufunc(c, a_sub, 3), "ASub")
  1883. assert_equal(c.count, 1)
  1884. c.count = 0
  1885. assert_equal(three_mul_ufunc(1, a_sub, c), "ASub")
  1886. assert_equal(c.count, 0)
  1887. c.count = 0
  1888. assert_equal(three_mul_ufunc(a, b, c), "A")
  1889. assert_equal(c.count, 0)
  1890. c_sub.count = 0
  1891. assert_equal(three_mul_ufunc(a, b, c_sub), "A")
  1892. assert_equal(c_sub.count, 0)
  1893. assert_equal(three_mul_ufunc(1, 2, b), "B")
  1894. assert_raises(TypeError, three_mul_ufunc, 1, 2, c)
  1895. assert_raises(TypeError, three_mul_ufunc, c_sub, 2, c)
  1896. assert_raises(TypeError, three_mul_ufunc, c_sub, 2, 3)
  1897. # Quaternary testing.
  1898. assert_equal(four_mul_ufunc(a, 1, 2, 3), "A")
  1899. assert_equal(four_mul_ufunc(1, a, 2, 3), "A")
  1900. assert_equal(four_mul_ufunc(1, 1, a, 3), "A")
  1901. assert_equal(four_mul_ufunc(1, 1, 2, a), "A")
  1902. assert_equal(four_mul_ufunc(a, b, 2, 3), "A")
  1903. assert_equal(four_mul_ufunc(1, a, 2, b), "A")
  1904. assert_equal(four_mul_ufunc(b, 1, a, 3), "B")
  1905. assert_equal(four_mul_ufunc(a_sub, 1, 2, a), "ASub")
  1906. assert_equal(four_mul_ufunc(a, 1, 2, a_sub), "ASub")
  1907. c = C()
  1908. c_sub = CSub()
  1909. assert_raises(TypeError, four_mul_ufunc, 1, 2, 3, c)
  1910. assert_equal(c.count, 1)
  1911. c.count = 0
  1912. assert_raises(TypeError, four_mul_ufunc, 1, 2, c_sub, c)
  1913. assert_equal(c_sub.count, 1)
  1914. assert_equal(c.count, 1)
  1915. c2 = C()
  1916. c.count = c_sub.count = 0
  1917. assert_raises(TypeError, four_mul_ufunc, 1, c, c_sub, c2)
  1918. assert_equal(c_sub.count, 1)
  1919. assert_equal(c.count, 1)
  1920. assert_equal(c2.count, 0)
  1921. c.count = c2.count = c_sub.count = 0
  1922. assert_raises(TypeError, four_mul_ufunc, c2, c, c_sub, c)
  1923. assert_equal(c_sub.count, 1)
  1924. assert_equal(c.count, 0)
  1925. assert_equal(c2.count, 1)
  1926. def test_ufunc_override_methods(self):
  1927. class A:
  1928. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  1929. return self, ufunc, method, inputs, kwargs
  1930. # __call__
  1931. a = A()
  1932. res = np.multiply.__call__(1, a, foo='bar', answer=42)
  1933. assert_equal(res[0], a)
  1934. assert_equal(res[1], np.multiply)
  1935. assert_equal(res[2], '__call__')
  1936. assert_equal(res[3], (1, a))
  1937. assert_equal(res[4], {'foo': 'bar', 'answer': 42})
  1938. # __call__, wrong args
  1939. assert_raises(TypeError, np.multiply, a)
  1940. assert_raises(TypeError, np.multiply, a, a, a, a)
  1941. assert_raises(TypeError, np.multiply, a, a, sig='a', signature='a')
  1942. assert_raises(TypeError, ncu_tests.inner1d, a, a, axis=0, axes=[0, 0])
  1943. # reduce, positional args
  1944. res = np.multiply.reduce(a, 'axis0', 'dtype0', 'out0', 'keep0')
  1945. assert_equal(res[0], a)
  1946. assert_equal(res[1], np.multiply)
  1947. assert_equal(res[2], 'reduce')
  1948. assert_equal(res[3], (a,))
  1949. assert_equal(res[4], {'dtype':'dtype0',
  1950. 'out': ('out0',),
  1951. 'keepdims': 'keep0',
  1952. 'axis': 'axis0'})
  1953. # reduce, kwargs
  1954. res = np.multiply.reduce(a, axis='axis0', dtype='dtype0', out='out0',
  1955. keepdims='keep0', initial='init0',
  1956. where='where0')
  1957. assert_equal(res[0], a)
  1958. assert_equal(res[1], np.multiply)
  1959. assert_equal(res[2], 'reduce')
  1960. assert_equal(res[3], (a,))
  1961. assert_equal(res[4], {'dtype':'dtype0',
  1962. 'out': ('out0',),
  1963. 'keepdims': 'keep0',
  1964. 'axis': 'axis0',
  1965. 'initial': 'init0',
  1966. 'where': 'where0'})
  1967. # reduce, output equal to None removed, but not other explicit ones,
  1968. # even if they are at their default value.
  1969. res = np.multiply.reduce(a, 0, None, None, False)
  1970. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False})
  1971. res = np.multiply.reduce(a, out=None, axis=0, keepdims=True)
  1972. assert_equal(res[4], {'axis': 0, 'keepdims': True})
  1973. res = np.multiply.reduce(a, None, out=(None,), dtype=None)
  1974. assert_equal(res[4], {'axis': None, 'dtype': None})
  1975. res = np.multiply.reduce(a, 0, None, None, False, 2, True)
  1976. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  1977. 'initial': 2, 'where': True})
  1978. # np._NoValue ignored for initial
  1979. res = np.multiply.reduce(a, 0, None, None, False,
  1980. np._NoValue, True)
  1981. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  1982. 'where': True})
  1983. # None kept for initial, True for where.
  1984. res = np.multiply.reduce(a, 0, None, None, False, None, True)
  1985. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  1986. 'initial': None, 'where': True})
  1987. # reduce, wrong args
  1988. assert_raises(ValueError, np.multiply.reduce, a, out=())
  1989. assert_raises(ValueError, np.multiply.reduce, a, out=('out0', 'out1'))
  1990. assert_raises(TypeError, np.multiply.reduce, a, 'axis0', axis='axis0')
  1991. # accumulate, pos args
  1992. res = np.multiply.accumulate(a, 'axis0', 'dtype0', 'out0')
  1993. assert_equal(res[0], a)
  1994. assert_equal(res[1], np.multiply)
  1995. assert_equal(res[2], 'accumulate')
  1996. assert_equal(res[3], (a,))
  1997. assert_equal(res[4], {'dtype':'dtype0',
  1998. 'out': ('out0',),
  1999. 'axis': 'axis0'})
  2000. # accumulate, kwargs
  2001. res = np.multiply.accumulate(a, axis='axis0', dtype='dtype0',
  2002. out='out0')
  2003. assert_equal(res[0], a)
  2004. assert_equal(res[1], np.multiply)
  2005. assert_equal(res[2], 'accumulate')
  2006. assert_equal(res[3], (a,))
  2007. assert_equal(res[4], {'dtype':'dtype0',
  2008. 'out': ('out0',),
  2009. 'axis': 'axis0'})
  2010. # accumulate, output equal to None removed.
  2011. res = np.multiply.accumulate(a, 0, None, None)
  2012. assert_equal(res[4], {'axis': 0, 'dtype': None})
  2013. res = np.multiply.accumulate(a, out=None, axis=0, dtype='dtype1')
  2014. assert_equal(res[4], {'axis': 0, 'dtype': 'dtype1'})
  2015. res = np.multiply.accumulate(a, None, out=(None,), dtype=None)
  2016. assert_equal(res[4], {'axis': None, 'dtype': None})
  2017. # accumulate, wrong args
  2018. assert_raises(ValueError, np.multiply.accumulate, a, out=())
  2019. assert_raises(ValueError, np.multiply.accumulate, a,
  2020. out=('out0', 'out1'))
  2021. assert_raises(TypeError, np.multiply.accumulate, a,
  2022. 'axis0', axis='axis0')
  2023. # reduceat, pos args
  2024. res = np.multiply.reduceat(a, [4, 2], 'axis0', 'dtype0', 'out0')
  2025. assert_equal(res[0], a)
  2026. assert_equal(res[1], np.multiply)
  2027. assert_equal(res[2], 'reduceat')
  2028. assert_equal(res[3], (a, [4, 2]))
  2029. assert_equal(res[4], {'dtype':'dtype0',
  2030. 'out': ('out0',),
  2031. 'axis': 'axis0'})
  2032. # reduceat, kwargs
  2033. res = np.multiply.reduceat(a, [4, 2], axis='axis0', dtype='dtype0',
  2034. out='out0')
  2035. assert_equal(res[0], a)
  2036. assert_equal(res[1], np.multiply)
  2037. assert_equal(res[2], 'reduceat')
  2038. assert_equal(res[3], (a, [4, 2]))
  2039. assert_equal(res[4], {'dtype':'dtype0',
  2040. 'out': ('out0',),
  2041. 'axis': 'axis0'})
  2042. # reduceat, output equal to None removed.
  2043. res = np.multiply.reduceat(a, [4, 2], 0, None, None)
  2044. assert_equal(res[4], {'axis': 0, 'dtype': None})
  2045. res = np.multiply.reduceat(a, [4, 2], axis=None, out=None, dtype='dt')
  2046. assert_equal(res[4], {'axis': None, 'dtype': 'dt'})
  2047. res = np.multiply.reduceat(a, [4, 2], None, None, out=(None,))
  2048. assert_equal(res[4], {'axis': None, 'dtype': None})
  2049. # reduceat, wrong args
  2050. assert_raises(ValueError, np.multiply.reduce, a, [4, 2], out=())
  2051. assert_raises(ValueError, np.multiply.reduce, a, [4, 2],
  2052. out=('out0', 'out1'))
  2053. assert_raises(TypeError, np.multiply.reduce, a, [4, 2],
  2054. 'axis0', axis='axis0')
  2055. # outer
  2056. res = np.multiply.outer(a, 42)
  2057. assert_equal(res[0], a)
  2058. assert_equal(res[1], np.multiply)
  2059. assert_equal(res[2], 'outer')
  2060. assert_equal(res[3], (a, 42))
  2061. assert_equal(res[4], {})
  2062. # outer, wrong args
  2063. assert_raises(TypeError, np.multiply.outer, a)
  2064. assert_raises(TypeError, np.multiply.outer, a, a, a, a)
  2065. assert_raises(TypeError, np.multiply.outer, a, a, sig='a', signature='a')
  2066. # at
  2067. res = np.multiply.at(a, [4, 2], 'b0')
  2068. assert_equal(res[0], a)
  2069. assert_equal(res[1], np.multiply)
  2070. assert_equal(res[2], 'at')
  2071. assert_equal(res[3], (a, [4, 2], 'b0'))
  2072. # at, wrong args
  2073. assert_raises(TypeError, np.multiply.at, a)
  2074. assert_raises(TypeError, np.multiply.at, a, a, a, a)
  2075. def test_ufunc_override_out(self):
  2076. class A:
  2077. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2078. return kwargs
  2079. class B:
  2080. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2081. return kwargs
  2082. a = A()
  2083. b = B()
  2084. res0 = np.multiply(a, b, 'out_arg')
  2085. res1 = np.multiply(a, b, out='out_arg')
  2086. res2 = np.multiply(2, b, 'out_arg')
  2087. res3 = np.multiply(3, b, out='out_arg')
  2088. res4 = np.multiply(a, 4, 'out_arg')
  2089. res5 = np.multiply(a, 5, out='out_arg')
  2090. assert_equal(res0['out'][0], 'out_arg')
  2091. assert_equal(res1['out'][0], 'out_arg')
  2092. assert_equal(res2['out'][0], 'out_arg')
  2093. assert_equal(res3['out'][0], 'out_arg')
  2094. assert_equal(res4['out'][0], 'out_arg')
  2095. assert_equal(res5['out'][0], 'out_arg')
  2096. # ufuncs with multiple output modf and frexp.
  2097. res6 = np.modf(a, 'out0', 'out1')
  2098. res7 = np.frexp(a, 'out0', 'out1')
  2099. assert_equal(res6['out'][0], 'out0')
  2100. assert_equal(res6['out'][1], 'out1')
  2101. assert_equal(res7['out'][0], 'out0')
  2102. assert_equal(res7['out'][1], 'out1')
  2103. # While we're at it, check that default output is never passed on.
  2104. assert_(np.sin(a, None) == {})
  2105. assert_(np.sin(a, out=None) == {})
  2106. assert_(np.sin(a, out=(None,)) == {})
  2107. assert_(np.modf(a, None) == {})
  2108. assert_(np.modf(a, None, None) == {})
  2109. assert_(np.modf(a, out=(None, None)) == {})
  2110. with assert_raises(TypeError):
  2111. # Out argument must be tuple, since there are multiple outputs.
  2112. np.modf(a, out=None)
  2113. # don't give positional and output argument, or too many arguments.
  2114. # wrong number of arguments in the tuple is an error too.
  2115. assert_raises(TypeError, np.multiply, a, b, 'one', out='two')
  2116. assert_raises(TypeError, np.multiply, a, b, 'one', 'two')
  2117. assert_raises(ValueError, np.multiply, a, b, out=('one', 'two'))
  2118. assert_raises(ValueError, np.multiply, a, out=())
  2119. assert_raises(TypeError, np.modf, a, 'one', out=('two', 'three'))
  2120. assert_raises(TypeError, np.modf, a, 'one', 'two', 'three')
  2121. assert_raises(ValueError, np.modf, a, out=('one', 'two', 'three'))
  2122. assert_raises(ValueError, np.modf, a, out=('one',))
  2123. def test_ufunc_override_exception(self):
  2124. class A:
  2125. def __array_ufunc__(self, *a, **kwargs):
  2126. raise ValueError("oops")
  2127. a = A()
  2128. assert_raises(ValueError, np.negative, 1, out=a)
  2129. assert_raises(ValueError, np.negative, a)
  2130. assert_raises(ValueError, np.divide, 1., a)
  2131. def test_ufunc_override_not_implemented(self):
  2132. class A:
  2133. def __array_ufunc__(self, *args, **kwargs):
  2134. return NotImplemented
  2135. msg = ("operand type(s) all returned NotImplemented from "
  2136. "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
  2137. with assert_raises_regex(TypeError, fnmatch.translate(msg)):
  2138. np.negative(A())
  2139. msg = ("operand type(s) all returned NotImplemented from "
  2140. "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
  2141. "out=(1,)): 'A', 'object', 'int'")
  2142. with assert_raises_regex(TypeError, fnmatch.translate(msg)):
  2143. np.add(A(), object(), out=1)
  2144. def test_ufunc_override_disabled(self):
  2145. class OptOut:
  2146. __array_ufunc__ = None
  2147. opt_out = OptOut()
  2148. # ufuncs always raise
  2149. msg = "operand 'OptOut' does not support ufuncs"
  2150. with assert_raises_regex(TypeError, msg):
  2151. np.add(opt_out, 1)
  2152. with assert_raises_regex(TypeError, msg):
  2153. np.add(1, opt_out)
  2154. with assert_raises_regex(TypeError, msg):
  2155. np.negative(opt_out)
  2156. # opt-outs still hold even when other arguments have pathological
  2157. # __array_ufunc__ implementations
  2158. class GreedyArray:
  2159. def __array_ufunc__(self, *args, **kwargs):
  2160. return self
  2161. greedy = GreedyArray()
  2162. assert_(np.negative(greedy) is greedy)
  2163. with assert_raises_regex(TypeError, msg):
  2164. np.add(greedy, opt_out)
  2165. with assert_raises_regex(TypeError, msg):
  2166. np.add(greedy, 1, out=opt_out)
  2167. def test_gufunc_override(self):
  2168. # gufunc are just ufunc instances, but follow a different path,
  2169. # so check __array_ufunc__ overrides them properly.
  2170. class A:
  2171. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2172. return self, ufunc, method, inputs, kwargs
  2173. inner1d = ncu_tests.inner1d
  2174. a = A()
  2175. res = inner1d(a, a)
  2176. assert_equal(res[0], a)
  2177. assert_equal(res[1], inner1d)
  2178. assert_equal(res[2], '__call__')
  2179. assert_equal(res[3], (a, a))
  2180. assert_equal(res[4], {})
  2181. res = inner1d(1, 1, out=a)
  2182. assert_equal(res[0], a)
  2183. assert_equal(res[1], inner1d)
  2184. assert_equal(res[2], '__call__')
  2185. assert_equal(res[3], (1, 1))
  2186. assert_equal(res[4], {'out': (a,)})
  2187. # wrong number of arguments in the tuple is an error too.
  2188. assert_raises(TypeError, inner1d, a, out='two')
  2189. assert_raises(TypeError, inner1d, a, a, 'one', out='two')
  2190. assert_raises(TypeError, inner1d, a, a, 'one', 'two')
  2191. assert_raises(ValueError, inner1d, a, a, out=('one', 'two'))
  2192. assert_raises(ValueError, inner1d, a, a, out=())
  2193. def test_ufunc_override_with_super(self):
  2194. # NOTE: this class is used in doc/source/user/basics.subclassing.rst
  2195. # if you make any changes here, do update it there too.
  2196. class A(np.ndarray):
  2197. def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
  2198. args = []
  2199. in_no = []
  2200. for i, input_ in enumerate(inputs):
  2201. if isinstance(input_, A):
  2202. in_no.append(i)
  2203. args.append(input_.view(np.ndarray))
  2204. else:
  2205. args.append(input_)
  2206. outputs = out
  2207. out_no = []
  2208. if outputs:
  2209. out_args = []
  2210. for j, output in enumerate(outputs):
  2211. if isinstance(output, A):
  2212. out_no.append(j)
  2213. out_args.append(output.view(np.ndarray))
  2214. else:
  2215. out_args.append(output)
  2216. kwargs['out'] = tuple(out_args)
  2217. else:
  2218. outputs = (None,) * ufunc.nout
  2219. info = {}
  2220. if in_no:
  2221. info['inputs'] = in_no
  2222. if out_no:
  2223. info['outputs'] = out_no
  2224. results = super(A, self).__array_ufunc__(ufunc, method,
  2225. *args, **kwargs)
  2226. if results is NotImplemented:
  2227. return NotImplemented
  2228. if method == 'at':
  2229. if isinstance(inputs[0], A):
  2230. inputs[0].info = info
  2231. return
  2232. if ufunc.nout == 1:
  2233. results = (results,)
  2234. results = tuple((np.asarray(result).view(A)
  2235. if output is None else output)
  2236. for result, output in zip(results, outputs))
  2237. if results and isinstance(results[0], A):
  2238. results[0].info = info
  2239. return results[0] if len(results) == 1 else results
  2240. class B:
  2241. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2242. if any(isinstance(input_, A) for input_ in inputs):
  2243. return "A!"
  2244. else:
  2245. return NotImplemented
  2246. d = np.arange(5.)
  2247. # 1 input, 1 output
  2248. a = np.arange(5.).view(A)
  2249. b = np.sin(a)
  2250. check = np.sin(d)
  2251. assert_(np.all(check == b))
  2252. assert_equal(b.info, {'inputs': [0]})
  2253. b = np.sin(d, out=(a,))
  2254. assert_(np.all(check == b))
  2255. assert_equal(b.info, {'outputs': [0]})
  2256. assert_(b is a)
  2257. a = np.arange(5.).view(A)
  2258. b = np.sin(a, out=a)
  2259. assert_(np.all(check == b))
  2260. assert_equal(b.info, {'inputs': [0], 'outputs': [0]})
  2261. # 1 input, 2 outputs
  2262. a = np.arange(5.).view(A)
  2263. b1, b2 = np.modf(a)
  2264. assert_equal(b1.info, {'inputs': [0]})
  2265. b1, b2 = np.modf(d, out=(None, a))
  2266. assert_(b2 is a)
  2267. assert_equal(b1.info, {'outputs': [1]})
  2268. a = np.arange(5.).view(A)
  2269. b = np.arange(5.).view(A)
  2270. c1, c2 = np.modf(a, out=(a, b))
  2271. assert_(c1 is a)
  2272. assert_(c2 is b)
  2273. assert_equal(c1.info, {'inputs': [0], 'outputs': [0, 1]})
  2274. # 2 input, 1 output
  2275. a = np.arange(5.).view(A)
  2276. b = np.arange(5.).view(A)
  2277. c = np.add(a, b, out=a)
  2278. assert_(c is a)
  2279. assert_equal(c.info, {'inputs': [0, 1], 'outputs': [0]})
  2280. # some tests with a non-ndarray subclass
  2281. a = np.arange(5.)
  2282. b = B()
  2283. assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  2284. assert_(b.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  2285. assert_raises(TypeError, np.add, a, b)
  2286. a = a.view(A)
  2287. assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  2288. assert_(b.__array_ufunc__(np.add, '__call__', a, b) == "A!")
  2289. assert_(np.add(a, b) == "A!")
  2290. # regression check for gh-9102 -- tests ufunc.reduce implicitly.
  2291. d = np.array([[1, 2, 3], [1, 2, 3]])
  2292. a = d.view(A)
  2293. c = a.any()
  2294. check = d.any()
  2295. assert_equal(c, check)
  2296. assert_(c.info, {'inputs': [0]})
  2297. c = a.max()
  2298. check = d.max()
  2299. assert_equal(c, check)
  2300. assert_(c.info, {'inputs': [0]})
  2301. b = np.array(0).view(A)
  2302. c = a.max(out=b)
  2303. assert_equal(c, check)
  2304. assert_(c is b)
  2305. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  2306. check = a.max(axis=0)
  2307. b = np.zeros_like(check).view(A)
  2308. c = a.max(axis=0, out=b)
  2309. assert_equal(c, check)
  2310. assert_(c is b)
  2311. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  2312. # simple explicit tests of reduce, accumulate, reduceat
  2313. check = np.add.reduce(d, axis=1)
  2314. c = np.add.reduce(a, axis=1)
  2315. assert_equal(c, check)
  2316. assert_(c.info, {'inputs': [0]})
  2317. b = np.zeros_like(c)
  2318. c = np.add.reduce(a, 1, None, b)
  2319. assert_equal(c, check)
  2320. assert_(c is b)
  2321. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  2322. check = np.add.accumulate(d, axis=0)
  2323. c = np.add.accumulate(a, axis=0)
  2324. assert_equal(c, check)
  2325. assert_(c.info, {'inputs': [0]})
  2326. b = np.zeros_like(c)
  2327. c = np.add.accumulate(a, 0, None, b)
  2328. assert_equal(c, check)
  2329. assert_(c is b)
  2330. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  2331. indices = [0, 2, 1]
  2332. check = np.add.reduceat(d, indices, axis=1)
  2333. c = np.add.reduceat(a, indices, axis=1)
  2334. assert_equal(c, check)
  2335. assert_(c.info, {'inputs': [0]})
  2336. b = np.zeros_like(c)
  2337. c = np.add.reduceat(a, indices, 1, None, b)
  2338. assert_equal(c, check)
  2339. assert_(c is b)
  2340. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  2341. # and a few tests for at
  2342. d = np.array([[1, 2, 3], [1, 2, 3]])
  2343. check = d.copy()
  2344. a = d.copy().view(A)
  2345. np.add.at(check, ([0, 1], [0, 2]), 1.)
  2346. np.add.at(a, ([0, 1], [0, 2]), 1.)
  2347. assert_equal(a, check)
  2348. assert_(a.info, {'inputs': [0]})
  2349. b = np.array(1.).view(A)
  2350. a = d.copy().view(A)
  2351. np.add.at(a, ([0, 1], [0, 2]), b)
  2352. assert_equal(a, check)
  2353. assert_(a.info, {'inputs': [0, 2]})
  2354. class TestChoose:
  2355. def test_mixed(self):
  2356. c = np.array([True, True])
  2357. a = np.array([True, True])
  2358. assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))
  2359. class TestRationalFunctions:
  2360. def test_lcm(self):
  2361. self._test_lcm_inner(np.int16)
  2362. self._test_lcm_inner(np.uint16)
  2363. def test_lcm_object(self):
  2364. self._test_lcm_inner(np.object_)
  2365. def test_gcd(self):
  2366. self._test_gcd_inner(np.int16)
  2367. self._test_lcm_inner(np.uint16)
  2368. def test_gcd_object(self):
  2369. self._test_gcd_inner(np.object_)
  2370. def _test_lcm_inner(self, dtype):
  2371. # basic use
  2372. a = np.array([12, 120], dtype=dtype)
  2373. b = np.array([20, 200], dtype=dtype)
  2374. assert_equal(np.lcm(a, b), [60, 600])
  2375. if not issubclass(dtype, np.unsignedinteger):
  2376. # negatives are ignored
  2377. a = np.array([12, -12, 12, -12], dtype=dtype)
  2378. b = np.array([20, 20, -20, -20], dtype=dtype)
  2379. assert_equal(np.lcm(a, b), [60]*4)
  2380. # reduce
  2381. a = np.array([3, 12, 20], dtype=dtype)
  2382. assert_equal(np.lcm.reduce([3, 12, 20]), 60)
  2383. # broadcasting, and a test including 0
  2384. a = np.arange(6).astype(dtype)
  2385. b = 20
  2386. assert_equal(np.lcm(a, b), [0, 20, 20, 60, 20, 20])
  2387. def _test_gcd_inner(self, dtype):
  2388. # basic use
  2389. a = np.array([12, 120], dtype=dtype)
  2390. b = np.array([20, 200], dtype=dtype)
  2391. assert_equal(np.gcd(a, b), [4, 40])
  2392. if not issubclass(dtype, np.unsignedinteger):
  2393. # negatives are ignored
  2394. a = np.array([12, -12, 12, -12], dtype=dtype)
  2395. b = np.array([20, 20, -20, -20], dtype=dtype)
  2396. assert_equal(np.gcd(a, b), [4]*4)
  2397. # reduce
  2398. a = np.array([15, 25, 35], dtype=dtype)
  2399. assert_equal(np.gcd.reduce(a), 5)
  2400. # broadcasting, and a test including 0
  2401. a = np.arange(6).astype(dtype)
  2402. b = 20
  2403. assert_equal(np.gcd(a, b), [20, 1, 2, 1, 4, 5])
  2404. def test_lcm_overflow(self):
  2405. # verify that we don't overflow when a*b does overflow
  2406. big = np.int32(np.iinfo(np.int32).max // 11)
  2407. a = 2*big
  2408. b = 5*big
  2409. assert_equal(np.lcm(a, b), 10*big)
  2410. def test_gcd_overflow(self):
  2411. for dtype in (np.int32, np.int64):
  2412. # verify that we don't overflow when taking abs(x)
  2413. # not relevant for lcm, where the result is unrepresentable anyway
  2414. a = dtype(np.iinfo(dtype).min) # negative power of two
  2415. q = -(a // 4)
  2416. assert_equal(np.gcd(a, q*3), q)
  2417. assert_equal(np.gcd(a, -q*3), q)
  2418. def test_decimal(self):
  2419. from decimal import Decimal
  2420. a = np.array([1, 1, -1, -1]) * Decimal('0.20')
  2421. b = np.array([1, -1, 1, -1]) * Decimal('0.12')
  2422. assert_equal(np.gcd(a, b), 4*[Decimal('0.04')])
  2423. assert_equal(np.lcm(a, b), 4*[Decimal('0.60')])
  2424. def test_float(self):
  2425. # not well-defined on float due to rounding errors
  2426. assert_raises(TypeError, np.gcd, 0.3, 0.4)
  2427. assert_raises(TypeError, np.lcm, 0.3, 0.4)
  2428. def test_builtin_long(self):
  2429. # sanity check that array coercion is alright for builtin longs
  2430. assert_equal(np.array(2**200).item(), 2**200)
  2431. # expressed as prime factors
  2432. a = np.array(2**100 * 3**5)
  2433. b = np.array([2**100 * 5**7, 2**50 * 3**10])
  2434. assert_equal(np.gcd(a, b), [2**100, 2**50 * 3**5])
  2435. assert_equal(np.lcm(a, b), [2**100 * 3**5 * 5**7, 2**100 * 3**10])
  2436. assert_equal(np.gcd(2**100, 3**100), 1)
  2437. class TestRoundingFunctions:
  2438. def test_object_direct(self):
  2439. """ test direct implementation of these magic methods """
  2440. class C:
  2441. def __floor__(self):
  2442. return 1
  2443. def __ceil__(self):
  2444. return 2
  2445. def __trunc__(self):
  2446. return 3
  2447. arr = np.array([C(), C()])
  2448. assert_equal(np.floor(arr), [1, 1])
  2449. assert_equal(np.ceil(arr), [2, 2])
  2450. assert_equal(np.trunc(arr), [3, 3])
  2451. def test_object_indirect(self):
  2452. """ test implementations via __float__ """
  2453. class C:
  2454. def __float__(self):
  2455. return -2.5
  2456. arr = np.array([C(), C()])
  2457. assert_equal(np.floor(arr), [-3, -3])
  2458. assert_equal(np.ceil(arr), [-2, -2])
  2459. with pytest.raises(TypeError):
  2460. np.trunc(arr) # consistent with math.trunc
  2461. def test_fraction(self):
  2462. f = Fraction(-4, 3)
  2463. assert_equal(np.floor(f), -2)
  2464. assert_equal(np.ceil(f), -1)
  2465. assert_equal(np.trunc(f), -1)
  2466. class TestComplexFunctions:
  2467. funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh,
  2468. np.arctanh, np.sin, np.cos, np.tan, np.exp,
  2469. np.exp2, np.log, np.sqrt, np.log10, np.log2,
  2470. np.log1p]
  2471. def test_it(self):
  2472. for f in self.funcs:
  2473. if f is np.arccosh:
  2474. x = 1.5
  2475. else:
  2476. x = .5
  2477. fr = f(x)
  2478. fz = f(complex(x))
  2479. assert_almost_equal(fz.real, fr, err_msg='real part %s' % f)
  2480. assert_almost_equal(fz.imag, 0., err_msg='imag part %s' % f)
  2481. def test_precisions_consistent(self):
  2482. z = 1 + 1j
  2483. for f in self.funcs:
  2484. fcf = f(np.csingle(z))
  2485. fcd = f(np.cdouble(z))
  2486. fcl = f(np.clongdouble(z))
  2487. assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s' % f)
  2488. assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s' % f)
  2489. def test_branch_cuts(self):
  2490. # check branch cuts and continuity on them
  2491. _check_branch_cut(np.log, -0.5, 1j, 1, -1, True)
  2492. _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True)
  2493. _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True)
  2494. _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True)
  2495. _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True)
  2496. _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True)
  2497. _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True)
  2498. _check_branch_cut(np.arctan, [0-2j, 2j], [1, 1], -1, 1, True)
  2499. _check_branch_cut(np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True)
  2500. _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True)
  2501. _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True)
  2502. # check against bogus branch cuts: assert continuity between quadrants
  2503. _check_branch_cut(np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1)
  2504. _check_branch_cut(np.arccos, [0-2j, 2j], [ 1, 1], 1, 1)
  2505. _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1)
  2506. _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1)
  2507. _check_branch_cut(np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1)
  2508. _check_branch_cut(np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1)
  2509. def test_branch_cuts_complex64(self):
  2510. # check branch cuts and continuity on them
  2511. _check_branch_cut(np.log, -0.5, 1j, 1, -1, True, np.complex64)
  2512. _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True, np.complex64)
  2513. _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True, np.complex64)
  2514. _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True, np.complex64)
  2515. _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True, np.complex64)
  2516. _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  2517. _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  2518. _check_branch_cut(np.arctan, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64)
  2519. _check_branch_cut(np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64)
  2520. _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64)
  2521. _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  2522. # check against bogus branch cuts: assert continuity between quadrants
  2523. _check_branch_cut(np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
  2524. _check_branch_cut(np.arccos, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
  2525. _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64)
  2526. _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64)
  2527. _check_branch_cut(np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64)
  2528. _check_branch_cut(np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64)
  2529. def test_against_cmath(self):
  2530. import cmath
  2531. points = [-1-1j, -1+1j, +1-1j, +1+1j]
  2532. name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
  2533. 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
  2534. atol = 4*np.finfo(complex).eps
  2535. for func in self.funcs:
  2536. fname = func.__name__.split('.')[-1]
  2537. cname = name_map.get(fname, fname)
  2538. try:
  2539. cfunc = getattr(cmath, cname)
  2540. except AttributeError:
  2541. continue
  2542. for p in points:
  2543. a = complex(func(np.complex_(p)))
  2544. b = cfunc(p)
  2545. assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
  2546. @pytest.mark.parametrize('dtype', [np.complex64, np.complex_, np.longcomplex])
  2547. def test_loss_of_precision(self, dtype):
  2548. """Check loss of precision in complex arc* functions"""
  2549. # Check against known-good functions
  2550. info = np.finfo(dtype)
  2551. real_dtype = dtype(0.).real.dtype
  2552. eps = info.eps
  2553. def check(x, rtol):
  2554. x = x.astype(real_dtype)
  2555. z = x.astype(dtype)
  2556. d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1)
  2557. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  2558. 'arcsinh'))
  2559. z = (1j*x).astype(dtype)
  2560. d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1)
  2561. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  2562. 'arcsin'))
  2563. z = x.astype(dtype)
  2564. d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1)
  2565. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  2566. 'arctanh'))
  2567. z = (1j*x).astype(dtype)
  2568. d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1)
  2569. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  2570. 'arctan'))
  2571. # The switchover was chosen as 1e-3; hence there can be up to
  2572. # ~eps/1e-3 of relative cancellation error before it
  2573. x_series = np.logspace(-20, -3.001, 200)
  2574. x_basic = np.logspace(-2.999, 0, 10, endpoint=False)
  2575. if dtype is np.longcomplex:
  2576. # It's not guaranteed that the system-provided arc functions
  2577. # are accurate down to a few epsilons. (Eg. on Linux 64-bit)
  2578. # So, give more leeway for long complex tests here:
  2579. # Can use 2.1 for > Ubuntu LTS Trusty (2014), glibc = 2.19.
  2580. if skip_longcomplex_msg:
  2581. pytest.skip(skip_longcomplex_msg)
  2582. check(x_series, 50.0*eps)
  2583. else:
  2584. check(x_series, 2.1*eps)
  2585. check(x_basic, 2.0*eps/1e-3)
  2586. # Check a few points
  2587. z = np.array([1e-5*(1+1j)], dtype=dtype)
  2588. p = 9.999999999333333333e-6 + 1.000000000066666666e-5j
  2589. d = np.absolute(1-np.arctanh(z)/p)
  2590. assert_(np.all(d < 1e-15))
  2591. p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j
  2592. d = np.absolute(1-np.arcsinh(z)/p)
  2593. assert_(np.all(d < 1e-15))
  2594. p = 9.999999999333333333e-6j + 1.000000000066666666e-5
  2595. d = np.absolute(1-np.arctan(z)/p)
  2596. assert_(np.all(d < 1e-15))
  2597. p = 1.0000000000333333333e-5j + 9.999999999666666667e-6
  2598. d = np.absolute(1-np.arcsin(z)/p)
  2599. assert_(np.all(d < 1e-15))
  2600. # Check continuity across switchover points
  2601. def check(func, z0, d=1):
  2602. z0 = np.asarray(z0, dtype=dtype)
  2603. zp = z0 + abs(z0) * d * eps * 2
  2604. zm = z0 - abs(z0) * d * eps * 2
  2605. assert_(np.all(zp != zm), (zp, zm))
  2606. # NB: the cancellation error at the switchover is at least eps
  2607. good = (abs(func(zp) - func(zm)) < 2*eps)
  2608. assert_(np.all(good), (func, z0[~good]))
  2609. for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan):
  2610. pts = [rp+1j*ip for rp in (-1e-3, 0, 1e-3) for ip in(-1e-3, 0, 1e-3)
  2611. if rp != 0 or ip != 0]
  2612. check(func, pts, 1)
  2613. check(func, pts, 1j)
  2614. check(func, pts, 1+1j)
  2615. class TestAttributes:
  2616. def test_attributes(self):
  2617. add = ncu.add
  2618. assert_equal(add.__name__, 'add')
  2619. assert_(add.ntypes >= 18) # don't fail if types added
  2620. assert_('ii->i' in add.types)
  2621. assert_equal(add.nin, 2)
  2622. assert_equal(add.nout, 1)
  2623. assert_equal(add.identity, 0)
  2624. def test_doc(self):
  2625. # don't bother checking the long list of kwargs, which are likely to
  2626. # change
  2627. assert_(ncu.add.__doc__.startswith(
  2628. "add(x1, x2, /, out=None, *, where=True"))
  2629. assert_(ncu.frexp.__doc__.startswith(
  2630. "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True"))
  2631. class TestSubclass:
  2632. def test_subclass_op(self):
  2633. class simple(np.ndarray):
  2634. def __new__(subtype, shape):
  2635. self = np.ndarray.__new__(subtype, shape, dtype=object)
  2636. self.fill(0)
  2637. return self
  2638. a = simple((3, 4))
  2639. assert_equal(a+a, a)
  2640. class TestFrompyfunc(object):
  2641. def test_identity(self):
  2642. def mul(a, b):
  2643. return a * b
  2644. # with identity=value
  2645. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=1)
  2646. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  2647. assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
  2648. assert_equal(mul_ufunc.reduce([]), 1)
  2649. # with identity=None (reorderable)
  2650. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=None)
  2651. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  2652. assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
  2653. assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
  2654. # with no identity (not reorderable)
  2655. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1)
  2656. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  2657. assert_raises(ValueError, lambda: mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)))
  2658. assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
  2659. def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False,
  2660. dtype=complex):
  2661. """
  2662. Check for a branch cut in a function.
  2663. Assert that `x0` lies on a branch cut of function `f` and `f` is
  2664. continuous from the direction `dx`.
  2665. Parameters
  2666. ----------
  2667. f : func
  2668. Function to check
  2669. x0 : array-like
  2670. Point on branch cut
  2671. dx : array-like
  2672. Direction to check continuity in
  2673. re_sign, im_sign : {1, -1}
  2674. Change of sign of the real or imaginary part expected
  2675. sig_zero_ok : bool
  2676. Whether to check if the branch cut respects signed zero (if applicable)
  2677. dtype : dtype
  2678. Dtype to check (should be complex)
  2679. """
  2680. x0 = np.atleast_1d(x0).astype(dtype)
  2681. dx = np.atleast_1d(dx).astype(dtype)
  2682. if np.dtype(dtype).char == 'F':
  2683. scale = np.finfo(dtype).eps * 1e2
  2684. atol = np.float32(1e-2)
  2685. else:
  2686. scale = np.finfo(dtype).eps * 1e3
  2687. atol = 1e-4
  2688. y0 = f(x0)
  2689. yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx))
  2690. ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx))
  2691. assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp))
  2692. assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp))
  2693. assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym))
  2694. assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym))
  2695. if sig_zero_ok:
  2696. # check that signed zeros also work as a displacement
  2697. jr = (x0.real == 0) & (dx.real != 0)
  2698. ji = (x0.imag == 0) & (dx.imag != 0)
  2699. if np.any(jr):
  2700. x = x0[jr]
  2701. x.real = np.NZERO
  2702. ym = f(x)
  2703. assert_(np.all(np.absolute(y0[jr].real - ym.real*re_sign) < atol), (y0[jr], ym))
  2704. assert_(np.all(np.absolute(y0[jr].imag - ym.imag*im_sign) < atol), (y0[jr], ym))
  2705. if np.any(ji):
  2706. x = x0[ji]
  2707. x.imag = np.NZERO
  2708. ym = f(x)
  2709. assert_(np.all(np.absolute(y0[ji].real - ym.real*re_sign) < atol), (y0[ji], ym))
  2710. assert_(np.all(np.absolute(y0[ji].imag - ym.imag*im_sign) < atol), (y0[ji], ym))
  2711. def test_copysign():
  2712. assert_(np.copysign(1, -1) == -1)
  2713. with np.errstate(divide="ignore"):
  2714. assert_(1 / np.copysign(0, -1) < 0)
  2715. assert_(1 / np.copysign(0, 1) > 0)
  2716. assert_(np.signbit(np.copysign(np.nan, -1)))
  2717. assert_(not np.signbit(np.copysign(np.nan, 1)))
  2718. def _test_nextafter(t):
  2719. one = t(1)
  2720. two = t(2)
  2721. zero = t(0)
  2722. eps = np.finfo(t).eps
  2723. assert_(np.nextafter(one, two) - one == eps)
  2724. assert_(np.nextafter(one, zero) - one < 0)
  2725. assert_(np.isnan(np.nextafter(np.nan, one)))
  2726. assert_(np.isnan(np.nextafter(one, np.nan)))
  2727. assert_(np.nextafter(one, one) == one)
  2728. def test_nextafter():
  2729. return _test_nextafter(np.float64)
  2730. def test_nextafterf():
  2731. return _test_nextafter(np.float32)
  2732. @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
  2733. reason="long double is same as double")
  2734. @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
  2735. reason="IBM double double")
  2736. def test_nextafterl():
  2737. return _test_nextafter(np.longdouble)
  2738. def test_nextafter_0():
  2739. for t, direction in itertools.product(np.sctypes['float'], (1, -1)):
  2740. tiny = np.finfo(t).tiny
  2741. assert_(0. < direction * np.nextafter(t(0), t(direction)) < tiny)
  2742. assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0)
  2743. def _test_spacing(t):
  2744. one = t(1)
  2745. eps = np.finfo(t).eps
  2746. nan = t(np.nan)
  2747. inf = t(np.inf)
  2748. with np.errstate(invalid='ignore'):
  2749. assert_(np.spacing(one) == eps)
  2750. assert_(np.isnan(np.spacing(nan)))
  2751. assert_(np.isnan(np.spacing(inf)))
  2752. assert_(np.isnan(np.spacing(-inf)))
  2753. assert_(np.spacing(t(1e30)) != 0)
  2754. def test_spacing():
  2755. return _test_spacing(np.float64)
  2756. def test_spacingf():
  2757. return _test_spacing(np.float32)
  2758. @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
  2759. reason="long double is same as double")
  2760. @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
  2761. reason="IBM double double")
  2762. def test_spacingl():
  2763. return _test_spacing(np.longdouble)
  2764. def test_spacing_gfortran():
  2765. # Reference from this fortran file, built with gfortran 4.3.3 on linux
  2766. # 32bits:
  2767. # PROGRAM test_spacing
  2768. # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37)
  2769. # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200)
  2770. #
  2771. # WRITE(*,*) spacing(0.00001_DBL)
  2772. # WRITE(*,*) spacing(1.0_DBL)
  2773. # WRITE(*,*) spacing(1000._DBL)
  2774. # WRITE(*,*) spacing(10500._DBL)
  2775. #
  2776. # WRITE(*,*) spacing(0.00001_SGL)
  2777. # WRITE(*,*) spacing(1.0_SGL)
  2778. # WRITE(*,*) spacing(1000._SGL)
  2779. # WRITE(*,*) spacing(10500._SGL)
  2780. # END PROGRAM
  2781. ref = {np.float64: [1.69406589450860068E-021,
  2782. 2.22044604925031308E-016,
  2783. 1.13686837721616030E-013,
  2784. 1.81898940354585648E-012],
  2785. np.float32: [9.09494702E-13,
  2786. 1.19209290E-07,
  2787. 6.10351563E-05,
  2788. 9.76562500E-04]}
  2789. for dt, dec_ in zip([np.float32, np.float64], (10, 20)):
  2790. x = np.array([1e-5, 1, 1000, 10500], dtype=dt)
  2791. assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec_)
  2792. def test_nextafter_vs_spacing():
  2793. # XXX: spacing does not handle long double yet
  2794. for t in [np.float32, np.float64]:
  2795. for _f in [1, 1e-5, 1000]:
  2796. f = t(_f)
  2797. f1 = t(_f + 1)
  2798. assert_(np.nextafter(f, f1) - f == np.spacing(f))
  2799. def test_pos_nan():
  2800. """Check np.nan is a positive nan."""
  2801. assert_(np.signbit(np.nan) == 0)
  2802. def test_reduceat():
  2803. """Test bug in reduceat when structured arrays are not copied."""
  2804. db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
  2805. a = np.empty([100], dtype=db)
  2806. a['name'] = 'Simple'
  2807. a['time'] = 10
  2808. a['value'] = 100
  2809. indx = [0, 7, 15, 25]
  2810. h2 = []
  2811. val1 = indx[0]
  2812. for val2 in indx[1:]:
  2813. h2.append(np.add.reduce(a['value'][val1:val2]))
  2814. val1 = val2
  2815. h2.append(np.add.reduce(a['value'][val1:]))
  2816. h2 = np.array(h2)
  2817. # test buffered -- this should work
  2818. h1 = np.add.reduceat(a['value'], indx)
  2819. assert_array_almost_equal(h1, h2)
  2820. # This is when the error occurs.
  2821. # test no buffer
  2822. np.setbufsize(32)
  2823. h1 = np.add.reduceat(a['value'], indx)
  2824. np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT)
  2825. assert_array_almost_equal(h1, h2)
  2826. def test_reduceat_empty():
  2827. """Reduceat should work with empty arrays"""
  2828. indices = np.array([], 'i4')
  2829. x = np.array([], 'f8')
  2830. result = np.add.reduceat(x, indices)
  2831. assert_equal(result.dtype, x.dtype)
  2832. assert_equal(result.shape, (0,))
  2833. # Another case with a slightly different zero-sized shape
  2834. x = np.ones((5, 2))
  2835. result = np.add.reduceat(x, [], axis=0)
  2836. assert_equal(result.dtype, x.dtype)
  2837. assert_equal(result.shape, (0, 2))
  2838. result = np.add.reduceat(x, [], axis=1)
  2839. assert_equal(result.dtype, x.dtype)
  2840. assert_equal(result.shape, (5, 0))
  2841. def test_complex_nan_comparisons():
  2842. nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
  2843. fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
  2844. complex(1, 1), complex(-1, -1), complex(0, 0)]
  2845. with np.errstate(invalid='ignore'):
  2846. for x in nans + fins:
  2847. x = np.array([x])
  2848. for y in nans + fins:
  2849. y = np.array([y])
  2850. if np.isfinite(x) and np.isfinite(y):
  2851. continue
  2852. assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
  2853. assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
  2854. assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
  2855. assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
  2856. assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
  2857. def test_rint_big_int():
  2858. # np.rint bug for large integer values on Windows 32-bit and MKL
  2859. # https://github.com/numpy/numpy/issues/6685
  2860. val = 4607998452777363968
  2861. # This is exactly representable in floating point
  2862. assert_equal(val, int(float(val)))
  2863. # Rint should not change the value
  2864. assert_equal(val, np.rint(val))
  2865. @pytest.mark.parametrize('ftype', [np.float32, np.float64])
  2866. def test_memoverlap_accumulate(ftype):
  2867. # Reproduces bug https://github.com/numpy/numpy/issues/15597
  2868. arr = np.array([0.61, 0.60, 0.77, 0.41, 0.19], dtype=ftype)
  2869. out_max = np.array([0.61, 0.61, 0.77, 0.77, 0.77], dtype=ftype)
  2870. out_min = np.array([0.61, 0.60, 0.60, 0.41, 0.19], dtype=ftype)
  2871. assert_equal(np.maximum.accumulate(arr), out_max)
  2872. assert_equal(np.minimum.accumulate(arr), out_min)
  2873. def test_signaling_nan_exceptions():
  2874. with assert_no_warnings():
  2875. a = np.ndarray(shape=(), dtype='float32', buffer=b'\x00\xe0\xbf\xff')
  2876. np.isnan(a)
  2877. @pytest.mark.parametrize("arr", [
  2878. np.arange(2),
  2879. np.matrix([0, 1]),
  2880. np.matrix([[0, 1], [2, 5]]),
  2881. ])
  2882. def test_outer_subclass_preserve(arr):
  2883. # for gh-8661
  2884. class foo(np.ndarray): pass
  2885. actual = np.multiply.outer(arr.view(foo), arr.view(foo))
  2886. assert actual.__class__.__name__ == 'foo'
  2887. def test_outer_bad_subclass():
  2888. class BadArr1(np.ndarray):
  2889. def __array_finalize__(self, obj):
  2890. # The outer call reshapes to 3 dims, try to do a bad reshape.
  2891. if self.ndim == 3:
  2892. self.shape = self.shape + (1,)
  2893. def __array_prepare__(self, obj, context=None):
  2894. return obj
  2895. class BadArr2(np.ndarray):
  2896. def __array_finalize__(self, obj):
  2897. if isinstance(obj, BadArr2):
  2898. # outer inserts 1-sized dims. In that case disturb them.
  2899. if self.shape[-1] == 1:
  2900. self.shape = self.shape[::-1]
  2901. def __array_prepare__(self, obj, context=None):
  2902. return obj
  2903. for cls in [BadArr1, BadArr2]:
  2904. arr = np.ones((2, 3)).view(cls)
  2905. with assert_raises(TypeError) as a:
  2906. # The first array gets reshaped (not the second one)
  2907. np.add.outer(arr, [1, 2])
  2908. # This actually works, since we only see the reshaping error:
  2909. arr = np.ones((2, 3)).view(cls)
  2910. assert type(np.add.outer([1, 2], arr)) is cls
  2911. def test_outer_exceeds_maxdims():
  2912. deep = np.ones((1,) * 17)
  2913. with assert_raises(ValueError):
  2914. np.add.outer(deep, deep)