test_umath.py 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419
  1. import platform
  2. import warnings
  3. import fnmatch
  4. import itertools
  5. import pytest
  6. import sys
  7. import os
  8. import operator
  9. from fractions import Fraction
  10. from functools import reduce
  11. from collections import namedtuple
  12. import numpy.core.umath as ncu
  13. from numpy.core import _umath_tests as ncu_tests
  14. import numpy as np
  15. from numpy.testing import (
  16. assert_, assert_equal, assert_raises, assert_raises_regex,
  17. assert_array_equal, assert_almost_equal, assert_array_almost_equal,
  18. assert_array_max_ulp, assert_allclose, assert_no_warnings, suppress_warnings,
  19. _gen_alignment_data, assert_array_almost_equal_nulp, IS_WASM
  20. )
  21. from numpy.testing._private.utils import _glibc_older_than
  22. UFUNCS = [obj for obj in np.core.umath.__dict__.values()
  23. if isinstance(obj, np.ufunc)]
  24. UFUNCS_UNARY = [
  25. uf for uf in UFUNCS if uf.nin == 1
  26. ]
  27. UFUNCS_UNARY_FP = [
  28. uf for uf in UFUNCS_UNARY if 'f->f' in uf.types
  29. ]
  30. UFUNCS_BINARY = [
  31. uf for uf in UFUNCS if uf.nin == 2
  32. ]
  33. UFUNCS_BINARY_ACC = [
  34. uf for uf in UFUNCS_BINARY if hasattr(uf, "accumulate") and uf.nout == 1
  35. ]
  36. def interesting_binop_operands(val1, val2, dtype):
  37. """
  38. Helper to create "interesting" operands to cover common code paths:
  39. * scalar inputs
  40. * only first "values" is an array (e.g. scalar division fast-paths)
  41. * Longer array (SIMD) placing the value of interest at different positions
  42. * Oddly strided arrays which may not be SIMD compatible
  43. It does not attempt to cover unaligned access or mixed dtypes.
  44. These are normally handled by the casting/buffering machinery.
  45. This is not a fixture (currently), since I believe a fixture normally
  46. only yields once?
  47. """
  48. fill_value = 1 # could be a parameter, but maybe not an optional one?
  49. arr1 = np.full(10003, dtype=dtype, fill_value=fill_value)
  50. arr2 = np.full(10003, dtype=dtype, fill_value=fill_value)
  51. arr1[0] = val1
  52. arr2[0] = val2
  53. extractor = lambda res: res
  54. yield arr1[0], arr2[0], extractor, "scalars"
  55. extractor = lambda res: res
  56. yield arr1[0, ...], arr2[0, ...], extractor, "scalar-arrays"
  57. # reset array values to fill_value:
  58. arr1[0] = fill_value
  59. arr2[0] = fill_value
  60. for pos in [0, 1, 2, 3, 4, 5, -1, -2, -3, -4]:
  61. arr1[pos] = val1
  62. arr2[pos] = val2
  63. extractor = lambda res: res[pos]
  64. yield arr1, arr2, extractor, f"off-{pos}"
  65. yield arr1, arr2[pos], extractor, f"off-{pos}-with-scalar"
  66. arr1[pos] = fill_value
  67. arr2[pos] = fill_value
  68. for stride in [-1, 113]:
  69. op1 = arr1[::stride]
  70. op2 = arr2[::stride]
  71. op1[10] = val1
  72. op2[10] = val2
  73. extractor = lambda res: res[10]
  74. yield op1, op2, extractor, f"stride-{stride}"
  75. op1[10] = fill_value
  76. op2[10] = fill_value
  77. def on_powerpc():
  78. """ True if we are running on a Power PC platform."""
  79. return platform.processor() == 'powerpc' or \
  80. platform.machine().startswith('ppc')
  81. def bad_arcsinh():
  82. """The blocklisted trig functions are not accurate on aarch64/PPC for
  83. complex256. Rather than dig through the actual problem skip the
  84. test. This should be fixed when we can move past glibc2.17
  85. which is the version in manylinux2014
  86. """
  87. if platform.machine() == 'aarch64':
  88. x = 1.78e-10
  89. elif on_powerpc():
  90. x = 2.16e-10
  91. else:
  92. return False
  93. v1 = np.arcsinh(np.float128(x))
  94. v2 = np.arcsinh(np.complex256(x)).real
  95. # The eps for float128 is 1-e33, so this is way bigger
  96. return abs((v1 / v2) - 1.0) > 1e-23
  97. class _FilterInvalids:
  98. def setup_method(self):
  99. self.olderr = np.seterr(invalid='ignore')
  100. def teardown_method(self):
  101. np.seterr(**self.olderr)
  102. class TestConstants:
  103. def test_pi(self):
  104. assert_allclose(ncu.pi, 3.141592653589793, 1e-15)
  105. def test_e(self):
  106. assert_allclose(ncu.e, 2.718281828459045, 1e-15)
  107. def test_euler_gamma(self):
  108. assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15)
  109. class TestOut:
  110. def test_out_subok(self):
  111. for subok in (True, False):
  112. a = np.array(0.5)
  113. o = np.empty(())
  114. r = np.add(a, 2, o, subok=subok)
  115. assert_(r is o)
  116. r = np.add(a, 2, out=o, subok=subok)
  117. assert_(r is o)
  118. r = np.add(a, 2, out=(o,), subok=subok)
  119. assert_(r is o)
  120. d = np.array(5.7)
  121. o1 = np.empty(())
  122. o2 = np.empty((), dtype=np.int32)
  123. r1, r2 = np.frexp(d, o1, None, subok=subok)
  124. assert_(r1 is o1)
  125. r1, r2 = np.frexp(d, None, o2, subok=subok)
  126. assert_(r2 is o2)
  127. r1, r2 = np.frexp(d, o1, o2, subok=subok)
  128. assert_(r1 is o1)
  129. assert_(r2 is o2)
  130. r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
  131. assert_(r1 is o1)
  132. r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
  133. assert_(r2 is o2)
  134. r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
  135. assert_(r1 is o1)
  136. assert_(r2 is o2)
  137. with assert_raises(TypeError):
  138. # Out argument must be tuple, since there are multiple outputs.
  139. r1, r2 = np.frexp(d, out=o1, subok=subok)
  140. assert_raises(TypeError, np.add, a, 2, o, o, subok=subok)
  141. assert_raises(TypeError, np.add, a, 2, o, out=o, subok=subok)
  142. assert_raises(TypeError, np.add, a, 2, None, out=o, subok=subok)
  143. assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
  144. assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
  145. assert_raises(TypeError, np.add, a, 2, [], subok=subok)
  146. assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
  147. assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
  148. o.flags.writeable = False
  149. assert_raises(ValueError, np.add, a, 2, o, subok=subok)
  150. assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
  151. assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok)
  152. def test_out_wrap_subok(self):
  153. class ArrayWrap(np.ndarray):
  154. __array_priority__ = 10
  155. def __new__(cls, arr):
  156. return np.asarray(arr).view(cls).copy()
  157. def __array_wrap__(self, arr, context):
  158. return arr.view(type(self))
  159. for subok in (True, False):
  160. a = ArrayWrap([0.5])
  161. r = np.add(a, 2, subok=subok)
  162. if subok:
  163. assert_(isinstance(r, ArrayWrap))
  164. else:
  165. assert_(type(r) == np.ndarray)
  166. r = np.add(a, 2, None, subok=subok)
  167. if subok:
  168. assert_(isinstance(r, ArrayWrap))
  169. else:
  170. assert_(type(r) == np.ndarray)
  171. r = np.add(a, 2, out=None, subok=subok)
  172. if subok:
  173. assert_(isinstance(r, ArrayWrap))
  174. else:
  175. assert_(type(r) == np.ndarray)
  176. r = np.add(a, 2, out=(None,), subok=subok)
  177. if subok:
  178. assert_(isinstance(r, ArrayWrap))
  179. else:
  180. assert_(type(r) == np.ndarray)
  181. d = ArrayWrap([5.7])
  182. o1 = np.empty((1,))
  183. o2 = np.empty((1,), dtype=np.int32)
  184. r1, r2 = np.frexp(d, o1, subok=subok)
  185. if subok:
  186. assert_(isinstance(r2, ArrayWrap))
  187. else:
  188. assert_(type(r2) == np.ndarray)
  189. r1, r2 = np.frexp(d, o1, None, subok=subok)
  190. if subok:
  191. assert_(isinstance(r2, ArrayWrap))
  192. else:
  193. assert_(type(r2) == np.ndarray)
  194. r1, r2 = np.frexp(d, None, o2, subok=subok)
  195. if subok:
  196. assert_(isinstance(r1, ArrayWrap))
  197. else:
  198. assert_(type(r1) == np.ndarray)
  199. r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
  200. if subok:
  201. assert_(isinstance(r2, ArrayWrap))
  202. else:
  203. assert_(type(r2) == np.ndarray)
  204. r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
  205. if subok:
  206. assert_(isinstance(r1, ArrayWrap))
  207. else:
  208. assert_(type(r1) == np.ndarray)
  209. with assert_raises(TypeError):
  210. # Out argument must be tuple, since there are multiple outputs.
  211. r1, r2 = np.frexp(d, out=o1, subok=subok)
  212. class TestComparisons:
  213. import operator
  214. @pytest.mark.parametrize('dtype', np.sctypes['uint'] + np.sctypes['int'] +
  215. np.sctypes['float'] + [np.bool_])
  216. @pytest.mark.parametrize('py_comp,np_comp', [
  217. (operator.lt, np.less),
  218. (operator.le, np.less_equal),
  219. (operator.gt, np.greater),
  220. (operator.ge, np.greater_equal),
  221. (operator.eq, np.equal),
  222. (operator.ne, np.not_equal)
  223. ])
  224. def test_comparison_functions(self, dtype, py_comp, np_comp):
  225. # Initialize input arrays
  226. if dtype == np.bool_:
  227. a = np.random.choice(a=[False, True], size=1000)
  228. b = np.random.choice(a=[False, True], size=1000)
  229. scalar = True
  230. else:
  231. a = np.random.randint(low=1, high=10, size=1000).astype(dtype)
  232. b = np.random.randint(low=1, high=10, size=1000).astype(dtype)
  233. scalar = 5
  234. np_scalar = np.dtype(dtype).type(scalar)
  235. a_lst = a.tolist()
  236. b_lst = b.tolist()
  237. # (Binary) Comparison (x1=array, x2=array)
  238. comp_b = np_comp(a, b).view(np.uint8)
  239. comp_b_list = [int(py_comp(x, y)) for x, y in zip(a_lst, b_lst)]
  240. # (Scalar1) Comparison (x1=scalar, x2=array)
  241. comp_s1 = np_comp(np_scalar, b).view(np.uint8)
  242. comp_s1_list = [int(py_comp(scalar, x)) for x in b_lst]
  243. # (Scalar2) Comparison (x1=array, x2=scalar)
  244. comp_s2 = np_comp(a, np_scalar).view(np.uint8)
  245. comp_s2_list = [int(py_comp(x, scalar)) for x in a_lst]
  246. # Sequence: Binary, Scalar1 and Scalar2
  247. assert_(comp_b.tolist() == comp_b_list,
  248. f"Failed comparison ({py_comp.__name__})")
  249. assert_(comp_s1.tolist() == comp_s1_list,
  250. f"Failed comparison ({py_comp.__name__})")
  251. assert_(comp_s2.tolist() == comp_s2_list,
  252. f"Failed comparison ({py_comp.__name__})")
  253. def test_ignore_object_identity_in_equal(self):
  254. # Check comparing identical objects whose comparison
  255. # is not a simple boolean, e.g., arrays that are compared elementwise.
  256. a = np.array([np.array([1, 2, 3]), None], dtype=object)
  257. assert_raises(ValueError, np.equal, a, a)
  258. # Check error raised when comparing identical non-comparable objects.
  259. class FunkyType:
  260. def __eq__(self, other):
  261. raise TypeError("I won't compare")
  262. a = np.array([FunkyType()])
  263. assert_raises(TypeError, np.equal, a, a)
  264. # Check identity doesn't override comparison mismatch.
  265. a = np.array([np.nan], dtype=object)
  266. assert_equal(np.equal(a, a), [False])
  267. def test_ignore_object_identity_in_not_equal(self):
  268. # Check comparing identical objects whose comparison
  269. # is not a simple boolean, e.g., arrays that are compared elementwise.
  270. a = np.array([np.array([1, 2, 3]), None], dtype=object)
  271. assert_raises(ValueError, np.not_equal, a, a)
  272. # Check error raised when comparing identical non-comparable objects.
  273. class FunkyType:
  274. def __ne__(self, other):
  275. raise TypeError("I won't compare")
  276. a = np.array([FunkyType()])
  277. assert_raises(TypeError, np.not_equal, a, a)
  278. # Check identity doesn't override comparison mismatch.
  279. a = np.array([np.nan], dtype=object)
  280. assert_equal(np.not_equal(a, a), [True])
  281. def test_error_in_equal_reduce(self):
  282. # gh-20929
  283. # make sure np.equal.reduce raises a TypeError if an array is passed
  284. # without specifying the dtype
  285. a = np.array([0, 0])
  286. assert_equal(np.equal.reduce(a, dtype=bool), True)
  287. assert_raises(TypeError, np.equal.reduce, a)
  288. def test_object_dtype(self):
  289. assert np.equal(1, [1], dtype=object).dtype == object
  290. assert np.equal(1, [1], signature=(None, None, "O")).dtype == object
  291. def test_object_nonbool_dtype_error(self):
  292. # bool output dtype is fine of course:
  293. assert np.equal(1, [1], dtype=bool).dtype == bool
  294. # but the following are examples do not have a loop:
  295. with pytest.raises(TypeError, match="No loop matching"):
  296. np.equal(1, 1, dtype=np.int64)
  297. with pytest.raises(TypeError, match="No loop matching"):
  298. np.equal(1, 1, sig=(None, None, "l"))
  299. class TestAdd:
  300. def test_reduce_alignment(self):
  301. # gh-9876
  302. # make sure arrays with weird strides work with the optimizations in
  303. # pairwise_sum_@TYPE@. On x86, the 'b' field will count as aligned at a
  304. # 4 byte offset, even though its itemsize is 8.
  305. a = np.zeros(2, dtype=[('a', np.int32), ('b', np.float64)])
  306. a['a'] = -1
  307. assert_equal(a['b'].sum(), 0)
  308. class TestDivision:
  309. def test_division_int(self):
  310. # int division should follow Python
  311. x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120])
  312. if 5 / 10 == 0.5:
  313. assert_equal(x / 100, [0.05, 0.1, 0.9, 1,
  314. -0.05, -0.1, -0.9, -1, -1.2])
  315. else:
  316. assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
  317. assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
  318. assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80])
  319. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  320. @pytest.mark.parametrize("dtype,ex_val", itertools.product(
  321. np.sctypes['int'] + np.sctypes['uint'], (
  322. (
  323. # dividend
  324. "np.array(range(fo.max-lsize, fo.max)).astype(dtype),"
  325. # divisors
  326. "np.arange(lsize).astype(dtype),"
  327. # scalar divisors
  328. "range(15)"
  329. ),
  330. (
  331. # dividend
  332. "np.arange(fo.min, fo.min+lsize).astype(dtype),"
  333. # divisors
  334. "np.arange(lsize//-2, lsize//2).astype(dtype),"
  335. # scalar divisors
  336. "range(fo.min, fo.min + 15)"
  337. ), (
  338. # dividend
  339. "np.array(range(fo.max-lsize, fo.max)).astype(dtype),"
  340. # divisors
  341. "np.arange(lsize).astype(dtype),"
  342. # scalar divisors
  343. "[1,3,9,13,neg, fo.min+1, fo.min//2, fo.max//3, fo.max//4]"
  344. )
  345. )
  346. ))
  347. def test_division_int_boundary(self, dtype, ex_val):
  348. fo = np.iinfo(dtype)
  349. neg = -1 if fo.min < 0 else 1
  350. # Large enough to test SIMD loops and remaind elements
  351. lsize = 512 + 7
  352. a, b, divisors = eval(ex_val)
  353. a_lst, b_lst = a.tolist(), b.tolist()
  354. c_div = lambda n, d: (
  355. 0 if d == 0 else (
  356. fo.min if (n and n == fo.min and d == -1) else n//d
  357. )
  358. )
  359. with np.errstate(divide='ignore'):
  360. ac = a.copy()
  361. ac //= b
  362. div_ab = a // b
  363. div_lst = [c_div(x, y) for x, y in zip(a_lst, b_lst)]
  364. msg = "Integer arrays floor division check (//)"
  365. assert all(div_ab == div_lst), msg
  366. msg_eq = "Integer arrays floor division check (//=)"
  367. assert all(ac == div_lst), msg_eq
  368. for divisor in divisors:
  369. ac = a.copy()
  370. with np.errstate(divide='ignore', over='ignore'):
  371. div_a = a // divisor
  372. ac //= divisor
  373. div_lst = [c_div(i, divisor) for i in a_lst]
  374. assert all(div_a == div_lst), msg
  375. assert all(ac == div_lst), msg_eq
  376. with np.errstate(divide='raise', over='raise'):
  377. if 0 in b:
  378. # Verify overflow case
  379. with pytest.raises(FloatingPointError,
  380. match="divide by zero encountered in floor_divide"):
  381. a // b
  382. else:
  383. a // b
  384. if fo.min and fo.min in a:
  385. with pytest.raises(FloatingPointError,
  386. match='overflow encountered in floor_divide'):
  387. a // -1
  388. elif fo.min:
  389. a // -1
  390. with pytest.raises(FloatingPointError,
  391. match="divide by zero encountered in floor_divide"):
  392. a // 0
  393. with pytest.raises(FloatingPointError,
  394. match="divide by zero encountered in floor_divide"):
  395. ac = a.copy()
  396. ac //= 0
  397. np.array([], dtype=dtype) // 0
  398. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  399. @pytest.mark.parametrize("dtype,ex_val", itertools.product(
  400. np.sctypes['int'] + np.sctypes['uint'], (
  401. "np.array([fo.max, 1, 2, 1, 1, 2, 3], dtype=dtype)",
  402. "np.array([fo.min, 1, -2, 1, 1, 2, -3]).astype(dtype)",
  403. "np.arange(fo.min, fo.min+(100*10), 10, dtype=dtype)",
  404. "np.array(range(fo.max-(100*7), fo.max, 7)).astype(dtype)",
  405. )
  406. ))
  407. def test_division_int_reduce(self, dtype, ex_val):
  408. fo = np.iinfo(dtype)
  409. a = eval(ex_val)
  410. lst = a.tolist()
  411. c_div = lambda n, d: (
  412. 0 if d == 0 or (n and n == fo.min and d == -1) else n//d
  413. )
  414. with np.errstate(divide='ignore'):
  415. div_a = np.floor_divide.reduce(a)
  416. div_lst = reduce(c_div, lst)
  417. msg = "Reduce floor integer division check"
  418. assert div_a == div_lst, msg
  419. with np.errstate(divide='raise', over='raise'):
  420. with pytest.raises(FloatingPointError,
  421. match="divide by zero encountered in reduce"):
  422. np.floor_divide.reduce(np.arange(-100, 100).astype(dtype))
  423. if fo.min:
  424. with pytest.raises(FloatingPointError,
  425. match='overflow encountered in reduce'):
  426. np.floor_divide.reduce(
  427. np.array([fo.min, 1, -1], dtype=dtype)
  428. )
  429. @pytest.mark.parametrize(
  430. "dividend,divisor,quotient",
  431. [(np.timedelta64(2,'Y'), np.timedelta64(2,'M'), 12),
  432. (np.timedelta64(2,'Y'), np.timedelta64(-2,'M'), -12),
  433. (np.timedelta64(-2,'Y'), np.timedelta64(2,'M'), -12),
  434. (np.timedelta64(-2,'Y'), np.timedelta64(-2,'M'), 12),
  435. (np.timedelta64(2,'M'), np.timedelta64(-2,'Y'), -1),
  436. (np.timedelta64(2,'Y'), np.timedelta64(0,'M'), 0),
  437. (np.timedelta64(2,'Y'), 2, np.timedelta64(1,'Y')),
  438. (np.timedelta64(2,'Y'), -2, np.timedelta64(-1,'Y')),
  439. (np.timedelta64(-2,'Y'), 2, np.timedelta64(-1,'Y')),
  440. (np.timedelta64(-2,'Y'), -2, np.timedelta64(1,'Y')),
  441. (np.timedelta64(-2,'Y'), -2, np.timedelta64(1,'Y')),
  442. (np.timedelta64(-2,'Y'), -3, np.timedelta64(0,'Y')),
  443. (np.timedelta64(-2,'Y'), 0, np.timedelta64('Nat','Y')),
  444. ])
  445. def test_division_int_timedelta(self, dividend, divisor, quotient):
  446. # If either divisor is 0 or quotient is Nat, check for division by 0
  447. if divisor and (isinstance(quotient, int) or not np.isnat(quotient)):
  448. msg = "Timedelta floor division check"
  449. assert dividend // divisor == quotient, msg
  450. # Test for arrays as well
  451. msg = "Timedelta arrays floor division check"
  452. dividend_array = np.array([dividend]*5)
  453. quotient_array = np.array([quotient]*5)
  454. assert all(dividend_array // divisor == quotient_array), msg
  455. else:
  456. if IS_WASM:
  457. pytest.skip("fp errors don't work in wasm")
  458. with np.errstate(divide='raise', invalid='raise'):
  459. with pytest.raises(FloatingPointError):
  460. dividend // divisor
  461. def test_division_complex(self):
  462. # check that implementation is correct
  463. msg = "Complex division implementation check"
  464. x = np.array([1. + 1.*1j, 1. + .5*1j, 1. + 2.*1j], dtype=np.complex128)
  465. assert_almost_equal(x**2/x, x, err_msg=msg)
  466. # check overflow, underflow
  467. msg = "Complex division overflow/underflow check"
  468. x = np.array([1.e+110, 1.e-110], dtype=np.complex128)
  469. y = x**2/x
  470. assert_almost_equal(y/x, [1, 1], err_msg=msg)
  471. def test_zero_division_complex(self):
  472. with np.errstate(invalid="ignore", divide="ignore"):
  473. x = np.array([0.0], dtype=np.complex128)
  474. y = 1.0/x
  475. assert_(np.isinf(y)[0])
  476. y = complex(np.inf, np.nan)/x
  477. assert_(np.isinf(y)[0])
  478. y = complex(np.nan, np.inf)/x
  479. assert_(np.isinf(y)[0])
  480. y = complex(np.inf, np.inf)/x
  481. assert_(np.isinf(y)[0])
  482. y = 0.0/x
  483. assert_(np.isnan(y)[0])
  484. def test_floor_division_complex(self):
  485. # check that floor division, divmod and remainder raises type errors
  486. x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128)
  487. with pytest.raises(TypeError):
  488. x // 7
  489. with pytest.raises(TypeError):
  490. np.divmod(x, 7)
  491. with pytest.raises(TypeError):
  492. np.remainder(x, 7)
  493. def test_floor_division_signed_zero(self):
  494. # Check that the sign bit is correctly set when dividing positive and
  495. # negative zero by one.
  496. x = np.zeros(10)
  497. assert_equal(np.signbit(x//1), 0)
  498. assert_equal(np.signbit((-x)//1), 1)
  499. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  500. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  501. def test_floor_division_errors(self, dtype):
  502. fnan = np.array(np.nan, dtype=dtype)
  503. fone = np.array(1.0, dtype=dtype)
  504. fzer = np.array(0.0, dtype=dtype)
  505. finf = np.array(np.inf, dtype=dtype)
  506. # divide by zero error check
  507. with np.errstate(divide='raise', invalid='ignore'):
  508. assert_raises(FloatingPointError, np.floor_divide, fone, fzer)
  509. with np.errstate(divide='ignore', invalid='raise'):
  510. np.floor_divide(fone, fzer)
  511. # The following already contain a NaN and should not warn
  512. with np.errstate(all='raise'):
  513. np.floor_divide(fnan, fone)
  514. np.floor_divide(fone, fnan)
  515. np.floor_divide(fnan, fzer)
  516. np.floor_divide(fzer, fnan)
  517. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  518. def test_floor_division_corner_cases(self, dtype):
  519. # test corner cases like 1.0//0.0 for errors and return vals
  520. x = np.zeros(10, dtype=dtype)
  521. y = np.ones(10, dtype=dtype)
  522. fnan = np.array(np.nan, dtype=dtype)
  523. fone = np.array(1.0, dtype=dtype)
  524. fzer = np.array(0.0, dtype=dtype)
  525. finf = np.array(np.inf, dtype=dtype)
  526. with suppress_warnings() as sup:
  527. sup.filter(RuntimeWarning, "invalid value encountered in floor_divide")
  528. div = np.floor_divide(fnan, fone)
  529. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  530. div = np.floor_divide(fone, fnan)
  531. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  532. div = np.floor_divide(fnan, fzer)
  533. assert(np.isnan(div)), "dt: %s, div: %s" % (dt, div)
  534. # verify 1.0//0.0 computations return inf
  535. with np.errstate(divide='ignore'):
  536. z = np.floor_divide(y, x)
  537. assert_(np.isinf(z).all())
  538. def floor_divide_and_remainder(x, y):
  539. return (np.floor_divide(x, y), np.remainder(x, y))
  540. def _signs(dt):
  541. if dt in np.typecodes['UnsignedInteger']:
  542. return (+1,)
  543. else:
  544. return (+1, -1)
  545. class TestRemainder:
  546. def test_remainder_basic(self):
  547. dt = np.typecodes['AllInteger'] + np.typecodes['Float']
  548. for op in [floor_divide_and_remainder, np.divmod]:
  549. for dt1, dt2 in itertools.product(dt, dt):
  550. for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
  551. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  552. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  553. a = np.array(sg1*71, dtype=dt1)
  554. b = np.array(sg2*19, dtype=dt2)
  555. div, rem = op(a, b)
  556. assert_equal(div*b + rem, a, err_msg=msg)
  557. if sg2 == -1:
  558. assert_(b < rem <= 0, msg)
  559. else:
  560. assert_(b > rem >= 0, msg)
  561. def test_float_remainder_exact(self):
  562. # test that float results are exact for small integers. This also
  563. # holds for the same integers scaled by powers of two.
  564. nlst = list(range(-127, 0))
  565. plst = list(range(1, 128))
  566. dividend = nlst + [0] + plst
  567. divisor = nlst + plst
  568. arg = list(itertools.product(dividend, divisor))
  569. tgt = list(divmod(*t) for t in arg)
  570. a, b = np.array(arg, dtype=int).T
  571. # convert exact integer results from Python to float so that
  572. # signed zero can be used, it is checked.
  573. tgtdiv, tgtrem = np.array(tgt, dtype=float).T
  574. tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
  575. tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
  576. for op in [floor_divide_and_remainder, np.divmod]:
  577. for dt in np.typecodes['Float']:
  578. msg = 'op: %s, dtype: %s' % (op.__name__, dt)
  579. fa = a.astype(dt)
  580. fb = b.astype(dt)
  581. div, rem = op(fa, fb)
  582. assert_equal(div, tgtdiv, err_msg=msg)
  583. assert_equal(rem, tgtrem, err_msg=msg)
  584. def test_float_remainder_roundoff(self):
  585. # gh-6127
  586. dt = np.typecodes['Float']
  587. for op in [floor_divide_and_remainder, np.divmod]:
  588. for dt1, dt2 in itertools.product(dt, dt):
  589. for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
  590. fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
  591. msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
  592. a = np.array(sg1*78*6e-8, dtype=dt1)
  593. b = np.array(sg2*6e-8, dtype=dt2)
  594. div, rem = op(a, b)
  595. # Equal assertion should hold when fmod is used
  596. assert_equal(div*b + rem, a, err_msg=msg)
  597. if sg2 == -1:
  598. assert_(b < rem <= 0, msg)
  599. else:
  600. assert_(b > rem >= 0, msg)
  601. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  602. @pytest.mark.xfail(sys.platform.startswith("darwin"),
  603. reason="MacOS seems to not give the correct 'invalid' warning for "
  604. "`fmod`. Hopefully, others always do.")
  605. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  606. def test_float_divmod_errors(self, dtype):
  607. # Check valid errors raised for divmod and remainder
  608. fzero = np.array(0.0, dtype=dtype)
  609. fone = np.array(1.0, dtype=dtype)
  610. finf = np.array(np.inf, dtype=dtype)
  611. fnan = np.array(np.nan, dtype=dtype)
  612. # since divmod is combination of both remainder and divide
  613. # ops it will set both dividebyzero and invalid flags
  614. with np.errstate(divide='raise', invalid='ignore'):
  615. assert_raises(FloatingPointError, np.divmod, fone, fzero)
  616. with np.errstate(divide='ignore', invalid='raise'):
  617. assert_raises(FloatingPointError, np.divmod, fone, fzero)
  618. with np.errstate(invalid='raise'):
  619. assert_raises(FloatingPointError, np.divmod, fzero, fzero)
  620. with np.errstate(invalid='raise'):
  621. assert_raises(FloatingPointError, np.divmod, finf, finf)
  622. with np.errstate(divide='ignore', invalid='raise'):
  623. assert_raises(FloatingPointError, np.divmod, finf, fzero)
  624. with np.errstate(divide='raise', invalid='ignore'):
  625. # inf / 0 does not set any flags, only the modulo creates a NaN
  626. np.divmod(finf, fzero)
  627. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  628. @pytest.mark.xfail(sys.platform.startswith("darwin"),
  629. reason="MacOS seems to not give the correct 'invalid' warning for "
  630. "`fmod`. Hopefully, others always do.")
  631. @pytest.mark.parametrize('dtype', np.typecodes['Float'])
  632. @pytest.mark.parametrize('fn', [np.fmod, np.remainder])
  633. def test_float_remainder_errors(self, dtype, fn):
  634. fzero = np.array(0.0, dtype=dtype)
  635. fone = np.array(1.0, dtype=dtype)
  636. finf = np.array(np.inf, dtype=dtype)
  637. fnan = np.array(np.nan, dtype=dtype)
  638. # The following already contain a NaN and should not warn.
  639. with np.errstate(all='raise'):
  640. with pytest.raises(FloatingPointError,
  641. match="invalid value"):
  642. fn(fone, fzero)
  643. fn(fnan, fzero)
  644. fn(fzero, fnan)
  645. fn(fone, fnan)
  646. fn(fnan, fone)
  647. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  648. def test_float_remainder_overflow(self):
  649. a = np.finfo(np.float64).tiny
  650. with np.errstate(over='ignore', invalid='ignore'):
  651. div, mod = np.divmod(4, a)
  652. np.isinf(div)
  653. assert_(mod == 0)
  654. with np.errstate(over='raise', invalid='ignore'):
  655. assert_raises(FloatingPointError, np.divmod, 4, a)
  656. with np.errstate(invalid='raise', over='ignore'):
  657. assert_raises(FloatingPointError, np.divmod, 4, a)
  658. def test_float_divmod_corner_cases(self):
  659. # check nan cases
  660. for dt in np.typecodes['Float']:
  661. fnan = np.array(np.nan, dtype=dt)
  662. fone = np.array(1.0, dtype=dt)
  663. fzer = np.array(0.0, dtype=dt)
  664. finf = np.array(np.inf, dtype=dt)
  665. with suppress_warnings() as sup:
  666. sup.filter(RuntimeWarning, "invalid value encountered in divmod")
  667. sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
  668. div, rem = np.divmod(fone, fzer)
  669. assert(np.isinf(div)), 'dt: %s, div: %s' % (dt, rem)
  670. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  671. div, rem = np.divmod(fzer, fzer)
  672. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  673. assert_(np.isnan(div)), 'dt: %s, rem: %s' % (dt, rem)
  674. div, rem = np.divmod(finf, finf)
  675. assert(np.isnan(div)), 'dt: %s, rem: %s' % (dt, rem)
  676. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  677. div, rem = np.divmod(finf, fzer)
  678. assert(np.isinf(div)), 'dt: %s, rem: %s' % (dt, rem)
  679. assert(np.isnan(rem)), 'dt: %s, rem: %s' % (dt, rem)
  680. div, rem = np.divmod(fnan, fone)
  681. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  682. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  683. div, rem = np.divmod(fone, fnan)
  684. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  685. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  686. div, rem = np.divmod(fnan, fzer)
  687. assert(np.isnan(rem)), "dt: %s, rem: %s" % (dt, rem)
  688. assert(np.isnan(div)), "dt: %s, rem: %s" % (dt, rem)
  689. def test_float_remainder_corner_cases(self):
  690. # Check remainder magnitude.
  691. for dt in np.typecodes['Float']:
  692. fone = np.array(1.0, dtype=dt)
  693. fzer = np.array(0.0, dtype=dt)
  694. fnan = np.array(np.nan, dtype=dt)
  695. b = np.array(1.0, dtype=dt)
  696. a = np.nextafter(np.array(0.0, dtype=dt), -b)
  697. rem = np.remainder(a, b)
  698. assert_(rem <= b, 'dt: %s' % dt)
  699. rem = np.remainder(-a, -b)
  700. assert_(rem >= -b, 'dt: %s' % dt)
  701. # Check nans, inf
  702. with suppress_warnings() as sup:
  703. sup.filter(RuntimeWarning, "invalid value encountered in remainder")
  704. sup.filter(RuntimeWarning, "invalid value encountered in fmod")
  705. for dt in np.typecodes['Float']:
  706. fone = np.array(1.0, dtype=dt)
  707. fzer = np.array(0.0, dtype=dt)
  708. finf = np.array(np.inf, dtype=dt)
  709. fnan = np.array(np.nan, dtype=dt)
  710. rem = np.remainder(fone, fzer)
  711. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  712. # MSVC 2008 returns NaN here, so disable the check.
  713. #rem = np.remainder(fone, finf)
  714. #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
  715. rem = np.remainder(finf, fone)
  716. fmod = np.fmod(finf, fone)
  717. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  718. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  719. rem = np.remainder(finf, finf)
  720. fmod = np.fmod(finf, fone)
  721. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  722. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  723. rem = np.remainder(finf, fzer)
  724. fmod = np.fmod(finf, fzer)
  725. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  726. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  727. rem = np.remainder(fone, fnan)
  728. fmod = np.fmod(fone, fnan)
  729. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  730. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
  731. rem = np.remainder(fnan, fzer)
  732. fmod = np.fmod(fnan, fzer)
  733. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  734. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
  735. rem = np.remainder(fnan, fone)
  736. fmod = np.fmod(fnan, fone)
  737. assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
  738. assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
  739. class TestDivisionIntegerOverflowsAndDivideByZero:
  740. result_type = namedtuple('result_type',
  741. ['nocast', 'casted'])
  742. helper_lambdas = {
  743. 'zero': lambda dtype: 0,
  744. 'min': lambda dtype: np.iinfo(dtype).min,
  745. 'neg_min': lambda dtype: -np.iinfo(dtype).min,
  746. 'min-zero': lambda dtype: (np.iinfo(dtype).min, 0),
  747. 'neg_min-zero': lambda dtype: (-np.iinfo(dtype).min, 0),
  748. }
  749. overflow_results = {
  750. np.remainder: result_type(
  751. helper_lambdas['zero'], helper_lambdas['zero']),
  752. np.fmod: result_type(
  753. helper_lambdas['zero'], helper_lambdas['zero']),
  754. operator.mod: result_type(
  755. helper_lambdas['zero'], helper_lambdas['zero']),
  756. operator.floordiv: result_type(
  757. helper_lambdas['min'], helper_lambdas['neg_min']),
  758. np.floor_divide: result_type(
  759. helper_lambdas['min'], helper_lambdas['neg_min']),
  760. np.divmod: result_type(
  761. helper_lambdas['min-zero'], helper_lambdas['neg_min-zero'])
  762. }
  763. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  764. @pytest.mark.parametrize("dtype", np.typecodes["Integer"])
  765. def test_signed_division_overflow(self, dtype):
  766. to_check = interesting_binop_operands(np.iinfo(dtype).min, -1, dtype)
  767. for op1, op2, extractor, operand_identifier in to_check:
  768. with pytest.warns(RuntimeWarning, match="overflow encountered"):
  769. res = op1 // op2
  770. assert res.dtype == op1.dtype
  771. assert extractor(res) == np.iinfo(op1.dtype).min
  772. # Remainder is well defined though, and does not warn:
  773. res = op1 % op2
  774. assert res.dtype == op1.dtype
  775. assert extractor(res) == 0
  776. # Check fmod as well:
  777. res = np.fmod(op1, op2)
  778. assert extractor(res) == 0
  779. # Divmod warns for the division part:
  780. with pytest.warns(RuntimeWarning, match="overflow encountered"):
  781. res1, res2 = np.divmod(op1, op2)
  782. assert res1.dtype == res2.dtype == op1.dtype
  783. assert extractor(res1) == np.iinfo(op1.dtype).min
  784. assert extractor(res2) == 0
  785. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  786. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  787. def test_divide_by_zero(self, dtype):
  788. # Note that the return value cannot be well defined here, but NumPy
  789. # currently uses 0 consistently. This could be changed.
  790. to_check = interesting_binop_operands(1, 0, dtype)
  791. for op1, op2, extractor, operand_identifier in to_check:
  792. with pytest.warns(RuntimeWarning, match="divide by zero"):
  793. res = op1 // op2
  794. assert res.dtype == op1.dtype
  795. assert extractor(res) == 0
  796. with pytest.warns(RuntimeWarning, match="divide by zero"):
  797. res1, res2 = np.divmod(op1, op2)
  798. assert res1.dtype == res2.dtype == op1.dtype
  799. assert extractor(res1) == 0
  800. assert extractor(res2) == 0
  801. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  802. @pytest.mark.parametrize("dividend_dtype",
  803. np.sctypes['int'])
  804. @pytest.mark.parametrize("divisor_dtype",
  805. np.sctypes['int'])
  806. @pytest.mark.parametrize("operation",
  807. [np.remainder, np.fmod, np.divmod, np.floor_divide,
  808. operator.mod, operator.floordiv])
  809. @np.errstate(divide='warn', over='warn')
  810. def test_overflows(self, dividend_dtype, divisor_dtype, operation):
  811. # SIMD tries to perform the operation on as many elements as possible
  812. # that is a multiple of the register's size. We resort to the
  813. # default implementation for the leftover elements.
  814. # We try to cover all paths here.
  815. arrays = [np.array([np.iinfo(dividend_dtype).min]*i,
  816. dtype=dividend_dtype) for i in range(1, 129)]
  817. divisor = np.array([-1], dtype=divisor_dtype)
  818. # If dividend is a larger type than the divisor (`else` case),
  819. # then, result will be a larger type than dividend and will not
  820. # result in an overflow for `divmod` and `floor_divide`.
  821. if np.dtype(dividend_dtype).itemsize >= np.dtype(
  822. divisor_dtype).itemsize and operation in (
  823. np.divmod, np.floor_divide, operator.floordiv):
  824. with pytest.warns(
  825. RuntimeWarning,
  826. match="overflow encountered in"):
  827. result = operation(
  828. dividend_dtype(np.iinfo(dividend_dtype).min),
  829. divisor_dtype(-1)
  830. )
  831. assert result == self.overflow_results[operation].nocast(
  832. dividend_dtype)
  833. # Arrays
  834. for a in arrays:
  835. # In case of divmod, we need to flatten the result
  836. # column first as we get a column vector of quotient and
  837. # remainder and a normal flatten of the expected result.
  838. with pytest.warns(
  839. RuntimeWarning,
  840. match="overflow encountered in"):
  841. result = np.array(operation(a, divisor)).flatten('f')
  842. expected_array = np.array(
  843. [self.overflow_results[operation].nocast(
  844. dividend_dtype)]*len(a)).flatten()
  845. assert_array_equal(result, expected_array)
  846. else:
  847. # Scalars
  848. result = operation(
  849. dividend_dtype(np.iinfo(dividend_dtype).min),
  850. divisor_dtype(-1)
  851. )
  852. assert result == self.overflow_results[operation].casted(
  853. dividend_dtype)
  854. # Arrays
  855. for a in arrays:
  856. # See above comment on flatten
  857. result = np.array(operation(a, divisor)).flatten('f')
  858. expected_array = np.array(
  859. [self.overflow_results[operation].casted(
  860. dividend_dtype)]*len(a)).flatten()
  861. assert_array_equal(result, expected_array)
  862. class TestCbrt:
  863. def test_cbrt_scalar(self):
  864. assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5)
  865. def test_cbrt(self):
  866. x = np.array([1., 2., -3., np.inf, -np.inf])
  867. assert_almost_equal(np.cbrt(x**3), x)
  868. assert_(np.isnan(np.cbrt(np.nan)))
  869. assert_equal(np.cbrt(np.inf), np.inf)
  870. assert_equal(np.cbrt(-np.inf), -np.inf)
  871. class TestPower:
  872. def test_power_float(self):
  873. x = np.array([1., 2., 3.])
  874. assert_equal(x**0, [1., 1., 1.])
  875. assert_equal(x**1, x)
  876. assert_equal(x**2, [1., 4., 9.])
  877. y = x.copy()
  878. y **= 2
  879. assert_equal(y, [1., 4., 9.])
  880. assert_almost_equal(x**(-1), [1., 0.5, 1./3])
  881. assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
  882. for out, inp, msg in _gen_alignment_data(dtype=np.float32,
  883. type='unary',
  884. max_size=11):
  885. exp = [ncu.sqrt(i) for i in inp]
  886. assert_almost_equal(inp**(0.5), exp, err_msg=msg)
  887. np.sqrt(inp, out=out)
  888. assert_equal(out, exp, err_msg=msg)
  889. for out, inp, msg in _gen_alignment_data(dtype=np.float64,
  890. type='unary',
  891. max_size=7):
  892. exp = [ncu.sqrt(i) for i in inp]
  893. assert_almost_equal(inp**(0.5), exp, err_msg=msg)
  894. np.sqrt(inp, out=out)
  895. assert_equal(out, exp, err_msg=msg)
  896. def test_power_complex(self):
  897. x = np.array([1+2j, 2+3j, 3+4j])
  898. assert_equal(x**0, [1., 1., 1.])
  899. assert_equal(x**1, x)
  900. assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j])
  901. assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])
  902. assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])
  903. assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)])
  904. assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2])
  905. assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197,
  906. (-117-44j)/15625])
  907. assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j),
  908. ncu.sqrt(3+4j)])
  909. norm = 1./((x**14)[0])
  910. assert_almost_equal(x**14 * norm,
  911. [i * norm for i in [-76443+16124j, 23161315+58317492j,
  912. 5583548873 + 2465133864j]])
  913. # Ticket #836
  914. def assert_complex_equal(x, y):
  915. assert_array_equal(x.real, y.real)
  916. assert_array_equal(x.imag, y.imag)
  917. for z in [complex(0, np.inf), complex(1, np.inf)]:
  918. z = np.array([z], dtype=np.complex_)
  919. with np.errstate(invalid="ignore"):
  920. assert_complex_equal(z**1, z)
  921. assert_complex_equal(z**2, z*z)
  922. assert_complex_equal(z**3, z*z*z)
  923. def test_power_zero(self):
  924. # ticket #1271
  925. zero = np.array([0j])
  926. one = np.array([1+0j])
  927. cnan = np.array([complex(np.nan, np.nan)])
  928. # FIXME cinf not tested.
  929. #cinf = np.array([complex(np.inf, 0)])
  930. def assert_complex_equal(x, y):
  931. x, y = np.asarray(x), np.asarray(y)
  932. assert_array_equal(x.real, y.real)
  933. assert_array_equal(x.imag, y.imag)
  934. # positive powers
  935. for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
  936. assert_complex_equal(np.power(zero, p), zero)
  937. # zero power
  938. assert_complex_equal(np.power(zero, 0), one)
  939. with np.errstate(invalid="ignore"):
  940. assert_complex_equal(np.power(zero, 0+1j), cnan)
  941. # negative power
  942. for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
  943. assert_complex_equal(np.power(zero, -p), cnan)
  944. assert_complex_equal(np.power(zero, -1+0.2j), cnan)
  945. def test_fast_power(self):
  946. x = np.array([1, 2, 3], np.int16)
  947. res = x**2.0
  948. assert_((x**2.00001).dtype is res.dtype)
  949. assert_array_equal(res, [1, 4, 9])
  950. # check the inplace operation on the casted copy doesn't mess with x
  951. assert_(not np.may_share_memory(res, x))
  952. assert_array_equal(x, [1, 2, 3])
  953. # Check that the fast path ignores 1-element not 0-d arrays
  954. res = x ** np.array([[[2]]])
  955. assert_equal(res.shape, (1, 1, 3))
  956. def test_integer_power(self):
  957. a = np.array([15, 15], 'i8')
  958. b = np.power(a, a)
  959. assert_equal(b, [437893890380859375, 437893890380859375])
  960. def test_integer_power_with_integer_zero_exponent(self):
  961. dtypes = np.typecodes['Integer']
  962. for dt in dtypes:
  963. arr = np.arange(-10, 10, dtype=dt)
  964. assert_equal(np.power(arr, 0), np.ones_like(arr))
  965. dtypes = np.typecodes['UnsignedInteger']
  966. for dt in dtypes:
  967. arr = np.arange(10, dtype=dt)
  968. assert_equal(np.power(arr, 0), np.ones_like(arr))
  969. def test_integer_power_of_1(self):
  970. dtypes = np.typecodes['AllInteger']
  971. for dt in dtypes:
  972. arr = np.arange(10, dtype=dt)
  973. assert_equal(np.power(1, arr), np.ones_like(arr))
  974. def test_integer_power_of_zero(self):
  975. dtypes = np.typecodes['AllInteger']
  976. for dt in dtypes:
  977. arr = np.arange(1, 10, dtype=dt)
  978. assert_equal(np.power(0, arr), np.zeros_like(arr))
  979. def test_integer_to_negative_power(self):
  980. dtypes = np.typecodes['Integer']
  981. for dt in dtypes:
  982. a = np.array([0, 1, 2, 3], dtype=dt)
  983. b = np.array([0, 1, 2, -3], dtype=dt)
  984. one = np.array(1, dtype=dt)
  985. minusone = np.array(-1, dtype=dt)
  986. assert_raises(ValueError, np.power, a, b)
  987. assert_raises(ValueError, np.power, a, minusone)
  988. assert_raises(ValueError, np.power, one, b)
  989. assert_raises(ValueError, np.power, one, minusone)
  990. def test_float_to_inf_power(self):
  991. for dt in [np.float32, np.float64]:
  992. a = np.array([1, 1, 2, 2, -2, -2, np.inf, -np.inf], dt)
  993. b = np.array([np.inf, -np.inf, np.inf, -np.inf,
  994. np.inf, -np.inf, np.inf, -np.inf], dt)
  995. r = np.array([1, 1, np.inf, 0, np.inf, 0, np.inf, 0], dt)
  996. assert_equal(np.power(a, b), r)
  997. class TestFloat_power:
  998. def test_type_conversion(self):
  999. arg_type = '?bhilBHILefdgFDG'
  1000. res_type = 'ddddddddddddgDDG'
  1001. for dtin, dtout in zip(arg_type, res_type):
  1002. msg = "dtin: %s, dtout: %s" % (dtin, dtout)
  1003. arg = np.ones(1, dtype=dtin)
  1004. res = np.float_power(arg, arg)
  1005. assert_(res.dtype.name == np.dtype(dtout).name, msg)
  1006. class TestLog2:
  1007. @pytest.mark.parametrize('dt', ['f', 'd', 'g'])
  1008. def test_log2_values(self, dt):
  1009. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  1010. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1011. xf = np.array(x, dtype=dt)
  1012. yf = np.array(y, dtype=dt)
  1013. assert_almost_equal(np.log2(xf), yf)
  1014. @pytest.mark.parametrize("i", range(1, 65))
  1015. def test_log2_ints(self, i):
  1016. # a good log2 implementation should provide this,
  1017. # might fail on OS with bad libm
  1018. v = np.log2(2.**i)
  1019. assert_equal(v, float(i), err_msg='at exponent %d' % i)
  1020. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1021. def test_log2_special(self):
  1022. assert_equal(np.log2(1.), 0.)
  1023. assert_equal(np.log2(np.inf), np.inf)
  1024. assert_(np.isnan(np.log2(np.nan)))
  1025. with warnings.catch_warnings(record=True) as w:
  1026. warnings.filterwarnings('always', '', RuntimeWarning)
  1027. assert_(np.isnan(np.log2(-1.)))
  1028. assert_(np.isnan(np.log2(-np.inf)))
  1029. assert_equal(np.log2(0.), -np.inf)
  1030. assert_(w[0].category is RuntimeWarning)
  1031. assert_(w[1].category is RuntimeWarning)
  1032. assert_(w[2].category is RuntimeWarning)
  1033. class TestExp2:
  1034. def test_exp2_values(self):
  1035. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  1036. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1037. for dt in ['f', 'd', 'g']:
  1038. xf = np.array(x, dtype=dt)
  1039. yf = np.array(y, dtype=dt)
  1040. assert_almost_equal(np.exp2(yf), xf)
  1041. class TestLogAddExp2(_FilterInvalids):
  1042. # Need test for intermediate precisions
  1043. def test_logaddexp2_values(self):
  1044. x = [1, 2, 3, 4, 5]
  1045. y = [5, 4, 3, 2, 1]
  1046. z = [6, 6, 6, 6, 6]
  1047. for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
  1048. xf = np.log2(np.array(x, dtype=dt))
  1049. yf = np.log2(np.array(y, dtype=dt))
  1050. zf = np.log2(np.array(z, dtype=dt))
  1051. assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec_)
  1052. def test_logaddexp2_range(self):
  1053. x = [1000000, -1000000, 1000200, -1000200]
  1054. y = [1000200, -1000200, 1000000, -1000000]
  1055. z = [1000200, -1000000, 1000200, -1000000]
  1056. for dt in ['f', 'd', 'g']:
  1057. logxf = np.array(x, dtype=dt)
  1058. logyf = np.array(y, dtype=dt)
  1059. logzf = np.array(z, dtype=dt)
  1060. assert_almost_equal(np.logaddexp2(logxf, logyf), logzf)
  1061. def test_inf(self):
  1062. inf = np.inf
  1063. x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
  1064. y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
  1065. z = [inf, inf, inf, -inf, inf, inf, 1, 1]
  1066. with np.errstate(invalid='raise'):
  1067. for dt in ['f', 'd', 'g']:
  1068. logxf = np.array(x, dtype=dt)
  1069. logyf = np.array(y, dtype=dt)
  1070. logzf = np.array(z, dtype=dt)
  1071. assert_equal(np.logaddexp2(logxf, logyf), logzf)
  1072. def test_nan(self):
  1073. assert_(np.isnan(np.logaddexp2(np.nan, np.inf)))
  1074. assert_(np.isnan(np.logaddexp2(np.inf, np.nan)))
  1075. assert_(np.isnan(np.logaddexp2(np.nan, 0)))
  1076. assert_(np.isnan(np.logaddexp2(0, np.nan)))
  1077. assert_(np.isnan(np.logaddexp2(np.nan, np.nan)))
  1078. def test_reduce(self):
  1079. assert_equal(np.logaddexp2.identity, -np.inf)
  1080. assert_equal(np.logaddexp2.reduce([]), -np.inf)
  1081. assert_equal(np.logaddexp2.reduce([-np.inf]), -np.inf)
  1082. assert_equal(np.logaddexp2.reduce([-np.inf, 0]), 0)
  1083. class TestLog:
  1084. def test_log_values(self):
  1085. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  1086. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1087. for dt in ['f', 'd', 'g']:
  1088. log2_ = 0.69314718055994530943
  1089. xf = np.array(x, dtype=dt)
  1090. yf = np.array(y, dtype=dt)*log2_
  1091. assert_almost_equal(np.log(xf), yf)
  1092. # test aliasing(issue #17761)
  1093. x = np.array([2, 0.937500, 3, 0.947500, 1.054697])
  1094. xf = np.log(x)
  1095. assert_almost_equal(np.log(x, out=x), xf)
  1096. # test log() of max for dtype does not raise
  1097. for dt in ['f', 'd', 'g']:
  1098. with np.errstate(all='raise'):
  1099. x = np.finfo(dt).max
  1100. np.log(x)
  1101. def test_log_strides(self):
  1102. np.random.seed(42)
  1103. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  1104. sizes = np.arange(2,100)
  1105. for ii in sizes:
  1106. x_f64 = np.float64(np.random.uniform(low=0.01, high=100.0,size=ii))
  1107. x_special = x_f64.copy()
  1108. x_special[3:-1:4] = 1.0
  1109. y_true = np.log(x_f64)
  1110. y_special = np.log(x_special)
  1111. for jj in strides:
  1112. assert_array_almost_equal_nulp(np.log(x_f64[::jj]), y_true[::jj], nulp=2)
  1113. assert_array_almost_equal_nulp(np.log(x_special[::jj]), y_special[::jj], nulp=2)
  1114. class TestExp:
  1115. def test_exp_values(self):
  1116. x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  1117. y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1118. for dt in ['f', 'd', 'g']:
  1119. log2_ = 0.69314718055994530943
  1120. xf = np.array(x, dtype=dt)
  1121. yf = np.array(y, dtype=dt)*log2_
  1122. assert_almost_equal(np.exp(yf), xf)
  1123. def test_exp_strides(self):
  1124. np.random.seed(42)
  1125. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  1126. sizes = np.arange(2,100)
  1127. for ii in sizes:
  1128. x_f64 = np.float64(np.random.uniform(low=0.01, high=709.1,size=ii))
  1129. y_true = np.exp(x_f64)
  1130. for jj in strides:
  1131. assert_array_almost_equal_nulp(np.exp(x_f64[::jj]), y_true[::jj], nulp=2)
  1132. class TestSpecialFloats:
  1133. def test_exp_values(self):
  1134. with np.errstate(under='raise', over='raise'):
  1135. x = [np.nan, np.nan, np.inf, 0.]
  1136. y = [np.nan, -np.nan, np.inf, -np.inf]
  1137. for dt in ['e', 'f', 'd', 'g']:
  1138. xf = np.array(x, dtype=dt)
  1139. yf = np.array(y, dtype=dt)
  1140. assert_equal(np.exp(yf), xf)
  1141. # See: https://github.com/numpy/numpy/issues/19192
  1142. @pytest.mark.xfail(
  1143. _glibc_older_than("2.17"),
  1144. reason="Older glibc versions may not raise appropriate FP exceptions"
  1145. )
  1146. def test_exp_exceptions(self):
  1147. with np.errstate(over='raise'):
  1148. assert_raises(FloatingPointError, np.exp, np.float16(11.0899))
  1149. assert_raises(FloatingPointError, np.exp, np.float32(100.))
  1150. assert_raises(FloatingPointError, np.exp, np.float32(1E19))
  1151. assert_raises(FloatingPointError, np.exp, np.float64(800.))
  1152. assert_raises(FloatingPointError, np.exp, np.float64(1E19))
  1153. with np.errstate(under='raise'):
  1154. assert_raises(FloatingPointError, np.exp, np.float16(-17.5))
  1155. assert_raises(FloatingPointError, np.exp, np.float32(-1000.))
  1156. assert_raises(FloatingPointError, np.exp, np.float32(-1E19))
  1157. assert_raises(FloatingPointError, np.exp, np.float64(-1000.))
  1158. assert_raises(FloatingPointError, np.exp, np.float64(-1E19))
  1159. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1160. def test_log_values(self):
  1161. with np.errstate(all='ignore'):
  1162. x = [np.nan, np.nan, np.inf, np.nan, -np.inf, np.nan]
  1163. y = [np.nan, -np.nan, np.inf, -np.inf, 0.0, -1.0]
  1164. y1p = [np.nan, -np.nan, np.inf, -np.inf, -1.0, -2.0]
  1165. for dt in ['e', 'f', 'd', 'g']:
  1166. xf = np.array(x, dtype=dt)
  1167. yf = np.array(y, dtype=dt)
  1168. yf1p = np.array(y1p, dtype=dt)
  1169. assert_equal(np.log(yf), xf)
  1170. assert_equal(np.log2(yf), xf)
  1171. assert_equal(np.log10(yf), xf)
  1172. assert_equal(np.log1p(yf1p), xf)
  1173. with np.errstate(divide='raise'):
  1174. for dt in ['e', 'f', 'd']:
  1175. assert_raises(FloatingPointError, np.log,
  1176. np.array(0.0, dtype=dt))
  1177. assert_raises(FloatingPointError, np.log2,
  1178. np.array(0.0, dtype=dt))
  1179. assert_raises(FloatingPointError, np.log10,
  1180. np.array(0.0, dtype=dt))
  1181. assert_raises(FloatingPointError, np.log1p,
  1182. np.array(-1.0, dtype=dt))
  1183. with np.errstate(invalid='raise'):
  1184. for dt in ['e', 'f', 'd']:
  1185. assert_raises(FloatingPointError, np.log,
  1186. np.array(-np.inf, dtype=dt))
  1187. assert_raises(FloatingPointError, np.log,
  1188. np.array(-1.0, dtype=dt))
  1189. assert_raises(FloatingPointError, np.log2,
  1190. np.array(-np.inf, dtype=dt))
  1191. assert_raises(FloatingPointError, np.log2,
  1192. np.array(-1.0, dtype=dt))
  1193. assert_raises(FloatingPointError, np.log10,
  1194. np.array(-np.inf, dtype=dt))
  1195. assert_raises(FloatingPointError, np.log10,
  1196. np.array(-1.0, dtype=dt))
  1197. assert_raises(FloatingPointError, np.log1p,
  1198. np.array(-np.inf, dtype=dt))
  1199. assert_raises(FloatingPointError, np.log1p,
  1200. np.array(-2.0, dtype=dt))
  1201. # See https://github.com/numpy/numpy/issues/18005
  1202. with assert_no_warnings():
  1203. a = np.array(1e9, dtype='float32')
  1204. np.log(a)
  1205. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1206. def test_sincos_values(self):
  1207. with np.errstate(all='ignore'):
  1208. x = [np.nan, np.nan, np.nan, np.nan]
  1209. y = [np.nan, -np.nan, np.inf, -np.inf]
  1210. for dt in ['e', 'f', 'd', 'g']:
  1211. xf = np.array(x, dtype=dt)
  1212. yf = np.array(y, dtype=dt)
  1213. assert_equal(np.sin(yf), xf)
  1214. assert_equal(np.cos(yf), xf)
  1215. with np.errstate(invalid='raise'):
  1216. for callable in [np.sin, np.cos]:
  1217. for value in [np.inf, -np.inf]:
  1218. for dt in ['e', 'f', 'd']:
  1219. assert_raises(FloatingPointError, callable,
  1220. np.array([value], dtype=dt))
  1221. @pytest.mark.parametrize('dt', ['e', 'f', 'd', 'g'])
  1222. def test_sqrt_values(self, dt):
  1223. with np.errstate(all='ignore'):
  1224. x = [np.nan, np.nan, np.inf, np.nan, 0.]
  1225. y = [np.nan, -np.nan, np.inf, -np.inf, 0.]
  1226. xf = np.array(x, dtype=dt)
  1227. yf = np.array(y, dtype=dt)
  1228. assert_equal(np.sqrt(yf), xf)
  1229. # with np.errstate(invalid='raise'):
  1230. # assert_raises(
  1231. # FloatingPointError, np.sqrt, np.array(-100., dtype=dt)
  1232. # )
  1233. def test_abs_values(self):
  1234. x = [np.nan, np.nan, np.inf, np.inf, 0., 0., 1.0, 1.0]
  1235. y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0., -1.0, 1.0]
  1236. for dt in ['e', 'f', 'd', 'g']:
  1237. xf = np.array(x, dtype=dt)
  1238. yf = np.array(y, dtype=dt)
  1239. assert_equal(np.abs(yf), xf)
  1240. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1241. def test_square_values(self):
  1242. x = [np.nan, np.nan, np.inf, np.inf]
  1243. y = [np.nan, -np.nan, np.inf, -np.inf]
  1244. with np.errstate(all='ignore'):
  1245. for dt in ['e', 'f', 'd', 'g']:
  1246. xf = np.array(x, dtype=dt)
  1247. yf = np.array(y, dtype=dt)
  1248. assert_equal(np.square(yf), xf)
  1249. with np.errstate(over='raise'):
  1250. assert_raises(FloatingPointError, np.square,
  1251. np.array(1E3, dtype='e'))
  1252. assert_raises(FloatingPointError, np.square,
  1253. np.array(1E32, dtype='f'))
  1254. assert_raises(FloatingPointError, np.square,
  1255. np.array(1E200, dtype='d'))
  1256. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1257. def test_reciprocal_values(self):
  1258. with np.errstate(all='ignore'):
  1259. x = [np.nan, np.nan, 0.0, -0.0, np.inf, -np.inf]
  1260. y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0.]
  1261. for dt in ['e', 'f', 'd', 'g']:
  1262. xf = np.array(x, dtype=dt)
  1263. yf = np.array(y, dtype=dt)
  1264. assert_equal(np.reciprocal(yf), xf)
  1265. with np.errstate(divide='raise'):
  1266. for dt in ['e', 'f', 'd', 'g']:
  1267. assert_raises(FloatingPointError, np.reciprocal,
  1268. np.array(-0.0, dtype=dt))
  1269. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1270. def test_tan(self):
  1271. with np.errstate(all='ignore'):
  1272. in_ = [np.nan, -np.nan, 0.0, -0.0, np.inf, -np.inf]
  1273. out = [np.nan, np.nan, 0.0, -0.0, np.nan, np.nan]
  1274. for dt in ['e', 'f', 'd']:
  1275. in_arr = np.array(in_, dtype=dt)
  1276. out_arr = np.array(out, dtype=dt)
  1277. assert_equal(np.tan(in_arr), out_arr)
  1278. with np.errstate(invalid='raise'):
  1279. for dt in ['e', 'f', 'd']:
  1280. assert_raises(FloatingPointError, np.tan,
  1281. np.array(np.inf, dtype=dt))
  1282. assert_raises(FloatingPointError, np.tan,
  1283. np.array(-np.inf, dtype=dt))
  1284. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1285. def test_arcsincos(self):
  1286. with np.errstate(all='ignore'):
  1287. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1288. out = [np.nan, np.nan, np.nan, np.nan]
  1289. for dt in ['e', 'f', 'd']:
  1290. in_arr = np.array(in_, dtype=dt)
  1291. out_arr = np.array(out, dtype=dt)
  1292. assert_equal(np.arcsin(in_arr), out_arr)
  1293. assert_equal(np.arccos(in_arr), out_arr)
  1294. for callable in [np.arcsin, np.arccos]:
  1295. for value in [np.inf, -np.inf, 2.0, -2.0]:
  1296. for dt in ['e', 'f', 'd']:
  1297. with np.errstate(invalid='raise'):
  1298. assert_raises(FloatingPointError, callable,
  1299. np.array(value, dtype=dt))
  1300. def test_arctan(self):
  1301. with np.errstate(all='ignore'):
  1302. in_ = [np.nan, -np.nan]
  1303. out = [np.nan, np.nan]
  1304. for dt in ['e', 'f', 'd']:
  1305. in_arr = np.array(in_, dtype=dt)
  1306. out_arr = np.array(out, dtype=dt)
  1307. assert_equal(np.arctan(in_arr), out_arr)
  1308. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1309. def test_sinh(self):
  1310. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1311. out = [np.nan, np.nan, np.inf, -np.inf]
  1312. for dt in ['e', 'f', 'd']:
  1313. in_arr = np.array(in_, dtype=dt)
  1314. out_arr = np.array(out, dtype=dt)
  1315. assert_equal(np.sinh(in_arr), out_arr)
  1316. with np.errstate(over='raise'):
  1317. assert_raises(FloatingPointError, np.sinh,
  1318. np.array(12.0, dtype='e'))
  1319. assert_raises(FloatingPointError, np.sinh,
  1320. np.array(120.0, dtype='f'))
  1321. assert_raises(FloatingPointError, np.sinh,
  1322. np.array(1200.0, dtype='d'))
  1323. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1324. def test_cosh(self):
  1325. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1326. out = [np.nan, np.nan, np.inf, np.inf]
  1327. for dt in ['e', 'f', 'd']:
  1328. in_arr = np.array(in_, dtype=dt)
  1329. out_arr = np.array(out, dtype=dt)
  1330. assert_equal(np.cosh(in_arr), out_arr)
  1331. with np.errstate(over='raise'):
  1332. assert_raises(FloatingPointError, np.cosh,
  1333. np.array(12.0, dtype='e'))
  1334. assert_raises(FloatingPointError, np.cosh,
  1335. np.array(120.0, dtype='f'))
  1336. assert_raises(FloatingPointError, np.cosh,
  1337. np.array(1200.0, dtype='d'))
  1338. def test_tanh(self):
  1339. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1340. out = [np.nan, np.nan, 1.0, -1.0]
  1341. for dt in ['e', 'f', 'd']:
  1342. in_arr = np.array(in_, dtype=dt)
  1343. out_arr = np.array(out, dtype=dt)
  1344. assert_equal(np.tanh(in_arr), out_arr)
  1345. def test_arcsinh(self):
  1346. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1347. out = [np.nan, np.nan, np.inf, -np.inf]
  1348. for dt in ['e', 'f', 'd']:
  1349. in_arr = np.array(in_, dtype=dt)
  1350. out_arr = np.array(out, dtype=dt)
  1351. assert_equal(np.arcsinh(in_arr), out_arr)
  1352. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1353. def test_arccosh(self):
  1354. with np.errstate(all='ignore'):
  1355. in_ = [np.nan, -np.nan, np.inf, -np.inf, 1.0, 0.0]
  1356. out = [np.nan, np.nan, np.inf, np.nan, 0.0, np.nan]
  1357. for dt in ['e', 'f', 'd']:
  1358. in_arr = np.array(in_, dtype=dt)
  1359. out_arr = np.array(out, dtype=dt)
  1360. assert_equal(np.arccosh(in_arr), out_arr)
  1361. for value in [0.0, -np.inf]:
  1362. with np.errstate(invalid='raise'):
  1363. for dt in ['e', 'f', 'd']:
  1364. assert_raises(FloatingPointError, np.arccosh,
  1365. np.array(value, dtype=dt))
  1366. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1367. def test_arctanh(self):
  1368. with np.errstate(all='ignore'):
  1369. in_ = [np.nan, -np.nan, np.inf, -np.inf, 1.0, -1.0, 2.0]
  1370. out = [np.nan, np.nan, np.nan, np.nan, np.inf, -np.inf, np.nan]
  1371. for dt in ['e', 'f', 'd']:
  1372. in_arr = np.array(in_, dtype=dt)
  1373. out_arr = np.array(out, dtype=dt)
  1374. assert_equal(np.arctanh(in_arr), out_arr)
  1375. for value in [1.01, np.inf, -np.inf, 1.0, -1.0]:
  1376. with np.errstate(invalid='raise', divide='raise'):
  1377. for dt in ['e', 'f', 'd']:
  1378. assert_raises(FloatingPointError, np.arctanh,
  1379. np.array(value, dtype=dt))
  1380. # See: https://github.com/numpy/numpy/issues/20448
  1381. @pytest.mark.xfail(
  1382. _glibc_older_than("2.17"),
  1383. reason="Older glibc versions may not raise appropriate FP exceptions"
  1384. )
  1385. def test_exp2(self):
  1386. with np.errstate(all='ignore'):
  1387. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1388. out = [np.nan, np.nan, np.inf, 0.0]
  1389. for dt in ['e', 'f', 'd']:
  1390. in_arr = np.array(in_, dtype=dt)
  1391. out_arr = np.array(out, dtype=dt)
  1392. assert_equal(np.exp2(in_arr), out_arr)
  1393. for value in [2000.0, -2000.0]:
  1394. with np.errstate(over='raise', under='raise'):
  1395. for dt in ['e', 'f', 'd']:
  1396. assert_raises(FloatingPointError, np.exp2,
  1397. np.array(value, dtype=dt))
  1398. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1399. def test_expm1(self):
  1400. with np.errstate(all='ignore'):
  1401. in_ = [np.nan, -np.nan, np.inf, -np.inf]
  1402. out = [np.nan, np.nan, np.inf, -1.0]
  1403. for dt in ['e', 'f', 'd']:
  1404. in_arr = np.array(in_, dtype=dt)
  1405. out_arr = np.array(out, dtype=dt)
  1406. assert_equal(np.expm1(in_arr), out_arr)
  1407. for value in [200.0, 2000.0]:
  1408. with np.errstate(over='raise'):
  1409. for dt in ['e', 'f']:
  1410. assert_raises(FloatingPointError, np.expm1,
  1411. np.array(value, dtype=dt))
  1412. # test to ensure no spurious FP exceptions are raised due to SIMD
  1413. INF_INVALID_ERR = [
  1414. np.cos, np.sin, np.tan, np.arccos, np.arcsin, np.spacing, np.arctanh
  1415. ]
  1416. NEG_INVALID_ERR = [
  1417. np.log, np.log2, np.log10, np.log1p, np.sqrt, np.arccosh,
  1418. np.arctanh
  1419. ]
  1420. ONE_INVALID_ERR = [
  1421. np.arctanh,
  1422. ]
  1423. LTONE_INVALID_ERR = [
  1424. np.arccosh,
  1425. ]
  1426. BYZERO_ERR = [
  1427. np.log, np.log2, np.log10, np.reciprocal, np.arccosh
  1428. ]
  1429. @pytest.mark.parametrize("ufunc", UFUNCS_UNARY_FP)
  1430. @pytest.mark.parametrize("dtype", ('e', 'f', 'd'))
  1431. @pytest.mark.parametrize("data, escape", (
  1432. ([0.03], LTONE_INVALID_ERR),
  1433. ([0.03]*32, LTONE_INVALID_ERR),
  1434. # neg
  1435. ([-1.0], NEG_INVALID_ERR),
  1436. ([-1.0]*32, NEG_INVALID_ERR),
  1437. # flat
  1438. ([1.0], ONE_INVALID_ERR),
  1439. ([1.0]*32, ONE_INVALID_ERR),
  1440. # zero
  1441. ([0.0], BYZERO_ERR),
  1442. ([0.0]*32, BYZERO_ERR),
  1443. ([-0.0], BYZERO_ERR),
  1444. ([-0.0]*32, BYZERO_ERR),
  1445. # nan
  1446. ([0.5, 0.5, 0.5, np.nan], LTONE_INVALID_ERR),
  1447. ([0.5, 0.5, 0.5, np.nan]*32, LTONE_INVALID_ERR),
  1448. ([np.nan, 1.0, 1.0, 1.0], ONE_INVALID_ERR),
  1449. ([np.nan, 1.0, 1.0, 1.0]*32, ONE_INVALID_ERR),
  1450. ([np.nan], []),
  1451. ([np.nan]*32, []),
  1452. # inf
  1453. ([0.5, 0.5, 0.5, np.inf], INF_INVALID_ERR + LTONE_INVALID_ERR),
  1454. ([0.5, 0.5, 0.5, np.inf]*32, INF_INVALID_ERR + LTONE_INVALID_ERR),
  1455. ([np.inf, 1.0, 1.0, 1.0], INF_INVALID_ERR),
  1456. ([np.inf, 1.0, 1.0, 1.0]*32, INF_INVALID_ERR),
  1457. ([np.inf], INF_INVALID_ERR),
  1458. ([np.inf]*32, INF_INVALID_ERR),
  1459. # ninf
  1460. ([0.5, 0.5, 0.5, -np.inf],
  1461. NEG_INVALID_ERR + INF_INVALID_ERR + LTONE_INVALID_ERR),
  1462. ([0.5, 0.5, 0.5, -np.inf]*32,
  1463. NEG_INVALID_ERR + INF_INVALID_ERR + LTONE_INVALID_ERR),
  1464. ([-np.inf, 1.0, 1.0, 1.0], NEG_INVALID_ERR + INF_INVALID_ERR),
  1465. ([-np.inf, 1.0, 1.0, 1.0]*32, NEG_INVALID_ERR + INF_INVALID_ERR),
  1466. ([-np.inf], NEG_INVALID_ERR + INF_INVALID_ERR),
  1467. ([-np.inf]*32, NEG_INVALID_ERR + INF_INVALID_ERR),
  1468. ))
  1469. def test_unary_spurious_fpexception(self, ufunc, dtype, data, escape):
  1470. if escape and ufunc in escape:
  1471. return
  1472. # FIXME: NAN raises FP invalid exception:
  1473. # - ceil/float16 on MSVC:32-bit
  1474. # - spacing/float16 on almost all platforms
  1475. if ufunc in (np.spacing, np.ceil) and dtype == 'e':
  1476. return
  1477. array = np.array(data, dtype=dtype)
  1478. with assert_no_warnings():
  1479. ufunc(array)
  1480. class TestFPClass:
  1481. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  1482. def test_fpclass(self, stride):
  1483. 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')
  1484. 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')
  1485. nan = np.array([True, True, False, False, False, False, False, False, False, False])
  1486. inf = np.array([False, False, True, True, False, False, False, False, False, False])
  1487. sign = np.array([False, True, False, True, True, False, True, False, False, True])
  1488. finite = np.array([False, False, False, False, True, True, True, True, True, True])
  1489. assert_equal(np.isnan(arr_f32[::stride]), nan[::stride])
  1490. assert_equal(np.isnan(arr_f64[::stride]), nan[::stride])
  1491. assert_equal(np.isinf(arr_f32[::stride]), inf[::stride])
  1492. assert_equal(np.isinf(arr_f64[::stride]), inf[::stride])
  1493. assert_equal(np.signbit(arr_f32[::stride]), sign[::stride])
  1494. assert_equal(np.signbit(arr_f64[::stride]), sign[::stride])
  1495. assert_equal(np.isfinite(arr_f32[::stride]), finite[::stride])
  1496. assert_equal(np.isfinite(arr_f64[::stride]), finite[::stride])
  1497. class TestLDExp:
  1498. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  1499. @pytest.mark.parametrize("dtype", ['f', 'd'])
  1500. def test_ldexp(self, dtype, stride):
  1501. mant = np.array([0.125, 0.25, 0.5, 1., 1., 2., 4., 8.], dtype=dtype)
  1502. exp = np.array([3, 2, 1, 0, 0, -1, -2, -3], dtype='i')
  1503. out = np.zeros(8, dtype=dtype)
  1504. assert_equal(np.ldexp(mant[::stride], exp[::stride], out=out[::stride]), np.ones(8, dtype=dtype)[::stride])
  1505. assert_equal(out[::stride], np.ones(8, dtype=dtype)[::stride])
  1506. class TestFRExp:
  1507. @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
  1508. @pytest.mark.parametrize("dtype", ['f', 'd'])
  1509. @pytest.mark.skipif(not sys.platform.startswith('linux'),
  1510. reason="np.frexp gives different answers for NAN/INF on windows and linux")
  1511. def test_frexp(self, dtype, stride):
  1512. arr = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 1.0, -1.0], dtype=dtype)
  1513. mant_true = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 0.5, -0.5], dtype=dtype)
  1514. exp_true = np.array([0, 0, 0, 0, 0, 0, 1, 1], dtype='i')
  1515. out_mant = np.ones(8, dtype=dtype)
  1516. out_exp = 2*np.ones(8, dtype='i')
  1517. mant, exp = np.frexp(arr[::stride], out=(out_mant[::stride], out_exp[::stride]))
  1518. assert_equal(mant_true[::stride], mant)
  1519. assert_equal(exp_true[::stride], exp)
  1520. assert_equal(out_mant[::stride], mant_true[::stride])
  1521. assert_equal(out_exp[::stride], exp_true[::stride])
  1522. # func : [maxulperror, low, high]
  1523. avx_ufuncs = {'sqrt' :[1, 0., 100.],
  1524. 'absolute' :[0, -100., 100.],
  1525. 'reciprocal' :[1, 1., 100.],
  1526. 'square' :[1, -100., 100.],
  1527. 'rint' :[0, -100., 100.],
  1528. 'floor' :[0, -100., 100.],
  1529. 'ceil' :[0, -100., 100.],
  1530. 'trunc' :[0, -100., 100.]}
  1531. class TestAVXUfuncs:
  1532. def test_avx_based_ufunc(self):
  1533. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  1534. np.random.seed(42)
  1535. for func, prop in avx_ufuncs.items():
  1536. maxulperr = prop[0]
  1537. minval = prop[1]
  1538. maxval = prop[2]
  1539. # various array sizes to ensure masking in AVX is tested
  1540. for size in range(1,32):
  1541. myfunc = getattr(np, func)
  1542. x_f32 = np.float32(np.random.uniform(low=minval, high=maxval,
  1543. size=size))
  1544. x_f64 = np.float64(x_f32)
  1545. x_f128 = np.longdouble(x_f32)
  1546. y_true128 = myfunc(x_f128)
  1547. if maxulperr == 0:
  1548. assert_equal(myfunc(x_f32), np.float32(y_true128))
  1549. assert_equal(myfunc(x_f64), np.float64(y_true128))
  1550. else:
  1551. assert_array_max_ulp(myfunc(x_f32), np.float32(y_true128),
  1552. maxulp=maxulperr)
  1553. assert_array_max_ulp(myfunc(x_f64), np.float64(y_true128),
  1554. maxulp=maxulperr)
  1555. # various strides to test gather instruction
  1556. if size > 1:
  1557. y_true32 = myfunc(x_f32)
  1558. y_true64 = myfunc(x_f64)
  1559. for jj in strides:
  1560. assert_equal(myfunc(x_f64[::jj]), y_true64[::jj])
  1561. assert_equal(myfunc(x_f32[::jj]), y_true32[::jj])
  1562. class TestAVXFloat32Transcendental:
  1563. def test_exp_float32(self):
  1564. np.random.seed(42)
  1565. x_f32 = np.float32(np.random.uniform(low=0.0,high=88.1,size=1000000))
  1566. x_f64 = np.float64(x_f32)
  1567. assert_array_max_ulp(np.exp(x_f32), np.float32(np.exp(x_f64)), maxulp=3)
  1568. def test_log_float32(self):
  1569. np.random.seed(42)
  1570. x_f32 = np.float32(np.random.uniform(low=0.0,high=1000,size=1000000))
  1571. x_f64 = np.float64(x_f32)
  1572. assert_array_max_ulp(np.log(x_f32), np.float32(np.log(x_f64)), maxulp=4)
  1573. def test_sincos_float32(self):
  1574. np.random.seed(42)
  1575. N = 1000000
  1576. M = np.int_(N/20)
  1577. index = np.random.randint(low=0, high=N, size=M)
  1578. x_f32 = np.float32(np.random.uniform(low=-100.,high=100.,size=N))
  1579. if not _glibc_older_than("2.17"):
  1580. # test coverage for elements > 117435.992f for which glibc is used
  1581. # this is known to be problematic on old glibc, so skip it there
  1582. x_f32[index] = np.float32(10E+10*np.random.rand(M))
  1583. x_f64 = np.float64(x_f32)
  1584. assert_array_max_ulp(np.sin(x_f32), np.float32(np.sin(x_f64)), maxulp=2)
  1585. assert_array_max_ulp(np.cos(x_f32), np.float32(np.cos(x_f64)), maxulp=2)
  1586. # test aliasing(issue #17761)
  1587. tx_f32 = x_f32.copy()
  1588. assert_array_max_ulp(np.sin(x_f32, out=x_f32), np.float32(np.sin(x_f64)), maxulp=2)
  1589. assert_array_max_ulp(np.cos(tx_f32, out=tx_f32), np.float32(np.cos(x_f64)), maxulp=2)
  1590. def test_strided_float32(self):
  1591. np.random.seed(42)
  1592. strides = np.array([-4,-3,-2,-1,1,2,3,4])
  1593. sizes = np.arange(2,100)
  1594. for ii in sizes:
  1595. x_f32 = np.float32(np.random.uniform(low=0.01,high=88.1,size=ii))
  1596. x_f32_large = x_f32.copy()
  1597. x_f32_large[3:-1:4] = 120000.0
  1598. exp_true = np.exp(x_f32)
  1599. log_true = np.log(x_f32)
  1600. sin_true = np.sin(x_f32_large)
  1601. cos_true = np.cos(x_f32_large)
  1602. for jj in strides:
  1603. assert_array_almost_equal_nulp(np.exp(x_f32[::jj]), exp_true[::jj], nulp=2)
  1604. assert_array_almost_equal_nulp(np.log(x_f32[::jj]), log_true[::jj], nulp=2)
  1605. assert_array_almost_equal_nulp(np.sin(x_f32_large[::jj]), sin_true[::jj], nulp=2)
  1606. assert_array_almost_equal_nulp(np.cos(x_f32_large[::jj]), cos_true[::jj], nulp=2)
  1607. class TestLogAddExp(_FilterInvalids):
  1608. def test_logaddexp_values(self):
  1609. x = [1, 2, 3, 4, 5]
  1610. y = [5, 4, 3, 2, 1]
  1611. z = [6, 6, 6, 6, 6]
  1612. for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
  1613. xf = np.log(np.array(x, dtype=dt))
  1614. yf = np.log(np.array(y, dtype=dt))
  1615. zf = np.log(np.array(z, dtype=dt))
  1616. assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_)
  1617. def test_logaddexp_range(self):
  1618. x = [1000000, -1000000, 1000200, -1000200]
  1619. y = [1000200, -1000200, 1000000, -1000000]
  1620. z = [1000200, -1000000, 1000200, -1000000]
  1621. for dt in ['f', 'd', 'g']:
  1622. logxf = np.array(x, dtype=dt)
  1623. logyf = np.array(y, dtype=dt)
  1624. logzf = np.array(z, dtype=dt)
  1625. assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
  1626. def test_inf(self):
  1627. inf = np.inf
  1628. x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
  1629. y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
  1630. z = [inf, inf, inf, -inf, inf, inf, 1, 1]
  1631. with np.errstate(invalid='raise'):
  1632. for dt in ['f', 'd', 'g']:
  1633. logxf = np.array(x, dtype=dt)
  1634. logyf = np.array(y, dtype=dt)
  1635. logzf = np.array(z, dtype=dt)
  1636. assert_equal(np.logaddexp(logxf, logyf), logzf)
  1637. def test_nan(self):
  1638. assert_(np.isnan(np.logaddexp(np.nan, np.inf)))
  1639. assert_(np.isnan(np.logaddexp(np.inf, np.nan)))
  1640. assert_(np.isnan(np.logaddexp(np.nan, 0)))
  1641. assert_(np.isnan(np.logaddexp(0, np.nan)))
  1642. assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
  1643. def test_reduce(self):
  1644. assert_equal(np.logaddexp.identity, -np.inf)
  1645. assert_equal(np.logaddexp.reduce([]), -np.inf)
  1646. class TestLog1p:
  1647. def test_log1p(self):
  1648. assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))
  1649. assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6))
  1650. def test_special(self):
  1651. with np.errstate(invalid="ignore", divide="ignore"):
  1652. assert_equal(ncu.log1p(np.nan), np.nan)
  1653. assert_equal(ncu.log1p(np.inf), np.inf)
  1654. assert_equal(ncu.log1p(-1.), -np.inf)
  1655. assert_equal(ncu.log1p(-2.), np.nan)
  1656. assert_equal(ncu.log1p(-np.inf), np.nan)
  1657. class TestExpm1:
  1658. def test_expm1(self):
  1659. assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1)
  1660. assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1)
  1661. def test_special(self):
  1662. assert_equal(ncu.expm1(np.inf), np.inf)
  1663. assert_equal(ncu.expm1(0.), 0.)
  1664. assert_equal(ncu.expm1(-0.), -0.)
  1665. assert_equal(ncu.expm1(np.inf), np.inf)
  1666. assert_equal(ncu.expm1(-np.inf), -1.)
  1667. def test_complex(self):
  1668. x = np.asarray(1e-12)
  1669. assert_allclose(x, ncu.expm1(x))
  1670. x = x.astype(np.complex128)
  1671. assert_allclose(x, ncu.expm1(x))
  1672. class TestHypot:
  1673. def test_simple(self):
  1674. assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2))
  1675. assert_almost_equal(ncu.hypot(0, 0), 0)
  1676. def test_reduce(self):
  1677. assert_almost_equal(ncu.hypot.reduce([3.0, 4.0]), 5.0)
  1678. assert_almost_equal(ncu.hypot.reduce([3.0, 4.0, 0]), 5.0)
  1679. assert_almost_equal(ncu.hypot.reduce([9.0, 12.0, 20.0]), 25.0)
  1680. assert_equal(ncu.hypot.reduce([]), 0.0)
  1681. def assert_hypot_isnan(x, y):
  1682. with np.errstate(invalid='ignore'):
  1683. assert_(np.isnan(ncu.hypot(x, y)),
  1684. "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y)))
  1685. def assert_hypot_isinf(x, y):
  1686. with np.errstate(invalid='ignore'):
  1687. assert_(np.isinf(ncu.hypot(x, y)),
  1688. "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
  1689. class TestHypotSpecialValues:
  1690. def test_nan_outputs(self):
  1691. assert_hypot_isnan(np.nan, np.nan)
  1692. assert_hypot_isnan(np.nan, 1)
  1693. def test_nan_outputs2(self):
  1694. assert_hypot_isinf(np.nan, np.inf)
  1695. assert_hypot_isinf(np.inf, np.nan)
  1696. assert_hypot_isinf(np.inf, 0)
  1697. assert_hypot_isinf(0, np.inf)
  1698. assert_hypot_isinf(np.inf, np.inf)
  1699. assert_hypot_isinf(np.inf, 23.0)
  1700. def test_no_fpe(self):
  1701. assert_no_warnings(ncu.hypot, np.inf, 0)
  1702. def assert_arctan2_isnan(x, y):
  1703. assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y)))
  1704. def assert_arctan2_ispinf(x, y):
  1705. 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)))
  1706. def assert_arctan2_isninf(x, y):
  1707. 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)))
  1708. def assert_arctan2_ispzero(x, y):
  1709. 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)))
  1710. def assert_arctan2_isnzero(x, y):
  1711. 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)))
  1712. class TestArctan2SpecialValues:
  1713. def test_one_one(self):
  1714. # atan2(1, 1) returns pi/4.
  1715. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi)
  1716. assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi)
  1717. assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi)
  1718. def test_zero_nzero(self):
  1719. # atan2(+-0, -0) returns +-pi.
  1720. assert_almost_equal(ncu.arctan2(np.PZERO, np.NZERO), np.pi)
  1721. assert_almost_equal(ncu.arctan2(np.NZERO, np.NZERO), -np.pi)
  1722. def test_zero_pzero(self):
  1723. # atan2(+-0, +0) returns +-0.
  1724. assert_arctan2_ispzero(np.PZERO, np.PZERO)
  1725. assert_arctan2_isnzero(np.NZERO, np.PZERO)
  1726. def test_zero_negative(self):
  1727. # atan2(+-0, x) returns +-pi for x < 0.
  1728. assert_almost_equal(ncu.arctan2(np.PZERO, -1), np.pi)
  1729. assert_almost_equal(ncu.arctan2(np.NZERO, -1), -np.pi)
  1730. def test_zero_positive(self):
  1731. # atan2(+-0, x) returns +-0 for x > 0.
  1732. assert_arctan2_ispzero(np.PZERO, 1)
  1733. assert_arctan2_isnzero(np.NZERO, 1)
  1734. def test_positive_zero(self):
  1735. # atan2(y, +-0) returns +pi/2 for y > 0.
  1736. assert_almost_equal(ncu.arctan2(1, np.PZERO), 0.5 * np.pi)
  1737. assert_almost_equal(ncu.arctan2(1, np.NZERO), 0.5 * np.pi)
  1738. def test_negative_zero(self):
  1739. # atan2(y, +-0) returns -pi/2 for y < 0.
  1740. assert_almost_equal(ncu.arctan2(-1, np.PZERO), -0.5 * np.pi)
  1741. assert_almost_equal(ncu.arctan2(-1, np.NZERO), -0.5 * np.pi)
  1742. def test_any_ninf(self):
  1743. # atan2(+-y, -infinity) returns +-pi for finite y > 0.
  1744. assert_almost_equal(ncu.arctan2(1, np.NINF), np.pi)
  1745. assert_almost_equal(ncu.arctan2(-1, np.NINF), -np.pi)
  1746. def test_any_pinf(self):
  1747. # atan2(+-y, +infinity) returns +-0 for finite y > 0.
  1748. assert_arctan2_ispzero(1, np.inf)
  1749. assert_arctan2_isnzero(-1, np.inf)
  1750. def test_inf_any(self):
  1751. # atan2(+-infinity, x) returns +-pi/2 for finite x.
  1752. assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi)
  1753. assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi)
  1754. def test_inf_ninf(self):
  1755. # atan2(+-infinity, -infinity) returns +-3*pi/4.
  1756. assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi)
  1757. assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi)
  1758. def test_inf_pinf(self):
  1759. # atan2(+-infinity, +infinity) returns +-pi/4.
  1760. assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi)
  1761. assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi)
  1762. def test_nan_any(self):
  1763. # atan2(nan, x) returns nan for any x, including inf
  1764. assert_arctan2_isnan(np.nan, np.inf)
  1765. assert_arctan2_isnan(np.inf, np.nan)
  1766. assert_arctan2_isnan(np.nan, np.nan)
  1767. class TestLdexp:
  1768. def _check_ldexp(self, tp):
  1769. assert_almost_equal(ncu.ldexp(np.array(2., np.float32),
  1770. np.array(3, tp)), 16.)
  1771. assert_almost_equal(ncu.ldexp(np.array(2., np.float64),
  1772. np.array(3, tp)), 16.)
  1773. assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble),
  1774. np.array(3, tp)), 16.)
  1775. def test_ldexp(self):
  1776. # The default Python int type should work
  1777. assert_almost_equal(ncu.ldexp(2., 3), 16.)
  1778. # The following int types should all be accepted
  1779. self._check_ldexp(np.int8)
  1780. self._check_ldexp(np.int16)
  1781. self._check_ldexp(np.int32)
  1782. self._check_ldexp('i')
  1783. self._check_ldexp('l')
  1784. def test_ldexp_overflow(self):
  1785. # silence warning emitted on overflow
  1786. with np.errstate(over="ignore"):
  1787. imax = np.iinfo(np.dtype('l')).max
  1788. imin = np.iinfo(np.dtype('l')).min
  1789. assert_equal(ncu.ldexp(2., imax), np.inf)
  1790. assert_equal(ncu.ldexp(2., imin), 0)
  1791. class TestMaximum(_FilterInvalids):
  1792. def test_reduce(self):
  1793. dflt = np.typecodes['AllFloat']
  1794. dint = np.typecodes['AllInteger']
  1795. seq1 = np.arange(11)
  1796. seq2 = seq1[::-1]
  1797. func = np.maximum.reduce
  1798. for dt in dint:
  1799. tmp1 = seq1.astype(dt)
  1800. tmp2 = seq2.astype(dt)
  1801. assert_equal(func(tmp1), 10)
  1802. assert_equal(func(tmp2), 10)
  1803. for dt in dflt:
  1804. tmp1 = seq1.astype(dt)
  1805. tmp2 = seq2.astype(dt)
  1806. assert_equal(func(tmp1), 10)
  1807. assert_equal(func(tmp2), 10)
  1808. tmp1[::2] = np.nan
  1809. tmp2[::2] = np.nan
  1810. assert_equal(func(tmp1), np.nan)
  1811. assert_equal(func(tmp2), np.nan)
  1812. def test_reduce_complex(self):
  1813. assert_equal(np.maximum.reduce([1, 2j]), 1)
  1814. assert_equal(np.maximum.reduce([1+3j, 2j]), 1+3j)
  1815. def test_float_nans(self):
  1816. nan = np.nan
  1817. arg1 = np.array([0, nan, nan])
  1818. arg2 = np.array([nan, 0, nan])
  1819. out = np.array([nan, nan, nan])
  1820. assert_equal(np.maximum(arg1, arg2), out)
  1821. def test_object_nans(self):
  1822. # Multiple checks to give this a chance to
  1823. # fail if cmp is used instead of rich compare.
  1824. # Failure cannot be guaranteed.
  1825. for i in range(1):
  1826. x = np.array(float('nan'), object)
  1827. y = 1.0
  1828. z = np.array(float('nan'), object)
  1829. assert_(np.maximum(x, y) == 1.0)
  1830. assert_(np.maximum(z, y) == 1.0)
  1831. def test_complex_nans(self):
  1832. nan = np.nan
  1833. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1834. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1835. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1836. out = np.array([nan, nan, nan], dtype=complex)
  1837. assert_equal(np.maximum(arg1, arg2), out)
  1838. def test_object_array(self):
  1839. arg1 = np.arange(5, dtype=object)
  1840. arg2 = arg1 + 1
  1841. assert_equal(np.maximum(arg1, arg2), arg2)
  1842. def test_strided_array(self):
  1843. arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
  1844. arr2 = np.array([-2.0,-1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
  1845. maxtrue = np.array([-2.0, 1.0, np.nan, 1.0, np.nan, np.nan, np.inf, -3.0])
  1846. out = np.ones(8)
  1847. out_maxtrue = np.array([-2.0, 1.0, 1.0, 10.0, 1.0, 1.0, np.nan, 1.0])
  1848. assert_equal(np.maximum(arr1,arr2), maxtrue)
  1849. assert_equal(np.maximum(arr1[::2],arr2[::2]), maxtrue[::2])
  1850. assert_equal(np.maximum(arr1[:4:], arr2[::2]), np.array([-2.0, np.nan, 10.0, 1.0]))
  1851. assert_equal(np.maximum(arr1[::3], arr2[:3:]), np.array([-2.0, 0.0, np.nan]))
  1852. assert_equal(np.maximum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-2.0, 10., np.nan]))
  1853. assert_equal(out, out_maxtrue)
  1854. def test_precision(self):
  1855. dtypes = [np.float16, np.float32, np.float64, np.longdouble]
  1856. for dt in dtypes:
  1857. dtmin = np.finfo(dt).min
  1858. dtmax = np.finfo(dt).max
  1859. d1 = dt(0.1)
  1860. d1_next = np.nextafter(d1, np.inf)
  1861. test_cases = [
  1862. # v1 v2 expected
  1863. (dtmin, -np.inf, dtmin),
  1864. (dtmax, -np.inf, dtmax),
  1865. (d1, d1_next, d1_next),
  1866. (dtmax, np.nan, np.nan),
  1867. ]
  1868. for v1, v2, expected in test_cases:
  1869. assert_equal(np.maximum([v1], [v2]), [expected])
  1870. assert_equal(np.maximum.reduce([v1, v2]), expected)
  1871. class TestMinimum(_FilterInvalids):
  1872. def test_reduce(self):
  1873. dflt = np.typecodes['AllFloat']
  1874. dint = np.typecodes['AllInteger']
  1875. seq1 = np.arange(11)
  1876. seq2 = seq1[::-1]
  1877. func = np.minimum.reduce
  1878. for dt in dint:
  1879. tmp1 = seq1.astype(dt)
  1880. tmp2 = seq2.astype(dt)
  1881. assert_equal(func(tmp1), 0)
  1882. assert_equal(func(tmp2), 0)
  1883. for dt in dflt:
  1884. tmp1 = seq1.astype(dt)
  1885. tmp2 = seq2.astype(dt)
  1886. assert_equal(func(tmp1), 0)
  1887. assert_equal(func(tmp2), 0)
  1888. tmp1[::2] = np.nan
  1889. tmp2[::2] = np.nan
  1890. assert_equal(func(tmp1), np.nan)
  1891. assert_equal(func(tmp2), np.nan)
  1892. def test_reduce_complex(self):
  1893. assert_equal(np.minimum.reduce([1, 2j]), 2j)
  1894. assert_equal(np.minimum.reduce([1+3j, 2j]), 2j)
  1895. def test_float_nans(self):
  1896. nan = np.nan
  1897. arg1 = np.array([0, nan, nan])
  1898. arg2 = np.array([nan, 0, nan])
  1899. out = np.array([nan, nan, nan])
  1900. assert_equal(np.minimum(arg1, arg2), out)
  1901. def test_object_nans(self):
  1902. # Multiple checks to give this a chance to
  1903. # fail if cmp is used instead of rich compare.
  1904. # Failure cannot be guaranteed.
  1905. for i in range(1):
  1906. x = np.array(float('nan'), object)
  1907. y = 1.0
  1908. z = np.array(float('nan'), object)
  1909. assert_(np.minimum(x, y) == 1.0)
  1910. assert_(np.minimum(z, y) == 1.0)
  1911. def test_complex_nans(self):
  1912. nan = np.nan
  1913. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1914. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1915. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1916. out = np.array([nan, nan, nan], dtype=complex)
  1917. assert_equal(np.minimum(arg1, arg2), out)
  1918. def test_object_array(self):
  1919. arg1 = np.arange(5, dtype=object)
  1920. arg2 = arg1 + 1
  1921. assert_equal(np.minimum(arg1, arg2), arg1)
  1922. def test_strided_array(self):
  1923. arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
  1924. arr2 = np.array([-2.0,-1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
  1925. mintrue = np.array([-4.0, -1.0, np.nan, 0.0, np.nan, np.nan, 1.0, -np.inf])
  1926. out = np.ones(8)
  1927. out_mintrue = np.array([-4.0, 1.0, 1.0, 1.0, 1.0, 1.0, np.nan, 1.0])
  1928. assert_equal(np.minimum(arr1,arr2), mintrue)
  1929. assert_equal(np.minimum(arr1[::2],arr2[::2]), mintrue[::2])
  1930. assert_equal(np.minimum(arr1[:4:], arr2[::2]), np.array([-4.0, np.nan, 0.0, 0.0]))
  1931. assert_equal(np.minimum(arr1[::3], arr2[:3:]), np.array([-4.0, -1.0, np.nan]))
  1932. assert_equal(np.minimum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-4.0, 1.0, np.nan]))
  1933. assert_equal(out, out_mintrue)
  1934. def test_precision(self):
  1935. dtypes = [np.float16, np.float32, np.float64, np.longdouble]
  1936. for dt in dtypes:
  1937. dtmin = np.finfo(dt).min
  1938. dtmax = np.finfo(dt).max
  1939. d1 = dt(0.1)
  1940. d1_next = np.nextafter(d1, np.inf)
  1941. test_cases = [
  1942. # v1 v2 expected
  1943. (dtmin, np.inf, dtmin),
  1944. (dtmax, np.inf, dtmax),
  1945. (d1, d1_next, d1),
  1946. (dtmin, np.nan, np.nan),
  1947. ]
  1948. for v1, v2, expected in test_cases:
  1949. assert_equal(np.minimum([v1], [v2]), [expected])
  1950. assert_equal(np.minimum.reduce([v1, v2]), expected)
  1951. class TestFmax(_FilterInvalids):
  1952. def test_reduce(self):
  1953. dflt = np.typecodes['AllFloat']
  1954. dint = np.typecodes['AllInteger']
  1955. seq1 = np.arange(11)
  1956. seq2 = seq1[::-1]
  1957. func = np.fmax.reduce
  1958. for dt in dint:
  1959. tmp1 = seq1.astype(dt)
  1960. tmp2 = seq2.astype(dt)
  1961. assert_equal(func(tmp1), 10)
  1962. assert_equal(func(tmp2), 10)
  1963. for dt in dflt:
  1964. tmp1 = seq1.astype(dt)
  1965. tmp2 = seq2.astype(dt)
  1966. assert_equal(func(tmp1), 10)
  1967. assert_equal(func(tmp2), 10)
  1968. tmp1[::2] = np.nan
  1969. tmp2[::2] = np.nan
  1970. assert_equal(func(tmp1), 9)
  1971. assert_equal(func(tmp2), 9)
  1972. def test_reduce_complex(self):
  1973. assert_equal(np.fmax.reduce([1, 2j]), 1)
  1974. assert_equal(np.fmax.reduce([1+3j, 2j]), 1+3j)
  1975. def test_float_nans(self):
  1976. nan = np.nan
  1977. arg1 = np.array([0, nan, nan])
  1978. arg2 = np.array([nan, 0, nan])
  1979. out = np.array([0, 0, nan])
  1980. assert_equal(np.fmax(arg1, arg2), out)
  1981. def test_complex_nans(self):
  1982. nan = np.nan
  1983. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  1984. arg1 = np.array([0, cnan, cnan], dtype=complex)
  1985. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  1986. out = np.array([0, 0, nan], dtype=complex)
  1987. assert_equal(np.fmax(arg1, arg2), out)
  1988. def test_precision(self):
  1989. dtypes = [np.float16, np.float32, np.float64, np.longdouble]
  1990. for dt in dtypes:
  1991. dtmin = np.finfo(dt).min
  1992. dtmax = np.finfo(dt).max
  1993. d1 = dt(0.1)
  1994. d1_next = np.nextafter(d1, np.inf)
  1995. test_cases = [
  1996. # v1 v2 expected
  1997. (dtmin, -np.inf, dtmin),
  1998. (dtmax, -np.inf, dtmax),
  1999. (d1, d1_next, d1_next),
  2000. (dtmax, np.nan, dtmax),
  2001. ]
  2002. for v1, v2, expected in test_cases:
  2003. assert_equal(np.fmax([v1], [v2]), [expected])
  2004. assert_equal(np.fmax.reduce([v1, v2]), expected)
  2005. class TestFmin(_FilterInvalids):
  2006. def test_reduce(self):
  2007. dflt = np.typecodes['AllFloat']
  2008. dint = np.typecodes['AllInteger']
  2009. seq1 = np.arange(11)
  2010. seq2 = seq1[::-1]
  2011. func = np.fmin.reduce
  2012. for dt in dint:
  2013. tmp1 = seq1.astype(dt)
  2014. tmp2 = seq2.astype(dt)
  2015. assert_equal(func(tmp1), 0)
  2016. assert_equal(func(tmp2), 0)
  2017. for dt in dflt:
  2018. tmp1 = seq1.astype(dt)
  2019. tmp2 = seq2.astype(dt)
  2020. assert_equal(func(tmp1), 0)
  2021. assert_equal(func(tmp2), 0)
  2022. tmp1[::2] = np.nan
  2023. tmp2[::2] = np.nan
  2024. assert_equal(func(tmp1), 1)
  2025. assert_equal(func(tmp2), 1)
  2026. def test_reduce_complex(self):
  2027. assert_equal(np.fmin.reduce([1, 2j]), 2j)
  2028. assert_equal(np.fmin.reduce([1+3j, 2j]), 2j)
  2029. def test_float_nans(self):
  2030. nan = np.nan
  2031. arg1 = np.array([0, nan, nan])
  2032. arg2 = np.array([nan, 0, nan])
  2033. out = np.array([0, 0, nan])
  2034. assert_equal(np.fmin(arg1, arg2), out)
  2035. def test_complex_nans(self):
  2036. nan = np.nan
  2037. for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
  2038. arg1 = np.array([0, cnan, cnan], dtype=complex)
  2039. arg2 = np.array([cnan, 0, cnan], dtype=complex)
  2040. out = np.array([0, 0, nan], dtype=complex)
  2041. assert_equal(np.fmin(arg1, arg2), out)
  2042. def test_precision(self):
  2043. dtypes = [np.float16, np.float32, np.float64, np.longdouble]
  2044. for dt in dtypes:
  2045. dtmin = np.finfo(dt).min
  2046. dtmax = np.finfo(dt).max
  2047. d1 = dt(0.1)
  2048. d1_next = np.nextafter(d1, np.inf)
  2049. test_cases = [
  2050. # v1 v2 expected
  2051. (dtmin, np.inf, dtmin),
  2052. (dtmax, np.inf, dtmax),
  2053. (d1, d1_next, d1),
  2054. (dtmin, np.nan, dtmin),
  2055. ]
  2056. for v1, v2, expected in test_cases:
  2057. assert_equal(np.fmin([v1], [v2]), [expected])
  2058. assert_equal(np.fmin.reduce([v1, v2]), expected)
  2059. class TestBool:
  2060. def test_exceptions(self):
  2061. a = np.ones(1, dtype=np.bool_)
  2062. assert_raises(TypeError, np.negative, a)
  2063. assert_raises(TypeError, np.positive, a)
  2064. assert_raises(TypeError, np.subtract, a, a)
  2065. def test_truth_table_logical(self):
  2066. # 2, 3 and 4 serves as true values
  2067. input1 = [0, 0, 3, 2]
  2068. input2 = [0, 4, 0, 2]
  2069. typecodes = (np.typecodes['AllFloat']
  2070. + np.typecodes['AllInteger']
  2071. + '?') # boolean
  2072. for dtype in map(np.dtype, typecodes):
  2073. arg1 = np.asarray(input1, dtype=dtype)
  2074. arg2 = np.asarray(input2, dtype=dtype)
  2075. # OR
  2076. out = [False, True, True, True]
  2077. for func in (np.logical_or, np.maximum):
  2078. assert_equal(func(arg1, arg2).astype(bool), out)
  2079. # AND
  2080. out = [False, False, False, True]
  2081. for func in (np.logical_and, np.minimum):
  2082. assert_equal(func(arg1, arg2).astype(bool), out)
  2083. # XOR
  2084. out = [False, True, True, False]
  2085. for func in (np.logical_xor, np.not_equal):
  2086. assert_equal(func(arg1, arg2).astype(bool), out)
  2087. def test_truth_table_bitwise(self):
  2088. arg1 = [False, False, True, True]
  2089. arg2 = [False, True, False, True]
  2090. out = [False, True, True, True]
  2091. assert_equal(np.bitwise_or(arg1, arg2), out)
  2092. out = [False, False, False, True]
  2093. assert_equal(np.bitwise_and(arg1, arg2), out)
  2094. out = [False, True, True, False]
  2095. assert_equal(np.bitwise_xor(arg1, arg2), out)
  2096. def test_reduce(self):
  2097. none = np.array([0, 0, 0, 0], bool)
  2098. some = np.array([1, 0, 1, 1], bool)
  2099. every = np.array([1, 1, 1, 1], bool)
  2100. empty = np.array([], bool)
  2101. arrs = [none, some, every, empty]
  2102. for arr in arrs:
  2103. assert_equal(np.logical_and.reduce(arr), all(arr))
  2104. for arr in arrs:
  2105. assert_equal(np.logical_or.reduce(arr), any(arr))
  2106. for arr in arrs:
  2107. assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1)
  2108. class TestBitwiseUFuncs:
  2109. bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O']
  2110. def test_values(self):
  2111. for dt in self.bitwise_types:
  2112. zeros = np.array([0], dtype=dt)
  2113. ones = np.array([-1]).astype(dt)
  2114. msg = "dt = '%s'" % dt.char
  2115. assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
  2116. assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
  2117. assert_equal(np.bitwise_or(zeros, zeros), zeros, err_msg=msg)
  2118. assert_equal(np.bitwise_or(zeros, ones), ones, err_msg=msg)
  2119. assert_equal(np.bitwise_or(ones, zeros), ones, err_msg=msg)
  2120. assert_equal(np.bitwise_or(ones, ones), ones, err_msg=msg)
  2121. assert_equal(np.bitwise_xor(zeros, zeros), zeros, err_msg=msg)
  2122. assert_equal(np.bitwise_xor(zeros, ones), ones, err_msg=msg)
  2123. assert_equal(np.bitwise_xor(ones, zeros), ones, err_msg=msg)
  2124. assert_equal(np.bitwise_xor(ones, ones), zeros, err_msg=msg)
  2125. assert_equal(np.bitwise_and(zeros, zeros), zeros, err_msg=msg)
  2126. assert_equal(np.bitwise_and(zeros, ones), zeros, err_msg=msg)
  2127. assert_equal(np.bitwise_and(ones, zeros), zeros, err_msg=msg)
  2128. assert_equal(np.bitwise_and(ones, ones), ones, err_msg=msg)
  2129. def test_types(self):
  2130. for dt in self.bitwise_types:
  2131. zeros = np.array([0], dtype=dt)
  2132. ones = np.array([-1]).astype(dt)
  2133. msg = "dt = '%s'" % dt.char
  2134. assert_(np.bitwise_not(zeros).dtype == dt, msg)
  2135. assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
  2136. assert_(np.bitwise_xor(zeros, zeros).dtype == dt, msg)
  2137. assert_(np.bitwise_and(zeros, zeros).dtype == dt, msg)
  2138. def test_identity(self):
  2139. assert_(np.bitwise_or.identity == 0, 'bitwise_or')
  2140. assert_(np.bitwise_xor.identity == 0, 'bitwise_xor')
  2141. assert_(np.bitwise_and.identity == -1, 'bitwise_and')
  2142. def test_reduction(self):
  2143. binary_funcs = (np.bitwise_or, np.bitwise_xor, np.bitwise_and)
  2144. for dt in self.bitwise_types:
  2145. zeros = np.array([0], dtype=dt)
  2146. ones = np.array([-1]).astype(dt)
  2147. for f in binary_funcs:
  2148. msg = "dt: '%s', f: '%s'" % (dt, f)
  2149. assert_equal(f.reduce(zeros), zeros, err_msg=msg)
  2150. assert_equal(f.reduce(ones), ones, err_msg=msg)
  2151. # Test empty reduction, no object dtype
  2152. for dt in self.bitwise_types[:-1]:
  2153. # No object array types
  2154. empty = np.array([], dtype=dt)
  2155. for f in binary_funcs:
  2156. msg = "dt: '%s', f: '%s'" % (dt, f)
  2157. tgt = np.array(f.identity).astype(dt)
  2158. res = f.reduce(empty)
  2159. assert_equal(res, tgt, err_msg=msg)
  2160. assert_(res.dtype == tgt.dtype, msg)
  2161. # Empty object arrays use the identity. Note that the types may
  2162. # differ, the actual type used is determined by the assign_identity
  2163. # function and is not the same as the type returned by the identity
  2164. # method.
  2165. for f in binary_funcs:
  2166. msg = "dt: '%s'" % (f,)
  2167. empty = np.array([], dtype=object)
  2168. tgt = f.identity
  2169. res = f.reduce(empty)
  2170. assert_equal(res, tgt, err_msg=msg)
  2171. # Non-empty object arrays do not use the identity
  2172. for f in binary_funcs:
  2173. msg = "dt: '%s'" % (f,)
  2174. btype = np.array([True], dtype=object)
  2175. assert_(type(f.reduce(btype)) is bool, msg)
  2176. class TestInt:
  2177. def test_logical_not(self):
  2178. x = np.ones(10, dtype=np.int16)
  2179. o = np.ones(10 * 2, dtype=bool)
  2180. tgt = o.copy()
  2181. tgt[::2] = False
  2182. os = o[::2]
  2183. assert_array_equal(np.logical_not(x, out=os), False)
  2184. assert_array_equal(o, tgt)
  2185. class TestFloatingPoint:
  2186. def test_floating_point(self):
  2187. assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
  2188. class TestDegrees:
  2189. def test_degrees(self):
  2190. assert_almost_equal(ncu.degrees(np.pi), 180.0)
  2191. assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0)
  2192. class TestRadians:
  2193. def test_radians(self):
  2194. assert_almost_equal(ncu.radians(180.0), np.pi)
  2195. assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi)
  2196. class TestHeavside:
  2197. def test_heaviside(self):
  2198. x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]])
  2199. expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]])
  2200. expected1 = expectedhalf.copy()
  2201. expected1[0, 2] = 1
  2202. h = ncu.heaviside(x, 0.5)
  2203. assert_equal(h, expectedhalf)
  2204. h = ncu.heaviside(x, 1.0)
  2205. assert_equal(h, expected1)
  2206. x = x.astype(np.float32)
  2207. h = ncu.heaviside(x, np.float32(0.5))
  2208. assert_equal(h, expectedhalf.astype(np.float32))
  2209. h = ncu.heaviside(x, np.float32(1.0))
  2210. assert_equal(h, expected1.astype(np.float32))
  2211. class TestSign:
  2212. def test_sign(self):
  2213. a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
  2214. out = np.zeros(a.shape)
  2215. tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
  2216. with np.errstate(invalid='ignore'):
  2217. res = ncu.sign(a)
  2218. assert_equal(res, tgt)
  2219. res = ncu.sign(a, out)
  2220. assert_equal(res, tgt)
  2221. assert_equal(out, tgt)
  2222. def test_sign_dtype_object(self):
  2223. # In reference to github issue #6229
  2224. foo = np.array([-.1, 0, .1])
  2225. a = np.sign(foo.astype(object))
  2226. b = np.sign(foo)
  2227. assert_array_equal(a, b)
  2228. def test_sign_dtype_nan_object(self):
  2229. # In reference to github issue #6229
  2230. def test_nan():
  2231. foo = np.array([np.nan])
  2232. # FIXME: a not used
  2233. a = np.sign(foo.astype(object))
  2234. assert_raises(TypeError, test_nan)
  2235. class TestMinMax:
  2236. def test_minmax_blocked(self):
  2237. # simd tests on max/min, test all alignments, slow but important
  2238. # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once)
  2239. for dt, sz in [(np.float32, 15), (np.float64, 7)]:
  2240. for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
  2241. max_size=sz):
  2242. for i in range(inp.size):
  2243. inp[:] = np.arange(inp.size, dtype=dt)
  2244. inp[i] = np.nan
  2245. emsg = lambda: '%r\n%s' % (inp, msg)
  2246. with suppress_warnings() as sup:
  2247. sup.filter(RuntimeWarning,
  2248. "invalid value encountered in reduce")
  2249. assert_(np.isnan(inp.max()), msg=emsg)
  2250. assert_(np.isnan(inp.min()), msg=emsg)
  2251. inp[i] = 1e10
  2252. assert_equal(inp.max(), 1e10, err_msg=msg)
  2253. inp[i] = -1e10
  2254. assert_equal(inp.min(), -1e10, err_msg=msg)
  2255. def test_lower_align(self):
  2256. # check data that is not aligned to element size
  2257. # i.e doubles are aligned to 4 bytes on i386
  2258. d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  2259. assert_equal(d.max(), d[0])
  2260. assert_equal(d.min(), d[0])
  2261. def test_reduce_reorder(self):
  2262. # gh 10370, 11029 Some compilers reorder the call to npy_getfloatstatus
  2263. # and put it before the call to an intrisic function that causes
  2264. # invalid status to be set. Also make sure warnings are not emitted
  2265. for n in (2, 4, 8, 16, 32):
  2266. for dt in (np.float32, np.float16, np.complex64):
  2267. for r in np.diagflat(np.array([np.nan] * n, dtype=dt)):
  2268. assert_equal(np.min(r), np.nan)
  2269. def test_minimize_no_warns(self):
  2270. a = np.minimum(np.nan, 1)
  2271. assert_equal(a, np.nan)
  2272. class TestAbsoluteNegative:
  2273. def test_abs_neg_blocked(self):
  2274. # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1
  2275. for dt, sz in [(np.float32, 11), (np.float64, 5)]:
  2276. for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
  2277. max_size=sz):
  2278. tgt = [ncu.absolute(i) for i in inp]
  2279. np.absolute(inp, out=out)
  2280. assert_equal(out, tgt, err_msg=msg)
  2281. assert_((out >= 0).all())
  2282. tgt = [-1*(i) for i in inp]
  2283. np.negative(inp, out=out)
  2284. assert_equal(out, tgt, err_msg=msg)
  2285. for v in [np.nan, -np.inf, np.inf]:
  2286. for i in range(inp.size):
  2287. d = np.arange(inp.size, dtype=dt)
  2288. inp[:] = -d
  2289. inp[i] = v
  2290. d[i] = -v if v == -np.inf else v
  2291. assert_array_equal(np.abs(inp), d, err_msg=msg)
  2292. np.abs(inp, out=out)
  2293. assert_array_equal(out, d, err_msg=msg)
  2294. assert_array_equal(-inp, -1*inp, err_msg=msg)
  2295. d = -1 * inp
  2296. np.negative(inp, out=out)
  2297. assert_array_equal(out, d, err_msg=msg)
  2298. def test_lower_align(self):
  2299. # check data that is not aligned to element size
  2300. # i.e doubles are aligned to 4 bytes on i386
  2301. d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
  2302. assert_equal(np.abs(d), d)
  2303. assert_equal(np.negative(d), -d)
  2304. np.negative(d, out=d)
  2305. np.negative(np.ones_like(d), out=d)
  2306. np.abs(d, out=d)
  2307. np.abs(np.ones_like(d), out=d)
  2308. class TestPositive:
  2309. def test_valid(self):
  2310. valid_dtypes = [int, float, complex, object]
  2311. for dtype in valid_dtypes:
  2312. x = np.arange(5, dtype=dtype)
  2313. result = np.positive(x)
  2314. assert_equal(x, result, err_msg=str(dtype))
  2315. def test_invalid(self):
  2316. with assert_raises(TypeError):
  2317. np.positive(True)
  2318. with assert_raises(TypeError):
  2319. np.positive(np.datetime64('2000-01-01'))
  2320. with assert_raises(TypeError):
  2321. np.positive(np.array(['foo'], dtype=str))
  2322. with assert_raises(TypeError):
  2323. np.positive(np.array(['bar'], dtype=object))
  2324. class TestSpecialMethods:
  2325. def test_wrap(self):
  2326. class with_wrap:
  2327. def __array__(self):
  2328. return np.zeros(1)
  2329. def __array_wrap__(self, arr, context):
  2330. r = with_wrap()
  2331. r.arr = arr
  2332. r.context = context
  2333. return r
  2334. a = with_wrap()
  2335. x = ncu.minimum(a, a)
  2336. assert_equal(x.arr, np.zeros(1))
  2337. func, args, i = x.context
  2338. assert_(func is ncu.minimum)
  2339. assert_equal(len(args), 2)
  2340. assert_equal(args[0], a)
  2341. assert_equal(args[1], a)
  2342. assert_equal(i, 0)
  2343. def test_wrap_and_prepare_out(self):
  2344. # Calling convention for out should not affect how special methods are
  2345. # called
  2346. class StoreArrayPrepareWrap(np.ndarray):
  2347. _wrap_args = None
  2348. _prepare_args = None
  2349. def __new__(cls):
  2350. return np.zeros(()).view(cls)
  2351. def __array_wrap__(self, obj, context):
  2352. self._wrap_args = context[1]
  2353. return obj
  2354. def __array_prepare__(self, obj, context):
  2355. self._prepare_args = context[1]
  2356. return obj
  2357. @property
  2358. def args(self):
  2359. # We need to ensure these are fetched at the same time, before
  2360. # any other ufuncs are called by the assertions
  2361. return (self._prepare_args, self._wrap_args)
  2362. def __repr__(self):
  2363. return "a" # for short test output
  2364. def do_test(f_call, f_expected):
  2365. a = StoreArrayPrepareWrap()
  2366. f_call(a)
  2367. p, w = a.args
  2368. expected = f_expected(a)
  2369. try:
  2370. assert_equal(p, expected)
  2371. assert_equal(w, expected)
  2372. except AssertionError as e:
  2373. # assert_equal produces truly useless error messages
  2374. raise AssertionError("\n".join([
  2375. "Bad arguments passed in ufunc call",
  2376. " expected: {}".format(expected),
  2377. " __array_prepare__ got: {}".format(p),
  2378. " __array_wrap__ got: {}".format(w)
  2379. ]))
  2380. # method not on the out argument
  2381. do_test(lambda a: np.add(a, 0), lambda a: (a, 0))
  2382. do_test(lambda a: np.add(a, 0, None), lambda a: (a, 0))
  2383. do_test(lambda a: np.add(a, 0, out=None), lambda a: (a, 0))
  2384. do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))
  2385. # method on the out argument
  2386. do_test(lambda a: np.add(0, 0, a), lambda a: (0, 0, a))
  2387. do_test(lambda a: np.add(0, 0, out=a), lambda a: (0, 0, a))
  2388. do_test(lambda a: np.add(0, 0, out=(a,)), lambda a: (0, 0, a))
  2389. # Also check the where mask handling:
  2390. do_test(lambda a: np.add(a, 0, where=False), lambda a: (a, 0))
  2391. do_test(lambda a: np.add(0, 0, a, where=False), lambda a: (0, 0, a))
  2392. def test_wrap_with_iterable(self):
  2393. # test fix for bug #1026:
  2394. class with_wrap(np.ndarray):
  2395. __array_priority__ = 10
  2396. def __new__(cls):
  2397. return np.asarray(1).view(cls).copy()
  2398. def __array_wrap__(self, arr, context):
  2399. return arr.view(type(self))
  2400. a = with_wrap()
  2401. x = ncu.multiply(a, (1, 2, 3))
  2402. assert_(isinstance(x, with_wrap))
  2403. assert_array_equal(x, np.array((1, 2, 3)))
  2404. def test_priority_with_scalar(self):
  2405. # test fix for bug #826:
  2406. class A(np.ndarray):
  2407. __array_priority__ = 10
  2408. def __new__(cls):
  2409. return np.asarray(1.0, 'float64').view(cls).copy()
  2410. a = A()
  2411. x = np.float64(1)*a
  2412. assert_(isinstance(x, A))
  2413. assert_array_equal(x, np.array(1))
  2414. def test_old_wrap(self):
  2415. class with_wrap:
  2416. def __array__(self):
  2417. return np.zeros(1)
  2418. def __array_wrap__(self, arr):
  2419. r = with_wrap()
  2420. r.arr = arr
  2421. return r
  2422. a = with_wrap()
  2423. x = ncu.minimum(a, a)
  2424. assert_equal(x.arr, np.zeros(1))
  2425. def test_priority(self):
  2426. class A:
  2427. def __array__(self):
  2428. return np.zeros(1)
  2429. def __array_wrap__(self, arr, context):
  2430. r = type(self)()
  2431. r.arr = arr
  2432. r.context = context
  2433. return r
  2434. class B(A):
  2435. __array_priority__ = 20.
  2436. class C(A):
  2437. __array_priority__ = 40.
  2438. x = np.zeros(1)
  2439. a = A()
  2440. b = B()
  2441. c = C()
  2442. f = ncu.minimum
  2443. assert_(type(f(x, x)) is np.ndarray)
  2444. assert_(type(f(x, a)) is A)
  2445. assert_(type(f(x, b)) is B)
  2446. assert_(type(f(x, c)) is C)
  2447. assert_(type(f(a, x)) is A)
  2448. assert_(type(f(b, x)) is B)
  2449. assert_(type(f(c, x)) is C)
  2450. assert_(type(f(a, a)) is A)
  2451. assert_(type(f(a, b)) is B)
  2452. assert_(type(f(b, a)) is B)
  2453. assert_(type(f(b, b)) is B)
  2454. assert_(type(f(b, c)) is C)
  2455. assert_(type(f(c, b)) is C)
  2456. assert_(type(f(c, c)) is C)
  2457. assert_(type(ncu.exp(a) is A))
  2458. assert_(type(ncu.exp(b) is B))
  2459. assert_(type(ncu.exp(c) is C))
  2460. def test_failing_wrap(self):
  2461. class A:
  2462. def __array__(self):
  2463. return np.zeros(2)
  2464. def __array_wrap__(self, arr, context):
  2465. raise RuntimeError
  2466. a = A()
  2467. assert_raises(RuntimeError, ncu.maximum, a, a)
  2468. assert_raises(RuntimeError, ncu.maximum.reduce, a)
  2469. def test_failing_out_wrap(self):
  2470. singleton = np.array([1.0])
  2471. class Ok(np.ndarray):
  2472. def __array_wrap__(self, obj):
  2473. return singleton
  2474. class Bad(np.ndarray):
  2475. def __array_wrap__(self, obj):
  2476. raise RuntimeError
  2477. ok = np.empty(1).view(Ok)
  2478. bad = np.empty(1).view(Bad)
  2479. # double-free (segfault) of "ok" if "bad" raises an exception
  2480. for i in range(10):
  2481. assert_raises(RuntimeError, ncu.frexp, 1, ok, bad)
  2482. def test_none_wrap(self):
  2483. # Tests that issue #8507 is resolved. Previously, this would segfault
  2484. class A:
  2485. def __array__(self):
  2486. return np.zeros(1)
  2487. def __array_wrap__(self, arr, context=None):
  2488. return None
  2489. a = A()
  2490. assert_equal(ncu.maximum(a, a), None)
  2491. def test_default_prepare(self):
  2492. class with_wrap:
  2493. __array_priority__ = 10
  2494. def __array__(self):
  2495. return np.zeros(1)
  2496. def __array_wrap__(self, arr, context):
  2497. return arr
  2498. a = with_wrap()
  2499. x = ncu.minimum(a, a)
  2500. assert_equal(x, np.zeros(1))
  2501. assert_equal(type(x), np.ndarray)
  2502. @pytest.mark.parametrize("use_where", [True, False])
  2503. def test_prepare(self, use_where):
  2504. class with_prepare(np.ndarray):
  2505. __array_priority__ = 10
  2506. def __array_prepare__(self, arr, context):
  2507. # make sure we can return a new
  2508. return np.array(arr).view(type=with_prepare)
  2509. a = np.array(1).view(type=with_prepare)
  2510. if use_where:
  2511. x = np.add(a, a, where=np.array(True))
  2512. else:
  2513. x = np.add(a, a)
  2514. assert_equal(x, np.array(2))
  2515. assert_equal(type(x), with_prepare)
  2516. @pytest.mark.parametrize("use_where", [True, False])
  2517. def test_prepare_out(self, use_where):
  2518. class with_prepare(np.ndarray):
  2519. __array_priority__ = 10
  2520. def __array_prepare__(self, arr, context):
  2521. return np.array(arr).view(type=with_prepare)
  2522. a = np.array([1]).view(type=with_prepare)
  2523. if use_where:
  2524. x = np.add(a, a, a, where=[True])
  2525. else:
  2526. x = np.add(a, a, a)
  2527. # Returned array is new, because of the strange
  2528. # __array_prepare__ above
  2529. assert_(not np.shares_memory(x, a))
  2530. assert_equal(x, np.array([2]))
  2531. assert_equal(type(x), with_prepare)
  2532. def test_failing_prepare(self):
  2533. class A:
  2534. def __array__(self):
  2535. return np.zeros(1)
  2536. def __array_prepare__(self, arr, context=None):
  2537. raise RuntimeError
  2538. a = A()
  2539. assert_raises(RuntimeError, ncu.maximum, a, a)
  2540. assert_raises(RuntimeError, ncu.maximum, a, a, where=False)
  2541. def test_array_too_many_args(self):
  2542. class A:
  2543. def __array__(self, dtype, context):
  2544. return np.zeros(1)
  2545. a = A()
  2546. assert_raises_regex(TypeError, '2 required positional', np.sum, a)
  2547. def test_ufunc_override(self):
  2548. # check override works even with instance with high priority.
  2549. class A:
  2550. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2551. return self, func, method, inputs, kwargs
  2552. class MyNDArray(np.ndarray):
  2553. __array_priority__ = 100
  2554. a = A()
  2555. b = np.array([1]).view(MyNDArray)
  2556. res0 = np.multiply(a, b)
  2557. res1 = np.multiply(b, b, out=a)
  2558. # self
  2559. assert_equal(res0[0], a)
  2560. assert_equal(res1[0], a)
  2561. assert_equal(res0[1], np.multiply)
  2562. assert_equal(res1[1], np.multiply)
  2563. assert_equal(res0[2], '__call__')
  2564. assert_equal(res1[2], '__call__')
  2565. assert_equal(res0[3], (a, b))
  2566. assert_equal(res1[3], (b, b))
  2567. assert_equal(res0[4], {})
  2568. assert_equal(res1[4], {'out': (a,)})
  2569. def test_ufunc_override_mro(self):
  2570. # Some multi arg functions for testing.
  2571. def tres_mul(a, b, c):
  2572. return a * b * c
  2573. def quatro_mul(a, b, c, d):
  2574. return a * b * c * d
  2575. # Make these into ufuncs.
  2576. three_mul_ufunc = np.frompyfunc(tres_mul, 3, 1)
  2577. four_mul_ufunc = np.frompyfunc(quatro_mul, 4, 1)
  2578. class A:
  2579. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2580. return "A"
  2581. class ASub(A):
  2582. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2583. return "ASub"
  2584. class B:
  2585. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2586. return "B"
  2587. class C:
  2588. def __init__(self):
  2589. self.count = 0
  2590. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2591. self.count += 1
  2592. return NotImplemented
  2593. class CSub(C):
  2594. def __array_ufunc__(self, func, method, *inputs, **kwargs):
  2595. self.count += 1
  2596. return NotImplemented
  2597. a = A()
  2598. a_sub = ASub()
  2599. b = B()
  2600. c = C()
  2601. # Standard
  2602. res = np.multiply(a, a_sub)
  2603. assert_equal(res, "ASub")
  2604. res = np.multiply(a_sub, b)
  2605. assert_equal(res, "ASub")
  2606. # With 1 NotImplemented
  2607. res = np.multiply(c, a)
  2608. assert_equal(res, "A")
  2609. assert_equal(c.count, 1)
  2610. # Check our counter works, so we can trust tests below.
  2611. res = np.multiply(c, a)
  2612. assert_equal(c.count, 2)
  2613. # Both NotImplemented.
  2614. c = C()
  2615. c_sub = CSub()
  2616. assert_raises(TypeError, np.multiply, c, c_sub)
  2617. assert_equal(c.count, 1)
  2618. assert_equal(c_sub.count, 1)
  2619. c.count = c_sub.count = 0
  2620. assert_raises(TypeError, np.multiply, c_sub, c)
  2621. assert_equal(c.count, 1)
  2622. assert_equal(c_sub.count, 1)
  2623. c.count = 0
  2624. assert_raises(TypeError, np.multiply, c, c)
  2625. assert_equal(c.count, 1)
  2626. c.count = 0
  2627. assert_raises(TypeError, np.multiply, 2, c)
  2628. assert_equal(c.count, 1)
  2629. # Ternary testing.
  2630. assert_equal(three_mul_ufunc(a, 1, 2), "A")
  2631. assert_equal(three_mul_ufunc(1, a, 2), "A")
  2632. assert_equal(three_mul_ufunc(1, 2, a), "A")
  2633. assert_equal(three_mul_ufunc(a, a, 6), "A")
  2634. assert_equal(three_mul_ufunc(a, 2, a), "A")
  2635. assert_equal(three_mul_ufunc(a, 2, b), "A")
  2636. assert_equal(three_mul_ufunc(a, 2, a_sub), "ASub")
  2637. assert_equal(three_mul_ufunc(a, a_sub, 3), "ASub")
  2638. c.count = 0
  2639. assert_equal(three_mul_ufunc(c, a_sub, 3), "ASub")
  2640. assert_equal(c.count, 1)
  2641. c.count = 0
  2642. assert_equal(three_mul_ufunc(1, a_sub, c), "ASub")
  2643. assert_equal(c.count, 0)
  2644. c.count = 0
  2645. assert_equal(three_mul_ufunc(a, b, c), "A")
  2646. assert_equal(c.count, 0)
  2647. c_sub.count = 0
  2648. assert_equal(three_mul_ufunc(a, b, c_sub), "A")
  2649. assert_equal(c_sub.count, 0)
  2650. assert_equal(three_mul_ufunc(1, 2, b), "B")
  2651. assert_raises(TypeError, three_mul_ufunc, 1, 2, c)
  2652. assert_raises(TypeError, three_mul_ufunc, c_sub, 2, c)
  2653. assert_raises(TypeError, three_mul_ufunc, c_sub, 2, 3)
  2654. # Quaternary testing.
  2655. assert_equal(four_mul_ufunc(a, 1, 2, 3), "A")
  2656. assert_equal(four_mul_ufunc(1, a, 2, 3), "A")
  2657. assert_equal(four_mul_ufunc(1, 1, a, 3), "A")
  2658. assert_equal(four_mul_ufunc(1, 1, 2, a), "A")
  2659. assert_equal(four_mul_ufunc(a, b, 2, 3), "A")
  2660. assert_equal(four_mul_ufunc(1, a, 2, b), "A")
  2661. assert_equal(four_mul_ufunc(b, 1, a, 3), "B")
  2662. assert_equal(four_mul_ufunc(a_sub, 1, 2, a), "ASub")
  2663. assert_equal(four_mul_ufunc(a, 1, 2, a_sub), "ASub")
  2664. c = C()
  2665. c_sub = CSub()
  2666. assert_raises(TypeError, four_mul_ufunc, 1, 2, 3, c)
  2667. assert_equal(c.count, 1)
  2668. c.count = 0
  2669. assert_raises(TypeError, four_mul_ufunc, 1, 2, c_sub, c)
  2670. assert_equal(c_sub.count, 1)
  2671. assert_equal(c.count, 1)
  2672. c2 = C()
  2673. c.count = c_sub.count = 0
  2674. assert_raises(TypeError, four_mul_ufunc, 1, c, c_sub, c2)
  2675. assert_equal(c_sub.count, 1)
  2676. assert_equal(c.count, 1)
  2677. assert_equal(c2.count, 0)
  2678. c.count = c2.count = c_sub.count = 0
  2679. assert_raises(TypeError, four_mul_ufunc, c2, c, c_sub, c)
  2680. assert_equal(c_sub.count, 1)
  2681. assert_equal(c.count, 0)
  2682. assert_equal(c2.count, 1)
  2683. def test_ufunc_override_methods(self):
  2684. class A:
  2685. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2686. return self, ufunc, method, inputs, kwargs
  2687. # __call__
  2688. a = A()
  2689. with assert_raises(TypeError):
  2690. np.multiply.__call__(1, a, foo='bar', answer=42)
  2691. res = np.multiply.__call__(1, a, subok='bar', where=42)
  2692. assert_equal(res[0], a)
  2693. assert_equal(res[1], np.multiply)
  2694. assert_equal(res[2], '__call__')
  2695. assert_equal(res[3], (1, a))
  2696. assert_equal(res[4], {'subok': 'bar', 'where': 42})
  2697. # __call__, wrong args
  2698. assert_raises(TypeError, np.multiply, a)
  2699. assert_raises(TypeError, np.multiply, a, a, a, a)
  2700. assert_raises(TypeError, np.multiply, a, a, sig='a', signature='a')
  2701. assert_raises(TypeError, ncu_tests.inner1d, a, a, axis=0, axes=[0, 0])
  2702. # reduce, positional args
  2703. res = np.multiply.reduce(a, 'axis0', 'dtype0', 'out0', 'keep0')
  2704. assert_equal(res[0], a)
  2705. assert_equal(res[1], np.multiply)
  2706. assert_equal(res[2], 'reduce')
  2707. assert_equal(res[3], (a,))
  2708. assert_equal(res[4], {'dtype':'dtype0',
  2709. 'out': ('out0',),
  2710. 'keepdims': 'keep0',
  2711. 'axis': 'axis0'})
  2712. # reduce, kwargs
  2713. res = np.multiply.reduce(a, axis='axis0', dtype='dtype0', out='out0',
  2714. keepdims='keep0', initial='init0',
  2715. where='where0')
  2716. assert_equal(res[0], a)
  2717. assert_equal(res[1], np.multiply)
  2718. assert_equal(res[2], 'reduce')
  2719. assert_equal(res[3], (a,))
  2720. assert_equal(res[4], {'dtype':'dtype0',
  2721. 'out': ('out0',),
  2722. 'keepdims': 'keep0',
  2723. 'axis': 'axis0',
  2724. 'initial': 'init0',
  2725. 'where': 'where0'})
  2726. # reduce, output equal to None removed, but not other explicit ones,
  2727. # even if they are at their default value.
  2728. res = np.multiply.reduce(a, 0, None, None, False)
  2729. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False})
  2730. res = np.multiply.reduce(a, out=None, axis=0, keepdims=True)
  2731. assert_equal(res[4], {'axis': 0, 'keepdims': True})
  2732. res = np.multiply.reduce(a, None, out=(None,), dtype=None)
  2733. assert_equal(res[4], {'axis': None, 'dtype': None})
  2734. res = np.multiply.reduce(a, 0, None, None, False, 2, True)
  2735. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  2736. 'initial': 2, 'where': True})
  2737. # np._NoValue ignored for initial
  2738. res = np.multiply.reduce(a, 0, None, None, False,
  2739. np._NoValue, True)
  2740. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  2741. 'where': True})
  2742. # None kept for initial, True for where.
  2743. res = np.multiply.reduce(a, 0, None, None, False, None, True)
  2744. assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
  2745. 'initial': None, 'where': True})
  2746. # reduce, wrong args
  2747. assert_raises(ValueError, np.multiply.reduce, a, out=())
  2748. assert_raises(ValueError, np.multiply.reduce, a, out=('out0', 'out1'))
  2749. assert_raises(TypeError, np.multiply.reduce, a, 'axis0', axis='axis0')
  2750. # accumulate, pos args
  2751. res = np.multiply.accumulate(a, 'axis0', 'dtype0', 'out0')
  2752. assert_equal(res[0], a)
  2753. assert_equal(res[1], np.multiply)
  2754. assert_equal(res[2], 'accumulate')
  2755. assert_equal(res[3], (a,))
  2756. assert_equal(res[4], {'dtype':'dtype0',
  2757. 'out': ('out0',),
  2758. 'axis': 'axis0'})
  2759. # accumulate, kwargs
  2760. res = np.multiply.accumulate(a, axis='axis0', dtype='dtype0',
  2761. out='out0')
  2762. assert_equal(res[0], a)
  2763. assert_equal(res[1], np.multiply)
  2764. assert_equal(res[2], 'accumulate')
  2765. assert_equal(res[3], (a,))
  2766. assert_equal(res[4], {'dtype':'dtype0',
  2767. 'out': ('out0',),
  2768. 'axis': 'axis0'})
  2769. # accumulate, output equal to None removed.
  2770. res = np.multiply.accumulate(a, 0, None, None)
  2771. assert_equal(res[4], {'axis': 0, 'dtype': None})
  2772. res = np.multiply.accumulate(a, out=None, axis=0, dtype='dtype1')
  2773. assert_equal(res[4], {'axis': 0, 'dtype': 'dtype1'})
  2774. res = np.multiply.accumulate(a, None, out=(None,), dtype=None)
  2775. assert_equal(res[4], {'axis': None, 'dtype': None})
  2776. # accumulate, wrong args
  2777. assert_raises(ValueError, np.multiply.accumulate, a, out=())
  2778. assert_raises(ValueError, np.multiply.accumulate, a,
  2779. out=('out0', 'out1'))
  2780. assert_raises(TypeError, np.multiply.accumulate, a,
  2781. 'axis0', axis='axis0')
  2782. # reduceat, pos args
  2783. res = np.multiply.reduceat(a, [4, 2], 'axis0', 'dtype0', 'out0')
  2784. assert_equal(res[0], a)
  2785. assert_equal(res[1], np.multiply)
  2786. assert_equal(res[2], 'reduceat')
  2787. assert_equal(res[3], (a, [4, 2]))
  2788. assert_equal(res[4], {'dtype':'dtype0',
  2789. 'out': ('out0',),
  2790. 'axis': 'axis0'})
  2791. # reduceat, kwargs
  2792. res = np.multiply.reduceat(a, [4, 2], axis='axis0', dtype='dtype0',
  2793. out='out0')
  2794. assert_equal(res[0], a)
  2795. assert_equal(res[1], np.multiply)
  2796. assert_equal(res[2], 'reduceat')
  2797. assert_equal(res[3], (a, [4, 2]))
  2798. assert_equal(res[4], {'dtype':'dtype0',
  2799. 'out': ('out0',),
  2800. 'axis': 'axis0'})
  2801. # reduceat, output equal to None removed.
  2802. res = np.multiply.reduceat(a, [4, 2], 0, None, None)
  2803. assert_equal(res[4], {'axis': 0, 'dtype': None})
  2804. res = np.multiply.reduceat(a, [4, 2], axis=None, out=None, dtype='dt')
  2805. assert_equal(res[4], {'axis': None, 'dtype': 'dt'})
  2806. res = np.multiply.reduceat(a, [4, 2], None, None, out=(None,))
  2807. assert_equal(res[4], {'axis': None, 'dtype': None})
  2808. # reduceat, wrong args
  2809. assert_raises(ValueError, np.multiply.reduce, a, [4, 2], out=())
  2810. assert_raises(ValueError, np.multiply.reduce, a, [4, 2],
  2811. out=('out0', 'out1'))
  2812. assert_raises(TypeError, np.multiply.reduce, a, [4, 2],
  2813. 'axis0', axis='axis0')
  2814. # outer
  2815. res = np.multiply.outer(a, 42)
  2816. assert_equal(res[0], a)
  2817. assert_equal(res[1], np.multiply)
  2818. assert_equal(res[2], 'outer')
  2819. assert_equal(res[3], (a, 42))
  2820. assert_equal(res[4], {})
  2821. # outer, wrong args
  2822. assert_raises(TypeError, np.multiply.outer, a)
  2823. assert_raises(TypeError, np.multiply.outer, a, a, a, a)
  2824. assert_raises(TypeError, np.multiply.outer, a, a, sig='a', signature='a')
  2825. # at
  2826. res = np.multiply.at(a, [4, 2], 'b0')
  2827. assert_equal(res[0], a)
  2828. assert_equal(res[1], np.multiply)
  2829. assert_equal(res[2], 'at')
  2830. assert_equal(res[3], (a, [4, 2], 'b0'))
  2831. # at, wrong args
  2832. assert_raises(TypeError, np.multiply.at, a)
  2833. assert_raises(TypeError, np.multiply.at, a, a, a, a)
  2834. def test_ufunc_override_out(self):
  2835. class A:
  2836. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2837. return kwargs
  2838. class B:
  2839. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2840. return kwargs
  2841. a = A()
  2842. b = B()
  2843. res0 = np.multiply(a, b, 'out_arg')
  2844. res1 = np.multiply(a, b, out='out_arg')
  2845. res2 = np.multiply(2, b, 'out_arg')
  2846. res3 = np.multiply(3, b, out='out_arg')
  2847. res4 = np.multiply(a, 4, 'out_arg')
  2848. res5 = np.multiply(a, 5, out='out_arg')
  2849. assert_equal(res0['out'][0], 'out_arg')
  2850. assert_equal(res1['out'][0], 'out_arg')
  2851. assert_equal(res2['out'][0], 'out_arg')
  2852. assert_equal(res3['out'][0], 'out_arg')
  2853. assert_equal(res4['out'][0], 'out_arg')
  2854. assert_equal(res5['out'][0], 'out_arg')
  2855. # ufuncs with multiple output modf and frexp.
  2856. res6 = np.modf(a, 'out0', 'out1')
  2857. res7 = np.frexp(a, 'out0', 'out1')
  2858. assert_equal(res6['out'][0], 'out0')
  2859. assert_equal(res6['out'][1], 'out1')
  2860. assert_equal(res7['out'][0], 'out0')
  2861. assert_equal(res7['out'][1], 'out1')
  2862. # While we're at it, check that default output is never passed on.
  2863. assert_(np.sin(a, None) == {})
  2864. assert_(np.sin(a, out=None) == {})
  2865. assert_(np.sin(a, out=(None,)) == {})
  2866. assert_(np.modf(a, None) == {})
  2867. assert_(np.modf(a, None, None) == {})
  2868. assert_(np.modf(a, out=(None, None)) == {})
  2869. with assert_raises(TypeError):
  2870. # Out argument must be tuple, since there are multiple outputs.
  2871. np.modf(a, out=None)
  2872. # don't give positional and output argument, or too many arguments.
  2873. # wrong number of arguments in the tuple is an error too.
  2874. assert_raises(TypeError, np.multiply, a, b, 'one', out='two')
  2875. assert_raises(TypeError, np.multiply, a, b, 'one', 'two')
  2876. assert_raises(ValueError, np.multiply, a, b, out=('one', 'two'))
  2877. assert_raises(TypeError, np.multiply, a, out=())
  2878. assert_raises(TypeError, np.modf, a, 'one', out=('two', 'three'))
  2879. assert_raises(TypeError, np.modf, a, 'one', 'two', 'three')
  2880. assert_raises(ValueError, np.modf, a, out=('one', 'two', 'three'))
  2881. assert_raises(ValueError, np.modf, a, out=('one',))
  2882. def test_ufunc_override_exception(self):
  2883. class A:
  2884. def __array_ufunc__(self, *a, **kwargs):
  2885. raise ValueError("oops")
  2886. a = A()
  2887. assert_raises(ValueError, np.negative, 1, out=a)
  2888. assert_raises(ValueError, np.negative, a)
  2889. assert_raises(ValueError, np.divide, 1., a)
  2890. def test_ufunc_override_not_implemented(self):
  2891. class A:
  2892. def __array_ufunc__(self, *args, **kwargs):
  2893. return NotImplemented
  2894. msg = ("operand type(s) all returned NotImplemented from "
  2895. "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
  2896. with assert_raises_regex(TypeError, fnmatch.translate(msg)):
  2897. np.negative(A())
  2898. msg = ("operand type(s) all returned NotImplemented from "
  2899. "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
  2900. "out=(1,)): 'A', 'object', 'int'")
  2901. with assert_raises_regex(TypeError, fnmatch.translate(msg)):
  2902. np.add(A(), object(), out=1)
  2903. def test_ufunc_override_disabled(self):
  2904. class OptOut:
  2905. __array_ufunc__ = None
  2906. opt_out = OptOut()
  2907. # ufuncs always raise
  2908. msg = "operand 'OptOut' does not support ufuncs"
  2909. with assert_raises_regex(TypeError, msg):
  2910. np.add(opt_out, 1)
  2911. with assert_raises_regex(TypeError, msg):
  2912. np.add(1, opt_out)
  2913. with assert_raises_regex(TypeError, msg):
  2914. np.negative(opt_out)
  2915. # opt-outs still hold even when other arguments have pathological
  2916. # __array_ufunc__ implementations
  2917. class GreedyArray:
  2918. def __array_ufunc__(self, *args, **kwargs):
  2919. return self
  2920. greedy = GreedyArray()
  2921. assert_(np.negative(greedy) is greedy)
  2922. with assert_raises_regex(TypeError, msg):
  2923. np.add(greedy, opt_out)
  2924. with assert_raises_regex(TypeError, msg):
  2925. np.add(greedy, 1, out=opt_out)
  2926. def test_gufunc_override(self):
  2927. # gufunc are just ufunc instances, but follow a different path,
  2928. # so check __array_ufunc__ overrides them properly.
  2929. class A:
  2930. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  2931. return self, ufunc, method, inputs, kwargs
  2932. inner1d = ncu_tests.inner1d
  2933. a = A()
  2934. res = inner1d(a, a)
  2935. assert_equal(res[0], a)
  2936. assert_equal(res[1], inner1d)
  2937. assert_equal(res[2], '__call__')
  2938. assert_equal(res[3], (a, a))
  2939. assert_equal(res[4], {})
  2940. res = inner1d(1, 1, out=a)
  2941. assert_equal(res[0], a)
  2942. assert_equal(res[1], inner1d)
  2943. assert_equal(res[2], '__call__')
  2944. assert_equal(res[3], (1, 1))
  2945. assert_equal(res[4], {'out': (a,)})
  2946. # wrong number of arguments in the tuple is an error too.
  2947. assert_raises(TypeError, inner1d, a, out='two')
  2948. assert_raises(TypeError, inner1d, a, a, 'one', out='two')
  2949. assert_raises(TypeError, inner1d, a, a, 'one', 'two')
  2950. assert_raises(ValueError, inner1d, a, a, out=('one', 'two'))
  2951. assert_raises(ValueError, inner1d, a, a, out=())
  2952. def test_ufunc_override_with_super(self):
  2953. # NOTE: this class is used in doc/source/user/basics.subclassing.rst
  2954. # if you make any changes here, do update it there too.
  2955. class A(np.ndarray):
  2956. def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
  2957. args = []
  2958. in_no = []
  2959. for i, input_ in enumerate(inputs):
  2960. if isinstance(input_, A):
  2961. in_no.append(i)
  2962. args.append(input_.view(np.ndarray))
  2963. else:
  2964. args.append(input_)
  2965. outputs = out
  2966. out_no = []
  2967. if outputs:
  2968. out_args = []
  2969. for j, output in enumerate(outputs):
  2970. if isinstance(output, A):
  2971. out_no.append(j)
  2972. out_args.append(output.view(np.ndarray))
  2973. else:
  2974. out_args.append(output)
  2975. kwargs['out'] = tuple(out_args)
  2976. else:
  2977. outputs = (None,) * ufunc.nout
  2978. info = {}
  2979. if in_no:
  2980. info['inputs'] = in_no
  2981. if out_no:
  2982. info['outputs'] = out_no
  2983. results = super().__array_ufunc__(ufunc, method,
  2984. *args, **kwargs)
  2985. if results is NotImplemented:
  2986. return NotImplemented
  2987. if method == 'at':
  2988. if isinstance(inputs[0], A):
  2989. inputs[0].info = info
  2990. return
  2991. if ufunc.nout == 1:
  2992. results = (results,)
  2993. results = tuple((np.asarray(result).view(A)
  2994. if output is None else output)
  2995. for result, output in zip(results, outputs))
  2996. if results and isinstance(results[0], A):
  2997. results[0].info = info
  2998. return results[0] if len(results) == 1 else results
  2999. class B:
  3000. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  3001. if any(isinstance(input_, A) for input_ in inputs):
  3002. return "A!"
  3003. else:
  3004. return NotImplemented
  3005. d = np.arange(5.)
  3006. # 1 input, 1 output
  3007. a = np.arange(5.).view(A)
  3008. b = np.sin(a)
  3009. check = np.sin(d)
  3010. assert_(np.all(check == b))
  3011. assert_equal(b.info, {'inputs': [0]})
  3012. b = np.sin(d, out=(a,))
  3013. assert_(np.all(check == b))
  3014. assert_equal(b.info, {'outputs': [0]})
  3015. assert_(b is a)
  3016. a = np.arange(5.).view(A)
  3017. b = np.sin(a, out=a)
  3018. assert_(np.all(check == b))
  3019. assert_equal(b.info, {'inputs': [0], 'outputs': [0]})
  3020. # 1 input, 2 outputs
  3021. a = np.arange(5.).view(A)
  3022. b1, b2 = np.modf(a)
  3023. assert_equal(b1.info, {'inputs': [0]})
  3024. b1, b2 = np.modf(d, out=(None, a))
  3025. assert_(b2 is a)
  3026. assert_equal(b1.info, {'outputs': [1]})
  3027. a = np.arange(5.).view(A)
  3028. b = np.arange(5.).view(A)
  3029. c1, c2 = np.modf(a, out=(a, b))
  3030. assert_(c1 is a)
  3031. assert_(c2 is b)
  3032. assert_equal(c1.info, {'inputs': [0], 'outputs': [0, 1]})
  3033. # 2 input, 1 output
  3034. a = np.arange(5.).view(A)
  3035. b = np.arange(5.).view(A)
  3036. c = np.add(a, b, out=a)
  3037. assert_(c is a)
  3038. assert_equal(c.info, {'inputs': [0, 1], 'outputs': [0]})
  3039. # some tests with a non-ndarray subclass
  3040. a = np.arange(5.)
  3041. b = B()
  3042. assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  3043. assert_(b.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  3044. assert_raises(TypeError, np.add, a, b)
  3045. a = a.view(A)
  3046. assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
  3047. assert_(b.__array_ufunc__(np.add, '__call__', a, b) == "A!")
  3048. assert_(np.add(a, b) == "A!")
  3049. # regression check for gh-9102 -- tests ufunc.reduce implicitly.
  3050. d = np.array([[1, 2, 3], [1, 2, 3]])
  3051. a = d.view(A)
  3052. c = a.any()
  3053. check = d.any()
  3054. assert_equal(c, check)
  3055. assert_(c.info, {'inputs': [0]})
  3056. c = a.max()
  3057. check = d.max()
  3058. assert_equal(c, check)
  3059. assert_(c.info, {'inputs': [0]})
  3060. b = np.array(0).view(A)
  3061. c = a.max(out=b)
  3062. assert_equal(c, check)
  3063. assert_(c is b)
  3064. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  3065. check = a.max(axis=0)
  3066. b = np.zeros_like(check).view(A)
  3067. c = a.max(axis=0, out=b)
  3068. assert_equal(c, check)
  3069. assert_(c is b)
  3070. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  3071. # simple explicit tests of reduce, accumulate, reduceat
  3072. check = np.add.reduce(d, axis=1)
  3073. c = np.add.reduce(a, axis=1)
  3074. assert_equal(c, check)
  3075. assert_(c.info, {'inputs': [0]})
  3076. b = np.zeros_like(c)
  3077. c = np.add.reduce(a, 1, None, b)
  3078. assert_equal(c, check)
  3079. assert_(c is b)
  3080. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  3081. check = np.add.accumulate(d, axis=0)
  3082. c = np.add.accumulate(a, axis=0)
  3083. assert_equal(c, check)
  3084. assert_(c.info, {'inputs': [0]})
  3085. b = np.zeros_like(c)
  3086. c = np.add.accumulate(a, 0, None, b)
  3087. assert_equal(c, check)
  3088. assert_(c is b)
  3089. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  3090. indices = [0, 2, 1]
  3091. check = np.add.reduceat(d, indices, axis=1)
  3092. c = np.add.reduceat(a, indices, axis=1)
  3093. assert_equal(c, check)
  3094. assert_(c.info, {'inputs': [0]})
  3095. b = np.zeros_like(c)
  3096. c = np.add.reduceat(a, indices, 1, None, b)
  3097. assert_equal(c, check)
  3098. assert_(c is b)
  3099. assert_(c.info, {'inputs': [0], 'outputs': [0]})
  3100. # and a few tests for at
  3101. d = np.array([[1, 2, 3], [1, 2, 3]])
  3102. check = d.copy()
  3103. a = d.copy().view(A)
  3104. np.add.at(check, ([0, 1], [0, 2]), 1.)
  3105. np.add.at(a, ([0, 1], [0, 2]), 1.)
  3106. assert_equal(a, check)
  3107. assert_(a.info, {'inputs': [0]})
  3108. b = np.array(1.).view(A)
  3109. a = d.copy().view(A)
  3110. np.add.at(a, ([0, 1], [0, 2]), b)
  3111. assert_equal(a, check)
  3112. assert_(a.info, {'inputs': [0, 2]})
  3113. class TestChoose:
  3114. def test_mixed(self):
  3115. c = np.array([True, True])
  3116. a = np.array([True, True])
  3117. assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))
  3118. class TestRationalFunctions:
  3119. def test_lcm(self):
  3120. self._test_lcm_inner(np.int16)
  3121. self._test_lcm_inner(np.uint16)
  3122. def test_lcm_object(self):
  3123. self._test_lcm_inner(np.object_)
  3124. def test_gcd(self):
  3125. self._test_gcd_inner(np.int16)
  3126. self._test_lcm_inner(np.uint16)
  3127. def test_gcd_object(self):
  3128. self._test_gcd_inner(np.object_)
  3129. def _test_lcm_inner(self, dtype):
  3130. # basic use
  3131. a = np.array([12, 120], dtype=dtype)
  3132. b = np.array([20, 200], dtype=dtype)
  3133. assert_equal(np.lcm(a, b), [60, 600])
  3134. if not issubclass(dtype, np.unsignedinteger):
  3135. # negatives are ignored
  3136. a = np.array([12, -12, 12, -12], dtype=dtype)
  3137. b = np.array([20, 20, -20, -20], dtype=dtype)
  3138. assert_equal(np.lcm(a, b), [60]*4)
  3139. # reduce
  3140. a = np.array([3, 12, 20], dtype=dtype)
  3141. assert_equal(np.lcm.reduce([3, 12, 20]), 60)
  3142. # broadcasting, and a test including 0
  3143. a = np.arange(6).astype(dtype)
  3144. b = 20
  3145. assert_equal(np.lcm(a, b), [0, 20, 20, 60, 20, 20])
  3146. def _test_gcd_inner(self, dtype):
  3147. # basic use
  3148. a = np.array([12, 120], dtype=dtype)
  3149. b = np.array([20, 200], dtype=dtype)
  3150. assert_equal(np.gcd(a, b), [4, 40])
  3151. if not issubclass(dtype, np.unsignedinteger):
  3152. # negatives are ignored
  3153. a = np.array([12, -12, 12, -12], dtype=dtype)
  3154. b = np.array([20, 20, -20, -20], dtype=dtype)
  3155. assert_equal(np.gcd(a, b), [4]*4)
  3156. # reduce
  3157. a = np.array([15, 25, 35], dtype=dtype)
  3158. assert_equal(np.gcd.reduce(a), 5)
  3159. # broadcasting, and a test including 0
  3160. a = np.arange(6).astype(dtype)
  3161. b = 20
  3162. assert_equal(np.gcd(a, b), [20, 1, 2, 1, 4, 5])
  3163. def test_lcm_overflow(self):
  3164. # verify that we don't overflow when a*b does overflow
  3165. big = np.int32(np.iinfo(np.int32).max // 11)
  3166. a = 2*big
  3167. b = 5*big
  3168. assert_equal(np.lcm(a, b), 10*big)
  3169. def test_gcd_overflow(self):
  3170. for dtype in (np.int32, np.int64):
  3171. # verify that we don't overflow when taking abs(x)
  3172. # not relevant for lcm, where the result is unrepresentable anyway
  3173. a = dtype(np.iinfo(dtype).min) # negative power of two
  3174. q = -(a // 4)
  3175. assert_equal(np.gcd(a, q*3), q)
  3176. assert_equal(np.gcd(a, -q*3), q)
  3177. def test_decimal(self):
  3178. from decimal import Decimal
  3179. a = np.array([1, 1, -1, -1]) * Decimal('0.20')
  3180. b = np.array([1, -1, 1, -1]) * Decimal('0.12')
  3181. assert_equal(np.gcd(a, b), 4*[Decimal('0.04')])
  3182. assert_equal(np.lcm(a, b), 4*[Decimal('0.60')])
  3183. def test_float(self):
  3184. # not well-defined on float due to rounding errors
  3185. assert_raises(TypeError, np.gcd, 0.3, 0.4)
  3186. assert_raises(TypeError, np.lcm, 0.3, 0.4)
  3187. def test_builtin_long(self):
  3188. # sanity check that array coercion is alright for builtin longs
  3189. assert_equal(np.array(2**200).item(), 2**200)
  3190. # expressed as prime factors
  3191. a = np.array(2**100 * 3**5)
  3192. b = np.array([2**100 * 5**7, 2**50 * 3**10])
  3193. assert_equal(np.gcd(a, b), [2**100, 2**50 * 3**5])
  3194. assert_equal(np.lcm(a, b), [2**100 * 3**5 * 5**7, 2**100 * 3**10])
  3195. assert_equal(np.gcd(2**100, 3**100), 1)
  3196. class TestRoundingFunctions:
  3197. def test_object_direct(self):
  3198. """ test direct implementation of these magic methods """
  3199. class C:
  3200. def __floor__(self):
  3201. return 1
  3202. def __ceil__(self):
  3203. return 2
  3204. def __trunc__(self):
  3205. return 3
  3206. arr = np.array([C(), C()])
  3207. assert_equal(np.floor(arr), [1, 1])
  3208. assert_equal(np.ceil(arr), [2, 2])
  3209. assert_equal(np.trunc(arr), [3, 3])
  3210. def test_object_indirect(self):
  3211. """ test implementations via __float__ """
  3212. class C:
  3213. def __float__(self):
  3214. return -2.5
  3215. arr = np.array([C(), C()])
  3216. assert_equal(np.floor(arr), [-3, -3])
  3217. assert_equal(np.ceil(arr), [-2, -2])
  3218. with pytest.raises(TypeError):
  3219. np.trunc(arr) # consistent with math.trunc
  3220. def test_fraction(self):
  3221. f = Fraction(-4, 3)
  3222. assert_equal(np.floor(f), -2)
  3223. assert_equal(np.ceil(f), -1)
  3224. assert_equal(np.trunc(f), -1)
  3225. class TestComplexFunctions:
  3226. funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh,
  3227. np.arctanh, np.sin, np.cos, np.tan, np.exp,
  3228. np.exp2, np.log, np.sqrt, np.log10, np.log2,
  3229. np.log1p]
  3230. def test_it(self):
  3231. for f in self.funcs:
  3232. if f is np.arccosh:
  3233. x = 1.5
  3234. else:
  3235. x = .5
  3236. fr = f(x)
  3237. fz = f(complex(x))
  3238. assert_almost_equal(fz.real, fr, err_msg='real part %s' % f)
  3239. assert_almost_equal(fz.imag, 0., err_msg='imag part %s' % f)
  3240. @pytest.mark.xfail(IS_WASM, reason="doesn't work")
  3241. def test_precisions_consistent(self):
  3242. z = 1 + 1j
  3243. for f in self.funcs:
  3244. fcf = f(np.csingle(z))
  3245. fcd = f(np.cdouble(z))
  3246. fcl = f(np.clongdouble(z))
  3247. assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s' % f)
  3248. assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s' % f)
  3249. @pytest.mark.xfail(IS_WASM, reason="doesn't work")
  3250. def test_branch_cuts(self):
  3251. # check branch cuts and continuity on them
  3252. _check_branch_cut(np.log, -0.5, 1j, 1, -1, True)
  3253. _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True)
  3254. _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True)
  3255. _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True)
  3256. _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True)
  3257. _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True)
  3258. _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True)
  3259. _check_branch_cut(np.arctan, [0-2j, 2j], [1, 1], -1, 1, True)
  3260. _check_branch_cut(np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True)
  3261. _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True)
  3262. _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True)
  3263. # check against bogus branch cuts: assert continuity between quadrants
  3264. _check_branch_cut(np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1)
  3265. _check_branch_cut(np.arccos, [0-2j, 2j], [ 1, 1], 1, 1)
  3266. _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1)
  3267. _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1)
  3268. _check_branch_cut(np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1)
  3269. _check_branch_cut(np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1)
  3270. @pytest.mark.xfail(IS_WASM, reason="doesn't work")
  3271. def test_branch_cuts_complex64(self):
  3272. # check branch cuts and continuity on them
  3273. _check_branch_cut(np.log, -0.5, 1j, 1, -1, True, np.complex64)
  3274. _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True, np.complex64)
  3275. _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True, np.complex64)
  3276. _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True, np.complex64)
  3277. _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True, np.complex64)
  3278. _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  3279. _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  3280. _check_branch_cut(np.arctan, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64)
  3281. _check_branch_cut(np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64)
  3282. _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64)
  3283. _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
  3284. # check against bogus branch cuts: assert continuity between quadrants
  3285. _check_branch_cut(np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
  3286. _check_branch_cut(np.arccos, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
  3287. _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64)
  3288. _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64)
  3289. _check_branch_cut(np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64)
  3290. _check_branch_cut(np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64)
  3291. def test_against_cmath(self):
  3292. import cmath
  3293. points = [-1-1j, -1+1j, +1-1j, +1+1j]
  3294. name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
  3295. 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
  3296. atol = 4*np.finfo(complex).eps
  3297. for func in self.funcs:
  3298. fname = func.__name__.split('.')[-1]
  3299. cname = name_map.get(fname, fname)
  3300. try:
  3301. cfunc = getattr(cmath, cname)
  3302. except AttributeError:
  3303. continue
  3304. for p in points:
  3305. a = complex(func(np.complex_(p)))
  3306. b = cfunc(p)
  3307. assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
  3308. @pytest.mark.xfail(IS_WASM, reason="doesn't work")
  3309. @pytest.mark.parametrize('dtype', [np.complex64, np.complex_, np.longcomplex])
  3310. def test_loss_of_precision(self, dtype):
  3311. """Check loss of precision in complex arc* functions"""
  3312. # Check against known-good functions
  3313. info = np.finfo(dtype)
  3314. real_dtype = dtype(0.).real.dtype
  3315. eps = info.eps
  3316. def check(x, rtol):
  3317. x = x.astype(real_dtype)
  3318. z = x.astype(dtype)
  3319. d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1)
  3320. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  3321. 'arcsinh'))
  3322. z = (1j*x).astype(dtype)
  3323. d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1)
  3324. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  3325. 'arcsin'))
  3326. z = x.astype(dtype)
  3327. d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1)
  3328. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  3329. 'arctanh'))
  3330. z = (1j*x).astype(dtype)
  3331. d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1)
  3332. assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
  3333. 'arctan'))
  3334. # The switchover was chosen as 1e-3; hence there can be up to
  3335. # ~eps/1e-3 of relative cancellation error before it
  3336. x_series = np.logspace(-20, -3.001, 200)
  3337. x_basic = np.logspace(-2.999, 0, 10, endpoint=False)
  3338. if dtype is np.longcomplex:
  3339. if bad_arcsinh():
  3340. pytest.skip("Trig functions of np.longcomplex values known "
  3341. "to be inaccurate on aarch64 and PPC for some "
  3342. "compilation configurations.")
  3343. # It's not guaranteed that the system-provided arc functions
  3344. # are accurate down to a few epsilons. (Eg. on Linux 64-bit)
  3345. # So, give more leeway for long complex tests here:
  3346. check(x_series, 50.0*eps)
  3347. else:
  3348. check(x_series, 2.1*eps)
  3349. check(x_basic, 2.0*eps/1e-3)
  3350. # Check a few points
  3351. z = np.array([1e-5*(1+1j)], dtype=dtype)
  3352. p = 9.999999999333333333e-6 + 1.000000000066666666e-5j
  3353. d = np.absolute(1-np.arctanh(z)/p)
  3354. assert_(np.all(d < 1e-15))
  3355. p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j
  3356. d = np.absolute(1-np.arcsinh(z)/p)
  3357. assert_(np.all(d < 1e-15))
  3358. p = 9.999999999333333333e-6j + 1.000000000066666666e-5
  3359. d = np.absolute(1-np.arctan(z)/p)
  3360. assert_(np.all(d < 1e-15))
  3361. p = 1.0000000000333333333e-5j + 9.999999999666666667e-6
  3362. d = np.absolute(1-np.arcsin(z)/p)
  3363. assert_(np.all(d < 1e-15))
  3364. # Check continuity across switchover points
  3365. def check(func, z0, d=1):
  3366. z0 = np.asarray(z0, dtype=dtype)
  3367. zp = z0 + abs(z0) * d * eps * 2
  3368. zm = z0 - abs(z0) * d * eps * 2
  3369. assert_(np.all(zp != zm), (zp, zm))
  3370. # NB: the cancellation error at the switchover is at least eps
  3371. good = (abs(func(zp) - func(zm)) < 2*eps)
  3372. assert_(np.all(good), (func, z0[~good]))
  3373. for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan):
  3374. pts = [rp+1j*ip for rp in (-1e-3, 0, 1e-3) for ip in(-1e-3, 0, 1e-3)
  3375. if rp != 0 or ip != 0]
  3376. check(func, pts, 1)
  3377. check(func, pts, 1j)
  3378. check(func, pts, 1+1j)
  3379. @np.errstate(all="ignore")
  3380. def test_promotion_corner_cases(self):
  3381. for func in self.funcs:
  3382. assert func(np.float16(1)).dtype == np.float16
  3383. # Integer to low precision float promotion is a dubious choice:
  3384. assert func(np.uint8(1)).dtype == np.float16
  3385. assert func(np.int16(1)).dtype == np.float32
  3386. class TestAttributes:
  3387. def test_attributes(self):
  3388. add = ncu.add
  3389. assert_equal(add.__name__, 'add')
  3390. assert_(add.ntypes >= 18) # don't fail if types added
  3391. assert_('ii->i' in add.types)
  3392. assert_equal(add.nin, 2)
  3393. assert_equal(add.nout, 1)
  3394. assert_equal(add.identity, 0)
  3395. def test_doc(self):
  3396. # don't bother checking the long list of kwargs, which are likely to
  3397. # change
  3398. assert_(ncu.add.__doc__.startswith(
  3399. "add(x1, x2, /, out=None, *, where=True"))
  3400. assert_(ncu.frexp.__doc__.startswith(
  3401. "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True"))
  3402. class TestSubclass:
  3403. def test_subclass_op(self):
  3404. class simple(np.ndarray):
  3405. def __new__(subtype, shape):
  3406. self = np.ndarray.__new__(subtype, shape, dtype=object)
  3407. self.fill(0)
  3408. return self
  3409. a = simple((3, 4))
  3410. assert_equal(a+a, a)
  3411. class TestFrompyfunc:
  3412. def test_identity(self):
  3413. def mul(a, b):
  3414. return a * b
  3415. # with identity=value
  3416. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=1)
  3417. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  3418. assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
  3419. assert_equal(mul_ufunc.reduce([]), 1)
  3420. # with identity=None (reorderable)
  3421. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=None)
  3422. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  3423. assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
  3424. assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
  3425. # with no identity (not reorderable)
  3426. mul_ufunc = np.frompyfunc(mul, nin=2, nout=1)
  3427. assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
  3428. assert_raises(ValueError, lambda: mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)))
  3429. assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
  3430. def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False,
  3431. dtype=complex):
  3432. """
  3433. Check for a branch cut in a function.
  3434. Assert that `x0` lies on a branch cut of function `f` and `f` is
  3435. continuous from the direction `dx`.
  3436. Parameters
  3437. ----------
  3438. f : func
  3439. Function to check
  3440. x0 : array-like
  3441. Point on branch cut
  3442. dx : array-like
  3443. Direction to check continuity in
  3444. re_sign, im_sign : {1, -1}
  3445. Change of sign of the real or imaginary part expected
  3446. sig_zero_ok : bool
  3447. Whether to check if the branch cut respects signed zero (if applicable)
  3448. dtype : dtype
  3449. Dtype to check (should be complex)
  3450. """
  3451. x0 = np.atleast_1d(x0).astype(dtype)
  3452. dx = np.atleast_1d(dx).astype(dtype)
  3453. if np.dtype(dtype).char == 'F':
  3454. scale = np.finfo(dtype).eps * 1e2
  3455. atol = np.float32(1e-2)
  3456. else:
  3457. scale = np.finfo(dtype).eps * 1e3
  3458. atol = 1e-4
  3459. y0 = f(x0)
  3460. yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx))
  3461. ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx))
  3462. assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp))
  3463. assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp))
  3464. assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym))
  3465. assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym))
  3466. if sig_zero_ok:
  3467. # check that signed zeros also work as a displacement
  3468. jr = (x0.real == 0) & (dx.real != 0)
  3469. ji = (x0.imag == 0) & (dx.imag != 0)
  3470. if np.any(jr):
  3471. x = x0[jr]
  3472. x.real = np.NZERO
  3473. ym = f(x)
  3474. assert_(np.all(np.absolute(y0[jr].real - ym.real*re_sign) < atol), (y0[jr], ym))
  3475. assert_(np.all(np.absolute(y0[jr].imag - ym.imag*im_sign) < atol), (y0[jr], ym))
  3476. if np.any(ji):
  3477. x = x0[ji]
  3478. x.imag = np.NZERO
  3479. ym = f(x)
  3480. assert_(np.all(np.absolute(y0[ji].real - ym.real*re_sign) < atol), (y0[ji], ym))
  3481. assert_(np.all(np.absolute(y0[ji].imag - ym.imag*im_sign) < atol), (y0[ji], ym))
  3482. def test_copysign():
  3483. assert_(np.copysign(1, -1) == -1)
  3484. with np.errstate(divide="ignore"):
  3485. assert_(1 / np.copysign(0, -1) < 0)
  3486. assert_(1 / np.copysign(0, 1) > 0)
  3487. assert_(np.signbit(np.copysign(np.nan, -1)))
  3488. assert_(not np.signbit(np.copysign(np.nan, 1)))
  3489. def _test_nextafter(t):
  3490. one = t(1)
  3491. two = t(2)
  3492. zero = t(0)
  3493. eps = np.finfo(t).eps
  3494. assert_(np.nextafter(one, two) - one == eps)
  3495. assert_(np.nextafter(one, zero) - one < 0)
  3496. assert_(np.isnan(np.nextafter(np.nan, one)))
  3497. assert_(np.isnan(np.nextafter(one, np.nan)))
  3498. assert_(np.nextafter(one, one) == one)
  3499. def test_nextafter():
  3500. return _test_nextafter(np.float64)
  3501. def test_nextafterf():
  3502. return _test_nextafter(np.float32)
  3503. @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
  3504. reason="long double is same as double")
  3505. @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
  3506. reason="IBM double double")
  3507. def test_nextafterl():
  3508. return _test_nextafter(np.longdouble)
  3509. def test_nextafter_0():
  3510. for t, direction in itertools.product(np.sctypes['float'], (1, -1)):
  3511. # The value of tiny for double double is NaN, so we need to pass the
  3512. # assert
  3513. with suppress_warnings() as sup:
  3514. sup.filter(UserWarning)
  3515. if not np.isnan(np.finfo(t).tiny):
  3516. tiny = np.finfo(t).tiny
  3517. assert_(
  3518. 0. < direction * np.nextafter(t(0), t(direction)) < tiny)
  3519. assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0)
  3520. def _test_spacing(t):
  3521. one = t(1)
  3522. eps = np.finfo(t).eps
  3523. nan = t(np.nan)
  3524. inf = t(np.inf)
  3525. with np.errstate(invalid='ignore'):
  3526. assert_(np.spacing(one) == eps)
  3527. assert_(np.isnan(np.spacing(nan)))
  3528. assert_(np.isnan(np.spacing(inf)))
  3529. assert_(np.isnan(np.spacing(-inf)))
  3530. assert_(np.spacing(t(1e30)) != 0)
  3531. def test_spacing():
  3532. return _test_spacing(np.float64)
  3533. def test_spacingf():
  3534. return _test_spacing(np.float32)
  3535. @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
  3536. reason="long double is same as double")
  3537. @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
  3538. reason="IBM double double")
  3539. def test_spacingl():
  3540. return _test_spacing(np.longdouble)
  3541. def test_spacing_gfortran():
  3542. # Reference from this fortran file, built with gfortran 4.3.3 on linux
  3543. # 32bits:
  3544. # PROGRAM test_spacing
  3545. # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37)
  3546. # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200)
  3547. #
  3548. # WRITE(*,*) spacing(0.00001_DBL)
  3549. # WRITE(*,*) spacing(1.0_DBL)
  3550. # WRITE(*,*) spacing(1000._DBL)
  3551. # WRITE(*,*) spacing(10500._DBL)
  3552. #
  3553. # WRITE(*,*) spacing(0.00001_SGL)
  3554. # WRITE(*,*) spacing(1.0_SGL)
  3555. # WRITE(*,*) spacing(1000._SGL)
  3556. # WRITE(*,*) spacing(10500._SGL)
  3557. # END PROGRAM
  3558. ref = {np.float64: [1.69406589450860068E-021,
  3559. 2.22044604925031308E-016,
  3560. 1.13686837721616030E-013,
  3561. 1.81898940354585648E-012],
  3562. np.float32: [9.09494702E-13,
  3563. 1.19209290E-07,
  3564. 6.10351563E-05,
  3565. 9.76562500E-04]}
  3566. for dt, dec_ in zip([np.float32, np.float64], (10, 20)):
  3567. x = np.array([1e-5, 1, 1000, 10500], dtype=dt)
  3568. assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec_)
  3569. def test_nextafter_vs_spacing():
  3570. # XXX: spacing does not handle long double yet
  3571. for t in [np.float32, np.float64]:
  3572. for _f in [1, 1e-5, 1000]:
  3573. f = t(_f)
  3574. f1 = t(_f + 1)
  3575. assert_(np.nextafter(f, f1) - f == np.spacing(f))
  3576. def test_pos_nan():
  3577. """Check np.nan is a positive nan."""
  3578. assert_(np.signbit(np.nan) == 0)
  3579. def test_reduceat():
  3580. """Test bug in reduceat when structured arrays are not copied."""
  3581. db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
  3582. a = np.empty([100], dtype=db)
  3583. a['name'] = 'Simple'
  3584. a['time'] = 10
  3585. a['value'] = 100
  3586. indx = [0, 7, 15, 25]
  3587. h2 = []
  3588. val1 = indx[0]
  3589. for val2 in indx[1:]:
  3590. h2.append(np.add.reduce(a['value'][val1:val2]))
  3591. val1 = val2
  3592. h2.append(np.add.reduce(a['value'][val1:]))
  3593. h2 = np.array(h2)
  3594. # test buffered -- this should work
  3595. h1 = np.add.reduceat(a['value'], indx)
  3596. assert_array_almost_equal(h1, h2)
  3597. # This is when the error occurs.
  3598. # test no buffer
  3599. np.setbufsize(32)
  3600. h1 = np.add.reduceat(a['value'], indx)
  3601. np.setbufsize(np.UFUNC_BUFSIZE_DEFAULT)
  3602. assert_array_almost_equal(h1, h2)
  3603. def test_reduceat_empty():
  3604. """Reduceat should work with empty arrays"""
  3605. indices = np.array([], 'i4')
  3606. x = np.array([], 'f8')
  3607. result = np.add.reduceat(x, indices)
  3608. assert_equal(result.dtype, x.dtype)
  3609. assert_equal(result.shape, (0,))
  3610. # Another case with a slightly different zero-sized shape
  3611. x = np.ones((5, 2))
  3612. result = np.add.reduceat(x, [], axis=0)
  3613. assert_equal(result.dtype, x.dtype)
  3614. assert_equal(result.shape, (0, 2))
  3615. result = np.add.reduceat(x, [], axis=1)
  3616. assert_equal(result.dtype, x.dtype)
  3617. assert_equal(result.shape, (5, 0))
  3618. def test_complex_nan_comparisons():
  3619. nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
  3620. fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
  3621. complex(1, 1), complex(-1, -1), complex(0, 0)]
  3622. with np.errstate(invalid='ignore'):
  3623. for x in nans + fins:
  3624. x = np.array([x])
  3625. for y in nans + fins:
  3626. y = np.array([y])
  3627. if np.isfinite(x) and np.isfinite(y):
  3628. continue
  3629. assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
  3630. assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
  3631. assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
  3632. assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
  3633. assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
  3634. def test_rint_big_int():
  3635. # np.rint bug for large integer values on Windows 32-bit and MKL
  3636. # https://github.com/numpy/numpy/issues/6685
  3637. val = 4607998452777363968
  3638. # This is exactly representable in floating point
  3639. assert_equal(val, int(float(val)))
  3640. # Rint should not change the value
  3641. assert_equal(val, np.rint(val))
  3642. @pytest.mark.parametrize('ftype', [np.float32, np.float64])
  3643. def test_memoverlap_accumulate(ftype):
  3644. # Reproduces bug https://github.com/numpy/numpy/issues/15597
  3645. arr = np.array([0.61, 0.60, 0.77, 0.41, 0.19], dtype=ftype)
  3646. out_max = np.array([0.61, 0.61, 0.77, 0.77, 0.77], dtype=ftype)
  3647. out_min = np.array([0.61, 0.60, 0.60, 0.41, 0.19], dtype=ftype)
  3648. assert_equal(np.maximum.accumulate(arr), out_max)
  3649. assert_equal(np.minimum.accumulate(arr), out_min)
  3650. @pytest.mark.parametrize("ufunc, dtype", [
  3651. (ufunc, t[0])
  3652. for ufunc in UFUNCS_BINARY_ACC
  3653. for t in ufunc.types
  3654. if t[-1] == '?' and t[0] not in 'DFGMmO'
  3655. ])
  3656. def test_memoverlap_accumulate_cmp(ufunc, dtype):
  3657. if ufunc.signature:
  3658. pytest.skip('For generic signatures only')
  3659. for size in (2, 8, 32, 64, 128, 256):
  3660. arr = np.array([0, 1, 1]*size, dtype=dtype)
  3661. acc = ufunc.accumulate(arr, dtype='?')
  3662. acc_u8 = acc.view(np.uint8)
  3663. exp = np.array(list(itertools.accumulate(arr, ufunc)), dtype=np.uint8)
  3664. assert_equal(exp, acc_u8)
  3665. @pytest.mark.parametrize("ufunc, dtype", [
  3666. (ufunc, t[0])
  3667. for ufunc in UFUNCS_BINARY_ACC
  3668. for t in ufunc.types
  3669. if t[0] == t[1] and t[0] == t[-1] and t[0] not in 'DFGMmO?'
  3670. ])
  3671. def test_memoverlap_accumulate_symmetric(ufunc, dtype):
  3672. if ufunc.signature:
  3673. pytest.skip('For generic signatures only')
  3674. with np.errstate(all='ignore'):
  3675. for size in (2, 8, 32, 64, 128, 256):
  3676. arr = np.array([0, 1, 2]*size).astype(dtype)
  3677. acc = ufunc.accumulate(arr, dtype=dtype)
  3678. exp = np.array(list(itertools.accumulate(arr, ufunc)), dtype=dtype)
  3679. assert_equal(exp, acc)
  3680. def test_signaling_nan_exceptions():
  3681. with assert_no_warnings():
  3682. a = np.ndarray(shape=(), dtype='float32', buffer=b'\x00\xe0\xbf\xff')
  3683. np.isnan(a)
  3684. @pytest.mark.parametrize("arr", [
  3685. np.arange(2),
  3686. np.matrix([0, 1]),
  3687. np.matrix([[0, 1], [2, 5]]),
  3688. ])
  3689. def test_outer_subclass_preserve(arr):
  3690. # for gh-8661
  3691. class foo(np.ndarray): pass
  3692. actual = np.multiply.outer(arr.view(foo), arr.view(foo))
  3693. assert actual.__class__.__name__ == 'foo'
  3694. def test_outer_bad_subclass():
  3695. class BadArr1(np.ndarray):
  3696. def __array_finalize__(self, obj):
  3697. # The outer call reshapes to 3 dims, try to do a bad reshape.
  3698. if self.ndim == 3:
  3699. self.shape = self.shape + (1,)
  3700. def __array_prepare__(self, obj, context=None):
  3701. return obj
  3702. class BadArr2(np.ndarray):
  3703. def __array_finalize__(self, obj):
  3704. if isinstance(obj, BadArr2):
  3705. # outer inserts 1-sized dims. In that case disturb them.
  3706. if self.shape[-1] == 1:
  3707. self.shape = self.shape[::-1]
  3708. def __array_prepare__(self, obj, context=None):
  3709. return obj
  3710. for cls in [BadArr1, BadArr2]:
  3711. arr = np.ones((2, 3)).view(cls)
  3712. with assert_raises(TypeError) as a:
  3713. # The first array gets reshaped (not the second one)
  3714. np.add.outer(arr, [1, 2])
  3715. # This actually works, since we only see the reshaping error:
  3716. arr = np.ones((2, 3)).view(cls)
  3717. assert type(np.add.outer([1, 2], arr)) is cls
  3718. def test_outer_exceeds_maxdims():
  3719. deep = np.ones((1,) * 17)
  3720. with assert_raises(ValueError):
  3721. np.add.outer(deep, deep)
  3722. def test_bad_legacy_ufunc_silent_errors():
  3723. # legacy ufuncs can't report errors and NumPy can't check if the GIL
  3724. # is released. So NumPy has to check after the GIL is released just to
  3725. # cover all bases. `np.power` uses/used to use this.
  3726. arr = np.arange(3).astype(np.float64)
  3727. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3728. ncu_tests.always_error(arr, arr)
  3729. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3730. # not contiguous means the fast-path cannot be taken
  3731. non_contig = arr.repeat(20).reshape(-1, 6)[:, ::2]
  3732. ncu_tests.always_error(non_contig, arr)
  3733. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3734. ncu_tests.always_error.outer(arr, arr)
  3735. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3736. ncu_tests.always_error.reduce(arr)
  3737. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3738. ncu_tests.always_error.reduceat(arr, [0, 1])
  3739. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3740. ncu_tests.always_error.accumulate(arr)
  3741. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3742. ncu_tests.always_error.at(arr, [0, 1, 2], arr)
  3743. @pytest.mark.parametrize('x1', [np.arange(3.0), [0.0, 1.0, 2.0]])
  3744. def test_bad_legacy_gufunc_silent_errors(x1):
  3745. # Verify that an exception raised in a gufunc loop propagates correctly.
  3746. # The signature of always_error_gufunc is '(i),()->()'.
  3747. with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
  3748. ncu_tests.always_error_gufunc(x1, 0.0)