test_ufunc.py 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798
  1. import warnings
  2. import itertools
  3. import sys
  4. import ctypes as ct
  5. import pytest
  6. from pytest import param
  7. import numpy as np
  8. import numpy.core._umath_tests as umt
  9. import numpy.linalg._umath_linalg as uml
  10. import numpy.core._operand_flag_tests as opflag_tests
  11. import numpy.core._rational_tests as _rational_tests
  12. from numpy.testing import (
  13. assert_, assert_equal, assert_raises, assert_array_equal,
  14. assert_almost_equal, assert_array_almost_equal, assert_no_warnings,
  15. assert_allclose, HAS_REFCOUNT, suppress_warnings, IS_WASM
  16. )
  17. from numpy.testing._private.utils import requires_memory
  18. from numpy.compat import pickle
  19. UNARY_UFUNCS = [obj for obj in np.core.umath.__dict__.values()
  20. if isinstance(obj, np.ufunc)]
  21. UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types]
  22. class TestUfuncKwargs:
  23. def test_kwarg_exact(self):
  24. assert_raises(TypeError, np.add, 1, 2, castingx='safe')
  25. assert_raises(TypeError, np.add, 1, 2, dtypex=int)
  26. assert_raises(TypeError, np.add, 1, 2, extobjx=[4096])
  27. assert_raises(TypeError, np.add, 1, 2, outx=None)
  28. assert_raises(TypeError, np.add, 1, 2, sigx='ii->i')
  29. assert_raises(TypeError, np.add, 1, 2, signaturex='ii->i')
  30. assert_raises(TypeError, np.add, 1, 2, subokx=False)
  31. assert_raises(TypeError, np.add, 1, 2, wherex=[True])
  32. def test_sig_signature(self):
  33. assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
  34. signature='ii->i')
  35. def test_sig_dtype(self):
  36. assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
  37. dtype=int)
  38. assert_raises(TypeError, np.add, 1, 2, signature='ii->i',
  39. dtype=int)
  40. def test_extobj_refcount(self):
  41. # Should not segfault with USE_DEBUG.
  42. assert_raises(TypeError, np.add, 1, 2, extobj=[4096], parrot=True)
  43. class TestUfuncGenericLoops:
  44. """Test generic loops.
  45. The loops to be tested are:
  46. PyUFunc_ff_f_As_dd_d
  47. PyUFunc_ff_f
  48. PyUFunc_dd_d
  49. PyUFunc_gg_g
  50. PyUFunc_FF_F_As_DD_D
  51. PyUFunc_DD_D
  52. PyUFunc_FF_F
  53. PyUFunc_GG_G
  54. PyUFunc_OO_O
  55. PyUFunc_OO_O_method
  56. PyUFunc_f_f_As_d_d
  57. PyUFunc_d_d
  58. PyUFunc_f_f
  59. PyUFunc_g_g
  60. PyUFunc_F_F_As_D_D
  61. PyUFunc_F_F
  62. PyUFunc_D_D
  63. PyUFunc_G_G
  64. PyUFunc_O_O
  65. PyUFunc_O_O_method
  66. PyUFunc_On_Om
  67. Where:
  68. f -- float
  69. d -- double
  70. g -- long double
  71. F -- complex float
  72. D -- complex double
  73. G -- complex long double
  74. O -- python object
  75. It is difficult to assure that each of these loops is entered from the
  76. Python level as the special cased loops are a moving target and the
  77. corresponding types are architecture dependent. We probably need to
  78. define C level testing ufuncs to get at them. For the time being, I've
  79. just looked at the signatures registered in the build directory to find
  80. relevant functions.
  81. """
  82. np_dtypes = [
  83. (np.single, np.single), (np.single, np.double),
  84. (np.csingle, np.csingle), (np.csingle, np.cdouble),
  85. (np.double, np.double), (np.longdouble, np.longdouble),
  86. (np.cdouble, np.cdouble), (np.clongdouble, np.clongdouble)]
  87. @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
  88. def test_unary_PyUFunc(self, input_dtype, output_dtype, f=np.exp, x=0, y=1):
  89. xs = np.full(10, input_dtype(x), dtype=output_dtype)
  90. ys = f(xs)[::2]
  91. assert_allclose(ys, y)
  92. assert_equal(ys.dtype, output_dtype)
  93. def f2(x, y):
  94. return x**y
  95. @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
  96. def test_binary_PyUFunc(self, input_dtype, output_dtype, f=f2, x=0, y=1):
  97. xs = np.full(10, input_dtype(x), dtype=output_dtype)
  98. ys = f(xs, xs)[::2]
  99. assert_allclose(ys, y)
  100. assert_equal(ys.dtype, output_dtype)
  101. # class to use in testing object method loops
  102. class foo:
  103. def conjugate(self):
  104. return np.bool_(1)
  105. def logical_xor(self, obj):
  106. return np.bool_(1)
  107. def test_unary_PyUFunc_O_O(self):
  108. x = np.ones(10, dtype=object)
  109. assert_(np.all(np.abs(x) == 1))
  110. def test_unary_PyUFunc_O_O_method_simple(self, foo=foo):
  111. x = np.full(10, foo(), dtype=object)
  112. assert_(np.all(np.conjugate(x) == True))
  113. def test_binary_PyUFunc_OO_O(self):
  114. x = np.ones(10, dtype=object)
  115. assert_(np.all(np.add(x, x) == 2))
  116. def test_binary_PyUFunc_OO_O_method(self, foo=foo):
  117. x = np.full(10, foo(), dtype=object)
  118. assert_(np.all(np.logical_xor(x, x)))
  119. def test_binary_PyUFunc_On_Om_method(self, foo=foo):
  120. x = np.full((10, 2, 3), foo(), dtype=object)
  121. assert_(np.all(np.logical_xor(x, x)))
  122. def test_python_complex_conjugate(self):
  123. # The conjugate ufunc should fall back to calling the method:
  124. arr = np.array([1+2j, 3-4j], dtype="O")
  125. assert isinstance(arr[0], complex)
  126. res = np.conjugate(arr)
  127. assert res.dtype == np.dtype("O")
  128. assert_array_equal(res, np.array([1-2j, 3+4j], dtype="O"))
  129. @pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS)
  130. def test_unary_PyUFunc_O_O_method_full(self, ufunc):
  131. """Compare the result of the object loop with non-object one"""
  132. val = np.float64(np.pi/4)
  133. class MyFloat(np.float64):
  134. def __getattr__(self, attr):
  135. try:
  136. return super().__getattr__(attr)
  137. except AttributeError:
  138. return lambda: getattr(np.core.umath, attr)(val)
  139. # Use 0-D arrays, to ensure the same element call
  140. num_arr = np.array(val, dtype=np.float64)
  141. obj_arr = np.array(MyFloat(val), dtype="O")
  142. with np.errstate(all="raise"):
  143. try:
  144. res_num = ufunc(num_arr)
  145. except Exception as exc:
  146. with assert_raises(type(exc)):
  147. ufunc(obj_arr)
  148. else:
  149. res_obj = ufunc(obj_arr)
  150. assert_array_almost_equal(res_num.astype("O"), res_obj)
  151. def _pickleable_module_global():
  152. pass
  153. class TestUfunc:
  154. def test_pickle(self):
  155. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  156. assert_(pickle.loads(pickle.dumps(np.sin,
  157. protocol=proto)) is np.sin)
  158. # Check that ufunc not defined in the top level numpy namespace
  159. # such as numpy.core._rational_tests.test_add can also be pickled
  160. res = pickle.loads(pickle.dumps(_rational_tests.test_add,
  161. protocol=proto))
  162. assert_(res is _rational_tests.test_add)
  163. def test_pickle_withstring(self):
  164. astring = (b"cnumpy.core\n_ufunc_reconstruct\np0\n"
  165. b"(S'numpy.core.umath'\np1\nS'cos'\np2\ntp3\nRp4\n.")
  166. assert_(pickle.loads(astring) is np.cos)
  167. def test_pickle_name_is_qualname(self):
  168. # This tests that a simplification of our ufunc pickle code will
  169. # lead to allowing qualnames as names. Future ufuncs should
  170. # possible add a specific qualname, or a hook into pickling instead
  171. # (dask+numba may benefit).
  172. _pickleable_module_global.ufunc = umt._pickleable_module_global_ufunc
  173. obj = pickle.loads(pickle.dumps(_pickleable_module_global.ufunc))
  174. assert obj is umt._pickleable_module_global_ufunc
  175. def test_reduceat_shifting_sum(self):
  176. L = 6
  177. x = np.arange(L)
  178. idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel()
  179. assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7])
  180. def test_all_ufunc(self):
  181. """Try to check presence and results of all ufuncs.
  182. The list of ufuncs comes from generate_umath.py and is as follows:
  183. ===== ==== ============= =============== ========================
  184. done args function types notes
  185. ===== ==== ============= =============== ========================
  186. n 1 conjugate nums + O
  187. n 1 absolute nums + O complex -> real
  188. n 1 negative nums + O
  189. n 1 sign nums + O -> int
  190. n 1 invert bool + ints + O flts raise an error
  191. n 1 degrees real + M cmplx raise an error
  192. n 1 radians real + M cmplx raise an error
  193. n 1 arccos flts + M
  194. n 1 arccosh flts + M
  195. n 1 arcsin flts + M
  196. n 1 arcsinh flts + M
  197. n 1 arctan flts + M
  198. n 1 arctanh flts + M
  199. n 1 cos flts + M
  200. n 1 sin flts + M
  201. n 1 tan flts + M
  202. n 1 cosh flts + M
  203. n 1 sinh flts + M
  204. n 1 tanh flts + M
  205. n 1 exp flts + M
  206. n 1 expm1 flts + M
  207. n 1 log flts + M
  208. n 1 log10 flts + M
  209. n 1 log1p flts + M
  210. n 1 sqrt flts + M real x < 0 raises error
  211. n 1 ceil real + M
  212. n 1 trunc real + M
  213. n 1 floor real + M
  214. n 1 fabs real + M
  215. n 1 rint flts + M
  216. n 1 isnan flts -> bool
  217. n 1 isinf flts -> bool
  218. n 1 isfinite flts -> bool
  219. n 1 signbit real -> bool
  220. n 1 modf real -> (frac, int)
  221. n 1 logical_not bool + nums + M -> bool
  222. n 2 left_shift ints + O flts raise an error
  223. n 2 right_shift ints + O flts raise an error
  224. n 2 add bool + nums + O boolean + is ||
  225. n 2 subtract bool + nums + O boolean - is ^
  226. n 2 multiply bool + nums + O boolean * is &
  227. n 2 divide nums + O
  228. n 2 floor_divide nums + O
  229. n 2 true_divide nums + O bBhH -> f, iIlLqQ -> d
  230. n 2 fmod nums + M
  231. n 2 power nums + O
  232. n 2 greater bool + nums + O -> bool
  233. n 2 greater_equal bool + nums + O -> bool
  234. n 2 less bool + nums + O -> bool
  235. n 2 less_equal bool + nums + O -> bool
  236. n 2 equal bool + nums + O -> bool
  237. n 2 not_equal bool + nums + O -> bool
  238. n 2 logical_and bool + nums + M -> bool
  239. n 2 logical_or bool + nums + M -> bool
  240. n 2 logical_xor bool + nums + M -> bool
  241. n 2 maximum bool + nums + O
  242. n 2 minimum bool + nums + O
  243. n 2 bitwise_and bool + ints + O flts raise an error
  244. n 2 bitwise_or bool + ints + O flts raise an error
  245. n 2 bitwise_xor bool + ints + O flts raise an error
  246. n 2 arctan2 real + M
  247. n 2 remainder ints + real + O
  248. n 2 hypot real + M
  249. ===== ==== ============= =============== ========================
  250. Types other than those listed will be accepted, but they are cast to
  251. the smallest compatible type for which the function is defined. The
  252. casting rules are:
  253. bool -> int8 -> float32
  254. ints -> double
  255. """
  256. pass
  257. # from include/numpy/ufuncobject.h
  258. size_inferred = 2
  259. can_ignore = 4
  260. def test_signature0(self):
  261. # the arguments to test_signature are: nin, nout, core_signature
  262. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  263. 2, 1, "(i),(i)->()")
  264. assert_equal(enabled, 1)
  265. assert_equal(num_dims, (1, 1, 0))
  266. assert_equal(ixs, (0, 0))
  267. assert_equal(flags, (self.size_inferred,))
  268. assert_equal(sizes, (-1,))
  269. def test_signature1(self):
  270. # empty core signature; treat as plain ufunc (with trivial core)
  271. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  272. 2, 1, "(),()->()")
  273. assert_equal(enabled, 0)
  274. assert_equal(num_dims, (0, 0, 0))
  275. assert_equal(ixs, ())
  276. assert_equal(flags, ())
  277. assert_equal(sizes, ())
  278. def test_signature2(self):
  279. # more complicated names for variables
  280. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  281. 2, 1, "(i1,i2),(J_1)->(_kAB)")
  282. assert_equal(enabled, 1)
  283. assert_equal(num_dims, (2, 1, 1))
  284. assert_equal(ixs, (0, 1, 2, 3))
  285. assert_equal(flags, (self.size_inferred,)*4)
  286. assert_equal(sizes, (-1, -1, -1, -1))
  287. def test_signature3(self):
  288. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  289. 2, 1, "(i1, i12), (J_1)->(i12, i2)")
  290. assert_equal(enabled, 1)
  291. assert_equal(num_dims, (2, 1, 2))
  292. assert_equal(ixs, (0, 1, 2, 1, 3))
  293. assert_equal(flags, (self.size_inferred,)*4)
  294. assert_equal(sizes, (-1, -1, -1, -1))
  295. def test_signature4(self):
  296. # matrix_multiply signature from _umath_tests
  297. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  298. 2, 1, "(n,k),(k,m)->(n,m)")
  299. assert_equal(enabled, 1)
  300. assert_equal(num_dims, (2, 2, 2))
  301. assert_equal(ixs, (0, 1, 1, 2, 0, 2))
  302. assert_equal(flags, (self.size_inferred,)*3)
  303. assert_equal(sizes, (-1, -1, -1))
  304. def test_signature5(self):
  305. # matmul signature from _umath_tests
  306. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  307. 2, 1, "(n?,k),(k,m?)->(n?,m?)")
  308. assert_equal(enabled, 1)
  309. assert_equal(num_dims, (2, 2, 2))
  310. assert_equal(ixs, (0, 1, 1, 2, 0, 2))
  311. assert_equal(flags, (self.size_inferred | self.can_ignore,
  312. self.size_inferred,
  313. self.size_inferred | self.can_ignore))
  314. assert_equal(sizes, (-1, -1, -1))
  315. def test_signature6(self):
  316. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  317. 1, 1, "(3)->()")
  318. assert_equal(enabled, 1)
  319. assert_equal(num_dims, (1, 0))
  320. assert_equal(ixs, (0,))
  321. assert_equal(flags, (0,))
  322. assert_equal(sizes, (3,))
  323. def test_signature7(self):
  324. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  325. 3, 1, "(3),(03,3),(n)->(9)")
  326. assert_equal(enabled, 1)
  327. assert_equal(num_dims, (1, 2, 1, 1))
  328. assert_equal(ixs, (0, 0, 0, 1, 2))
  329. assert_equal(flags, (0, self.size_inferred, 0))
  330. assert_equal(sizes, (3, -1, 9))
  331. def test_signature8(self):
  332. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  333. 3, 1, "(3?),(3?,3?),(n)->(9)")
  334. assert_equal(enabled, 1)
  335. assert_equal(num_dims, (1, 2, 1, 1))
  336. assert_equal(ixs, (0, 0, 0, 1, 2))
  337. assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
  338. assert_equal(sizes, (3, -1, 9))
  339. def test_signature9(self):
  340. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  341. 1, 1, "( 3) -> ( )")
  342. assert_equal(enabled, 1)
  343. assert_equal(num_dims, (1, 0))
  344. assert_equal(ixs, (0,))
  345. assert_equal(flags, (0,))
  346. assert_equal(sizes, (3,))
  347. def test_signature10(self):
  348. enabled, num_dims, ixs, flags, sizes = umt.test_signature(
  349. 3, 1, "( 3? ) , (3? , 3?) ,(n )-> ( 9)")
  350. assert_equal(enabled, 1)
  351. assert_equal(num_dims, (1, 2, 1, 1))
  352. assert_equal(ixs, (0, 0, 0, 1, 2))
  353. assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
  354. assert_equal(sizes, (3, -1, 9))
  355. def test_signature_failure_extra_parenthesis(self):
  356. with assert_raises(ValueError):
  357. umt.test_signature(2, 1, "((i)),(i)->()")
  358. def test_signature_failure_mismatching_parenthesis(self):
  359. with assert_raises(ValueError):
  360. umt.test_signature(2, 1, "(i),)i(->()")
  361. def test_signature_failure_signature_missing_input_arg(self):
  362. with assert_raises(ValueError):
  363. umt.test_signature(2, 1, "(i),->()")
  364. def test_signature_failure_signature_missing_output_arg(self):
  365. with assert_raises(ValueError):
  366. umt.test_signature(2, 2, "(i),(i)->()")
  367. def test_get_signature(self):
  368. assert_equal(umt.inner1d.signature, "(i),(i)->()")
  369. def test_forced_sig(self):
  370. a = 0.5*np.arange(3, dtype='f8')
  371. assert_equal(np.add(a, 0.5), [0.5, 1, 1.5])
  372. with pytest.warns(DeprecationWarning):
  373. assert_equal(np.add(a, 0.5, sig='i', casting='unsafe'), [0, 0, 1])
  374. assert_equal(np.add(a, 0.5, sig='ii->i', casting='unsafe'), [0, 0, 1])
  375. with pytest.warns(DeprecationWarning):
  376. assert_equal(np.add(a, 0.5, sig=('i4',), casting='unsafe'),
  377. [0, 0, 1])
  378. assert_equal(np.add(a, 0.5, sig=('i4', 'i4', 'i4'),
  379. casting='unsafe'), [0, 0, 1])
  380. b = np.zeros((3,), dtype='f8')
  381. np.add(a, 0.5, out=b)
  382. assert_equal(b, [0.5, 1, 1.5])
  383. b[:] = 0
  384. with pytest.warns(DeprecationWarning):
  385. np.add(a, 0.5, sig='i', out=b, casting='unsafe')
  386. assert_equal(b, [0, 0, 1])
  387. b[:] = 0
  388. np.add(a, 0.5, sig='ii->i', out=b, casting='unsafe')
  389. assert_equal(b, [0, 0, 1])
  390. b[:] = 0
  391. with pytest.warns(DeprecationWarning):
  392. np.add(a, 0.5, sig=('i4',), out=b, casting='unsafe')
  393. assert_equal(b, [0, 0, 1])
  394. b[:] = 0
  395. np.add(a, 0.5, sig=('i4', 'i4', 'i4'), out=b, casting='unsafe')
  396. assert_equal(b, [0, 0, 1])
  397. def test_signature_all_None(self):
  398. # signature all None, is an acceptable alternative (since 1.21)
  399. # to not providing a signature.
  400. res1 = np.add([3], [4], sig=(None, None, None))
  401. res2 = np.add([3], [4])
  402. assert_array_equal(res1, res2)
  403. res1 = np.maximum([3], [4], sig=(None, None, None))
  404. res2 = np.maximum([3], [4])
  405. assert_array_equal(res1, res2)
  406. with pytest.raises(TypeError):
  407. # special case, that would be deprecated anyway, so errors:
  408. np.add(3, 4, signature=(None,))
  409. def test_signature_dtype_type(self):
  410. # Since that will be the normal behaviour (past NumPy 1.21)
  411. # we do support the types already:
  412. float_dtype = type(np.dtype(np.float64))
  413. np.add(3, 4, signature=(float_dtype, float_dtype, None))
  414. @pytest.mark.parametrize("get_kwarg", [
  415. lambda dt: dict(dtype=x),
  416. lambda dt: dict(signature=(x, None, None))])
  417. def test_signature_dtype_instances_allowed(self, get_kwarg):
  418. # We allow certain dtype instances when there is a clear singleton
  419. # and the given one is equivalent; mainly for backcompat.
  420. int64 = np.dtype("int64")
  421. int64_2 = pickle.loads(pickle.dumps(int64))
  422. # Relies on pickling behavior, if assert fails just remove test...
  423. assert int64 is not int64_2
  424. assert np.add(1, 2, **get_kwarg(int64_2)).dtype == int64
  425. td = np.timedelta(2, "s")
  426. assert np.add(td, td, **get_kwarg("m8")).dtype == "m8[s]"
  427. @pytest.mark.parametrize("get_kwarg", [
  428. param(lambda x: dict(dtype=x), id="dtype"),
  429. param(lambda x: dict(signature=(x, None, None)), id="signature")])
  430. def test_signature_dtype_instances_allowed(self, get_kwarg):
  431. msg = "The `dtype` and `signature` arguments to ufuncs"
  432. with pytest.raises(TypeError, match=msg):
  433. np.add(3, 5, **get_kwarg(np.dtype("int64").newbyteorder()))
  434. with pytest.raises(TypeError, match=msg):
  435. np.add(3, 5, **get_kwarg(np.dtype("m8[ns]")))
  436. with pytest.raises(TypeError, match=msg):
  437. np.add(3, 5, **get_kwarg("m8[ns]"))
  438. @pytest.mark.parametrize("casting", ["unsafe", "same_kind", "safe"])
  439. def test_partial_signature_mismatch(self, casting):
  440. # If the second argument matches already, no need to specify it:
  441. res = np.ldexp(np.float32(1.), np.int_(2), dtype="d")
  442. assert res.dtype == "d"
  443. res = np.ldexp(np.float32(1.), np.int_(2), signature=(None, None, "d"))
  444. assert res.dtype == "d"
  445. # ldexp only has a loop for long input as second argument, overriding
  446. # the output cannot help with that (no matter the casting)
  447. with pytest.raises(TypeError):
  448. np.ldexp(1., np.uint64(3), dtype="d")
  449. with pytest.raises(TypeError):
  450. np.ldexp(1., np.uint64(3), signature=(None, None, "d"))
  451. def test_partial_signature_mismatch_with_cache(self):
  452. with pytest.raises(TypeError):
  453. np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
  454. # Ensure e,d->None is in the dispatching cache (double loop)
  455. np.add(np.float16(1), np.float64(2))
  456. # The error must still be raised:
  457. with pytest.raises(TypeError):
  458. np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
  459. def test_use_output_signature_for_all_arguments(self):
  460. # Test that providing only `dtype=` or `signature=(None, None, dtype)`
  461. # is sufficient if falling back to a homogeneous signature works.
  462. # In this case, the `intp, intp -> intp` loop is chosen.
  463. res = np.power(1.5, 2.8, dtype=np.intp, casting="unsafe")
  464. assert res == 1 # the cast happens first.
  465. res = np.power(1.5, 2.8, signature=(None, None, np.intp),
  466. casting="unsafe")
  467. assert res == 1
  468. with pytest.raises(TypeError):
  469. # the unsafe casting would normally cause errors though:
  470. np.power(1.5, 2.8, dtype=np.intp)
  471. def test_signature_errors(self):
  472. with pytest.raises(TypeError,
  473. match="the signature object to ufunc must be a string or"):
  474. np.add(3, 4, signature=123.) # neither a string nor a tuple
  475. with pytest.raises(ValueError):
  476. # bad symbols that do not translate to dtypes
  477. np.add(3, 4, signature="%^->#")
  478. with pytest.raises(ValueError):
  479. np.add(3, 4, signature=b"ii-i") # incomplete and byte string
  480. with pytest.raises(ValueError):
  481. np.add(3, 4, signature="ii>i") # incomplete string
  482. with pytest.raises(ValueError):
  483. np.add(3, 4, signature=(None, "f8")) # bad length
  484. with pytest.raises(UnicodeDecodeError):
  485. np.add(3, 4, signature=b"\xff\xff->i")
  486. def test_forced_dtype_times(self):
  487. # Signatures only set the type numbers (not the actual loop dtypes)
  488. # so using `M` in a signature/dtype should generally work:
  489. a = np.array(['2010-01-02', '1999-03-14', '1833-03'], dtype='>M8[D]')
  490. np.maximum(a, a, dtype="M")
  491. np.maximum.reduce(a, dtype="M")
  492. arr = np.arange(10, dtype="m8[s]")
  493. np.add(arr, arr, dtype="m")
  494. np.maximum(arr, arr, dtype="m")
  495. @pytest.mark.parametrize("ufunc", [np.add, np.sqrt])
  496. def test_cast_safety(self, ufunc):
  497. """Basic test for the safest casts, because ufuncs inner loops can
  498. indicate a cast-safety as well (which is normally always "no").
  499. """
  500. def call_ufunc(arr, **kwargs):
  501. return ufunc(*(arr,) * ufunc.nin, **kwargs)
  502. arr = np.array([1., 2., 3.], dtype=np.float32)
  503. arr_bs = arr.astype(arr.dtype.newbyteorder())
  504. expected = call_ufunc(arr)
  505. # Normally, a "no" cast:
  506. res = call_ufunc(arr, casting="no")
  507. assert_array_equal(expected, res)
  508. # Byte-swapping is not allowed with "no" though:
  509. with pytest.raises(TypeError):
  510. call_ufunc(arr_bs, casting="no")
  511. # But is allowed with "equiv":
  512. res = call_ufunc(arr_bs, casting="equiv")
  513. assert_array_equal(expected, res)
  514. # Casting to float64 is safe, but not equiv:
  515. with pytest.raises(TypeError):
  516. call_ufunc(arr_bs, dtype=np.float64, casting="equiv")
  517. # but it is safe cast:
  518. res = call_ufunc(arr_bs, dtype=np.float64, casting="safe")
  519. expected = call_ufunc(arr.astype(np.float64)) # upcast
  520. assert_array_equal(expected, res)
  521. def test_true_divide(self):
  522. a = np.array(10)
  523. b = np.array(20)
  524. tgt = np.array(0.5)
  525. for tc in 'bhilqBHILQefdgFDG':
  526. dt = np.dtype(tc)
  527. aa = a.astype(dt)
  528. bb = b.astype(dt)
  529. # Check result value and dtype.
  530. for x, y in itertools.product([aa, -aa], [bb, -bb]):
  531. # Check with no output type specified
  532. if tc in 'FDG':
  533. tgt = complex(x)/complex(y)
  534. else:
  535. tgt = float(x)/float(y)
  536. res = np.true_divide(x, y)
  537. rtol = max(np.finfo(res).resolution, 1e-15)
  538. assert_allclose(res, tgt, rtol=rtol)
  539. if tc in 'bhilqBHILQ':
  540. assert_(res.dtype.name == 'float64')
  541. else:
  542. assert_(res.dtype.name == dt.name )
  543. # Check with output type specified. This also checks for the
  544. # incorrect casts in issue gh-3484 because the unary '-' does
  545. # not change types, even for unsigned types, Hence casts in the
  546. # ufunc from signed to unsigned and vice versa will lead to
  547. # errors in the values.
  548. for tcout in 'bhilqBHILQ':
  549. dtout = np.dtype(tcout)
  550. assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
  551. for tcout in 'efdg':
  552. dtout = np.dtype(tcout)
  553. if tc in 'FDG':
  554. # Casting complex to float is not allowed
  555. assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
  556. else:
  557. tgt = float(x)/float(y)
  558. rtol = max(np.finfo(dtout).resolution, 1e-15)
  559. # The value of tiny for double double is NaN
  560. with suppress_warnings() as sup:
  561. sup.filter(UserWarning)
  562. if not np.isnan(np.finfo(dtout).tiny):
  563. atol = max(np.finfo(dtout).tiny, 3e-308)
  564. else:
  565. atol = 3e-308
  566. # Some test values result in invalid for float16
  567. # and the cast to it may overflow to inf.
  568. with np.errstate(invalid='ignore', over='ignore'):
  569. res = np.true_divide(x, y, dtype=dtout)
  570. if not np.isfinite(res) and tcout == 'e':
  571. continue
  572. assert_allclose(res, tgt, rtol=rtol, atol=atol)
  573. assert_(res.dtype.name == dtout.name)
  574. for tcout in 'FDG':
  575. dtout = np.dtype(tcout)
  576. tgt = complex(x)/complex(y)
  577. rtol = max(np.finfo(dtout).resolution, 1e-15)
  578. # The value of tiny for double double is NaN
  579. with suppress_warnings() as sup:
  580. sup.filter(UserWarning)
  581. if not np.isnan(np.finfo(dtout).tiny):
  582. atol = max(np.finfo(dtout).tiny, 3e-308)
  583. else:
  584. atol = 3e-308
  585. res = np.true_divide(x, y, dtype=dtout)
  586. if not np.isfinite(res):
  587. continue
  588. assert_allclose(res, tgt, rtol=rtol, atol=atol)
  589. assert_(res.dtype.name == dtout.name)
  590. # Check booleans
  591. a = np.ones((), dtype=np.bool_)
  592. res = np.true_divide(a, a)
  593. assert_(res == 1.0)
  594. assert_(res.dtype.name == 'float64')
  595. res = np.true_divide(~a, a)
  596. assert_(res == 0.0)
  597. assert_(res.dtype.name == 'float64')
  598. def test_sum_stability(self):
  599. a = np.ones(500, dtype=np.float32)
  600. assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 4)
  601. a = np.ones(500, dtype=np.float64)
  602. assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 13)
  603. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  604. def test_sum(self):
  605. for dt in (int, np.float16, np.float32, np.float64, np.longdouble):
  606. for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
  607. 128, 1024, 1235):
  608. # warning if sum overflows, which it does in float16
  609. with warnings.catch_warnings(record=True) as w:
  610. warnings.simplefilter("always", RuntimeWarning)
  611. tgt = dt(v * (v + 1) / 2)
  612. overflow = not np.isfinite(tgt)
  613. assert_equal(len(w), 1 * overflow)
  614. d = np.arange(1, v + 1, dtype=dt)
  615. assert_almost_equal(np.sum(d), tgt)
  616. assert_equal(len(w), 2 * overflow)
  617. assert_almost_equal(np.sum(d[::-1]), tgt)
  618. assert_equal(len(w), 3 * overflow)
  619. d = np.ones(500, dtype=dt)
  620. assert_almost_equal(np.sum(d[::2]), 250.)
  621. assert_almost_equal(np.sum(d[1::2]), 250.)
  622. assert_almost_equal(np.sum(d[::3]), 167.)
  623. assert_almost_equal(np.sum(d[1::3]), 167.)
  624. assert_almost_equal(np.sum(d[::-2]), 250.)
  625. assert_almost_equal(np.sum(d[-1::-2]), 250.)
  626. assert_almost_equal(np.sum(d[::-3]), 167.)
  627. assert_almost_equal(np.sum(d[-1::-3]), 167.)
  628. # sum with first reduction entry != 0
  629. d = np.ones((1,), dtype=dt)
  630. d += d
  631. assert_almost_equal(d, 2.)
  632. def test_sum_complex(self):
  633. for dt in (np.complex64, np.complex128, np.clongdouble):
  634. for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
  635. 128, 1024, 1235):
  636. tgt = dt(v * (v + 1) / 2) - dt((v * (v + 1) / 2) * 1j)
  637. d = np.empty(v, dtype=dt)
  638. d.real = np.arange(1, v + 1)
  639. d.imag = -np.arange(1, v + 1)
  640. assert_almost_equal(np.sum(d), tgt)
  641. assert_almost_equal(np.sum(d[::-1]), tgt)
  642. d = np.ones(500, dtype=dt) + 1j
  643. assert_almost_equal(np.sum(d[::2]), 250. + 250j)
  644. assert_almost_equal(np.sum(d[1::2]), 250. + 250j)
  645. assert_almost_equal(np.sum(d[::3]), 167. + 167j)
  646. assert_almost_equal(np.sum(d[1::3]), 167. + 167j)
  647. assert_almost_equal(np.sum(d[::-2]), 250. + 250j)
  648. assert_almost_equal(np.sum(d[-1::-2]), 250. + 250j)
  649. assert_almost_equal(np.sum(d[::-3]), 167. + 167j)
  650. assert_almost_equal(np.sum(d[-1::-3]), 167. + 167j)
  651. # sum with first reduction entry != 0
  652. d = np.ones((1,), dtype=dt) + 1j
  653. d += d
  654. assert_almost_equal(d, 2. + 2j)
  655. def test_sum_initial(self):
  656. # Integer, single axis
  657. assert_equal(np.sum([3], initial=2), 5)
  658. # Floating point
  659. assert_almost_equal(np.sum([0.2], initial=0.1), 0.3)
  660. # Multiple non-adjacent axes
  661. assert_equal(np.sum(np.ones((2, 3, 5), dtype=np.int64), axis=(0, 2), initial=2),
  662. [12, 12, 12])
  663. def test_sum_where(self):
  664. # More extensive tests done in test_reduction_with_where.
  665. assert_equal(np.sum([[1., 2.], [3., 4.]], where=[True, False]), 4.)
  666. assert_equal(np.sum([[1., 2.], [3., 4.]], axis=0, initial=5.,
  667. where=[True, False]), [9., 5.])
  668. def test_inner1d(self):
  669. a = np.arange(6).reshape((2, 3))
  670. assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1))
  671. a = np.arange(6)
  672. assert_array_equal(umt.inner1d(a, a), np.sum(a*a))
  673. def test_broadcast(self):
  674. msg = "broadcast"
  675. a = np.arange(4).reshape((2, 1, 2))
  676. b = np.arange(4).reshape((1, 2, 2))
  677. assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg)
  678. msg = "extend & broadcast loop dimensions"
  679. b = np.arange(4).reshape((2, 2))
  680. assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg)
  681. # Broadcast in core dimensions should fail
  682. a = np.arange(8).reshape((4, 2))
  683. b = np.arange(4).reshape((4, 1))
  684. assert_raises(ValueError, umt.inner1d, a, b)
  685. # Extend core dimensions should fail
  686. a = np.arange(8).reshape((4, 2))
  687. b = np.array(7)
  688. assert_raises(ValueError, umt.inner1d, a, b)
  689. # Broadcast should fail
  690. a = np.arange(2).reshape((2, 1, 1))
  691. b = np.arange(3).reshape((3, 1, 1))
  692. assert_raises(ValueError, umt.inner1d, a, b)
  693. # Writing to a broadcasted array with overlap should warn, gh-2705
  694. a = np.arange(2)
  695. b = np.arange(4).reshape((2, 2))
  696. u, v = np.broadcast_arrays(a, b)
  697. assert_equal(u.strides[0], 0)
  698. x = u + v
  699. with warnings.catch_warnings(record=True) as w:
  700. warnings.simplefilter("always")
  701. u += v
  702. assert_equal(len(w), 1)
  703. assert_(x[0, 0] != u[0, 0])
  704. # Output reduction should not be allowed.
  705. # See gh-15139
  706. a = np.arange(6).reshape(3, 2)
  707. b = np.ones(2)
  708. out = np.empty(())
  709. assert_raises(ValueError, umt.inner1d, a, b, out)
  710. out2 = np.empty(3)
  711. c = umt.inner1d(a, b, out2)
  712. assert_(c is out2)
  713. def test_out_broadcasts(self):
  714. # For ufuncs and gufuncs (not for reductions), we currently allow
  715. # the output to cause broadcasting of the input arrays.
  716. # both along dimensions with shape 1 and dimensions which do not
  717. # exist at all in the inputs.
  718. arr = np.arange(3).reshape(1, 3)
  719. out = np.empty((5, 4, 3))
  720. np.add(arr, arr, out=out)
  721. assert (out == np.arange(3) * 2).all()
  722. # The same holds for gufuncs (gh-16484)
  723. umt.inner1d(arr, arr, out=out)
  724. # the result would be just a scalar `5`, but is broadcast fully:
  725. assert (out == 5).all()
  726. @pytest.mark.parametrize(["arr", "out"], [
  727. ([2], np.empty(())),
  728. ([1, 2], np.empty(1)),
  729. (np.ones((4, 3)), np.empty((4, 1)))],
  730. ids=["(1,)->()", "(2,)->(1,)", "(4, 3)->(4, 1)"])
  731. def test_out_broadcast_errors(self, arr, out):
  732. # Output is (currently) allowed to broadcast inputs, but it cannot be
  733. # smaller than the actual result.
  734. with pytest.raises(ValueError, match="non-broadcastable"):
  735. np.positive(arr, out=out)
  736. with pytest.raises(ValueError, match="non-broadcastable"):
  737. np.add(np.ones(()), arr, out=out)
  738. def test_type_cast(self):
  739. msg = "type cast"
  740. a = np.arange(6, dtype='short').reshape((2, 3))
  741. assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1),
  742. err_msg=msg)
  743. msg = "type cast on one argument"
  744. a = np.arange(6).reshape((2, 3))
  745. b = a + 0.1
  746. assert_array_almost_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1),
  747. err_msg=msg)
  748. def test_endian(self):
  749. msg = "big endian"
  750. a = np.arange(6, dtype='>i4').reshape((2, 3))
  751. assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1),
  752. err_msg=msg)
  753. msg = "little endian"
  754. a = np.arange(6, dtype='<i4').reshape((2, 3))
  755. assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1),
  756. err_msg=msg)
  757. # Output should always be native-endian
  758. Ba = np.arange(1, dtype='>f8')
  759. La = np.arange(1, dtype='<f8')
  760. assert_equal((Ba+Ba).dtype, np.dtype('f8'))
  761. assert_equal((Ba+La).dtype, np.dtype('f8'))
  762. assert_equal((La+Ba).dtype, np.dtype('f8'))
  763. assert_equal((La+La).dtype, np.dtype('f8'))
  764. assert_equal(np.absolute(La).dtype, np.dtype('f8'))
  765. assert_equal(np.absolute(Ba).dtype, np.dtype('f8'))
  766. assert_equal(np.negative(La).dtype, np.dtype('f8'))
  767. assert_equal(np.negative(Ba).dtype, np.dtype('f8'))
  768. def test_incontiguous_array(self):
  769. msg = "incontiguous memory layout of array"
  770. x = np.arange(64).reshape((2, 2, 2, 2, 2, 2))
  771. a = x[:, 0,:, 0,:, 0]
  772. b = x[:, 1,:, 1,:, 1]
  773. a[0, 0, 0] = -1
  774. msg2 = "make sure it references to the original array"
  775. assert_equal(x[0, 0, 0, 0, 0, 0], -1, err_msg=msg2)
  776. assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg)
  777. x = np.arange(24).reshape(2, 3, 4)
  778. a = x.T
  779. b = x.T
  780. a[0, 0, 0] = -1
  781. assert_equal(x[0, 0, 0], -1, err_msg=msg2)
  782. assert_array_equal(umt.inner1d(a, b), np.sum(a*b, axis=-1), err_msg=msg)
  783. def test_output_argument(self):
  784. msg = "output argument"
  785. a = np.arange(12).reshape((2, 3, 2))
  786. b = np.arange(4).reshape((2, 1, 2)) + 1
  787. c = np.zeros((2, 3), dtype='int')
  788. umt.inner1d(a, b, c)
  789. assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg)
  790. c[:] = -1
  791. umt.inner1d(a, b, out=c)
  792. assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg)
  793. msg = "output argument with type cast"
  794. c = np.zeros((2, 3), dtype='int16')
  795. umt.inner1d(a, b, c)
  796. assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg)
  797. c[:] = -1
  798. umt.inner1d(a, b, out=c)
  799. assert_array_equal(c, np.sum(a*b, axis=-1), err_msg=msg)
  800. msg = "output argument with incontiguous layout"
  801. c = np.zeros((2, 3, 4), dtype='int16')
  802. umt.inner1d(a, b, c[..., 0])
  803. assert_array_equal(c[..., 0], np.sum(a*b, axis=-1), err_msg=msg)
  804. c[:] = -1
  805. umt.inner1d(a, b, out=c[..., 0])
  806. assert_array_equal(c[..., 0], np.sum(a*b, axis=-1), err_msg=msg)
  807. def test_axes_argument(self):
  808. # inner1d signature: '(i),(i)->()'
  809. inner1d = umt.inner1d
  810. a = np.arange(27.).reshape((3, 3, 3))
  811. b = np.arange(10., 19.).reshape((3, 1, 3))
  812. # basic tests on inputs (outputs tested below with matrix_multiply).
  813. c = inner1d(a, b)
  814. assert_array_equal(c, (a * b).sum(-1))
  815. # default
  816. c = inner1d(a, b, axes=[(-1,), (-1,), ()])
  817. assert_array_equal(c, (a * b).sum(-1))
  818. # integers ok for single axis.
  819. c = inner1d(a, b, axes=[-1, -1, ()])
  820. assert_array_equal(c, (a * b).sum(-1))
  821. # mix fine
  822. c = inner1d(a, b, axes=[(-1,), -1, ()])
  823. assert_array_equal(c, (a * b).sum(-1))
  824. # can omit last axis.
  825. c = inner1d(a, b, axes=[-1, -1])
  826. assert_array_equal(c, (a * b).sum(-1))
  827. # can pass in other types of integer (with __index__ protocol)
  828. c = inner1d(a, b, axes=[np.int8(-1), np.array(-1, dtype=np.int32)])
  829. assert_array_equal(c, (a * b).sum(-1))
  830. # swap some axes
  831. c = inner1d(a, b, axes=[0, 0])
  832. assert_array_equal(c, (a * b).sum(0))
  833. c = inner1d(a, b, axes=[0, 2])
  834. assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
  835. # Check errors for improperly constructed axes arguments.
  836. # should have list.
  837. assert_raises(TypeError, inner1d, a, b, axes=-1)
  838. # needs enough elements
  839. assert_raises(ValueError, inner1d, a, b, axes=[-1])
  840. # should pass in indices.
  841. assert_raises(TypeError, inner1d, a, b, axes=[-1.0, -1.0])
  842. assert_raises(TypeError, inner1d, a, b, axes=[(-1.0,), -1])
  843. assert_raises(TypeError, inner1d, a, b, axes=[None, 1])
  844. # cannot pass an index unless there is only one dimension
  845. # (output is wrong in this case)
  846. assert_raises(TypeError, inner1d, a, b, axes=[-1, -1, -1])
  847. # or pass in generally the wrong number of axes
  848. assert_raises(ValueError, inner1d, a, b, axes=[-1, -1, (-1,)])
  849. assert_raises(ValueError, inner1d, a, b, axes=[-1, (-2, -1), ()])
  850. # axes need to have same length.
  851. assert_raises(ValueError, inner1d, a, b, axes=[0, 1])
  852. # matrix_multiply signature: '(m,n),(n,p)->(m,p)'
  853. mm = umt.matrix_multiply
  854. a = np.arange(12).reshape((2, 3, 2))
  855. b = np.arange(8).reshape((2, 2, 2, 1)) + 1
  856. # Sanity check.
  857. c = mm(a, b)
  858. assert_array_equal(c, np.matmul(a, b))
  859. # Default axes.
  860. c = mm(a, b, axes=[(-2, -1), (-2, -1), (-2, -1)])
  861. assert_array_equal(c, np.matmul(a, b))
  862. # Default with explicit axes.
  863. c = mm(a, b, axes=[(1, 2), (2, 3), (2, 3)])
  864. assert_array_equal(c, np.matmul(a, b))
  865. # swap some axes.
  866. c = mm(a, b, axes=[(0, -1), (1, 2), (-2, -1)])
  867. assert_array_equal(c, np.matmul(a.transpose(1, 0, 2),
  868. b.transpose(0, 3, 1, 2)))
  869. # Default with output array.
  870. c = np.empty((2, 2, 3, 1))
  871. d = mm(a, b, out=c, axes=[(1, 2), (2, 3), (2, 3)])
  872. assert_(c is d)
  873. assert_array_equal(c, np.matmul(a, b))
  874. # Transposed output array
  875. c = np.empty((1, 2, 2, 3))
  876. d = mm(a, b, out=c, axes=[(-2, -1), (-2, -1), (3, 0)])
  877. assert_(c is d)
  878. assert_array_equal(c, np.matmul(a, b).transpose(3, 0, 1, 2))
  879. # Check errors for improperly constructed axes arguments.
  880. # wrong argument
  881. assert_raises(TypeError, mm, a, b, axis=1)
  882. # axes should be list
  883. assert_raises(TypeError, mm, a, b, axes=1)
  884. assert_raises(TypeError, mm, a, b, axes=((-2, -1), (-2, -1), (-2, -1)))
  885. # list needs to have right length
  886. assert_raises(ValueError, mm, a, b, axes=[])
  887. assert_raises(ValueError, mm, a, b, axes=[(-2, -1)])
  888. # list should contain tuples for multiple axes
  889. assert_raises(TypeError, mm, a, b, axes=[-1, -1, -1])
  890. assert_raises(TypeError, mm, a, b, axes=[(-2, -1), (-2, -1), -1])
  891. assert_raises(TypeError,
  892. mm, a, b, axes=[[-2, -1], [-2, -1], [-2, -1]])
  893. assert_raises(TypeError,
  894. mm, a, b, axes=[(-2, -1), (-2, -1), [-2, -1]])
  895. assert_raises(TypeError, mm, a, b, axes=[(-2, -1), (-2, -1), None])
  896. # tuples should not have duplicated values
  897. assert_raises(ValueError, mm, a, b, axes=[(-2, -1), (-2, -1), (-2, -2)])
  898. # arrays should have enough axes.
  899. z = np.zeros((2, 2))
  900. assert_raises(ValueError, mm, z, z[0])
  901. assert_raises(ValueError, mm, z, z, out=z[:, 0])
  902. assert_raises(ValueError, mm, z[1], z, axes=[0, 1])
  903. assert_raises(ValueError, mm, z, z, out=z[0], axes=[0, 1])
  904. # Regular ufuncs should not accept axes.
  905. assert_raises(TypeError, np.add, 1., 1., axes=[0])
  906. # should be able to deal with bad unrelated kwargs.
  907. assert_raises(TypeError, mm, z, z, axes=[0, 1], parrot=True)
  908. def test_axis_argument(self):
  909. # inner1d signature: '(i),(i)->()'
  910. inner1d = umt.inner1d
  911. a = np.arange(27.).reshape((3, 3, 3))
  912. b = np.arange(10., 19.).reshape((3, 1, 3))
  913. c = inner1d(a, b)
  914. assert_array_equal(c, (a * b).sum(-1))
  915. c = inner1d(a, b, axis=-1)
  916. assert_array_equal(c, (a * b).sum(-1))
  917. out = np.zeros_like(c)
  918. d = inner1d(a, b, axis=-1, out=out)
  919. assert_(d is out)
  920. assert_array_equal(d, c)
  921. c = inner1d(a, b, axis=0)
  922. assert_array_equal(c, (a * b).sum(0))
  923. # Sanity checks on innerwt and cumsum.
  924. a = np.arange(6).reshape((2, 3))
  925. b = np.arange(10, 16).reshape((2, 3))
  926. w = np.arange(20, 26).reshape((2, 3))
  927. assert_array_equal(umt.innerwt(a, b, w, axis=0),
  928. np.sum(a * b * w, axis=0))
  929. assert_array_equal(umt.cumsum(a, axis=0), np.cumsum(a, axis=0))
  930. assert_array_equal(umt.cumsum(a, axis=-1), np.cumsum(a, axis=-1))
  931. out = np.empty_like(a)
  932. b = umt.cumsum(a, out=out, axis=0)
  933. assert_(out is b)
  934. assert_array_equal(b, np.cumsum(a, axis=0))
  935. b = umt.cumsum(a, out=out, axis=1)
  936. assert_(out is b)
  937. assert_array_equal(b, np.cumsum(a, axis=-1))
  938. # Check errors.
  939. # Cannot pass in both axis and axes.
  940. assert_raises(TypeError, inner1d, a, b, axis=0, axes=[0, 0])
  941. # Not an integer.
  942. assert_raises(TypeError, inner1d, a, b, axis=[0])
  943. # more than 1 core dimensions.
  944. mm = umt.matrix_multiply
  945. assert_raises(TypeError, mm, a, b, axis=1)
  946. # Output wrong size in axis.
  947. out = np.empty((1, 2, 3), dtype=a.dtype)
  948. assert_raises(ValueError, umt.cumsum, a, out=out, axis=0)
  949. # Regular ufuncs should not accept axis.
  950. assert_raises(TypeError, np.add, 1., 1., axis=0)
  951. def test_keepdims_argument(self):
  952. # inner1d signature: '(i),(i)->()'
  953. inner1d = umt.inner1d
  954. a = np.arange(27.).reshape((3, 3, 3))
  955. b = np.arange(10., 19.).reshape((3, 1, 3))
  956. c = inner1d(a, b)
  957. assert_array_equal(c, (a * b).sum(-1))
  958. c = inner1d(a, b, keepdims=False)
  959. assert_array_equal(c, (a * b).sum(-1))
  960. c = inner1d(a, b, keepdims=True)
  961. assert_array_equal(c, (a * b).sum(-1, keepdims=True))
  962. out = np.zeros_like(c)
  963. d = inner1d(a, b, keepdims=True, out=out)
  964. assert_(d is out)
  965. assert_array_equal(d, c)
  966. # Now combined with axis and axes.
  967. c = inner1d(a, b, axis=-1, keepdims=False)
  968. assert_array_equal(c, (a * b).sum(-1, keepdims=False))
  969. c = inner1d(a, b, axis=-1, keepdims=True)
  970. assert_array_equal(c, (a * b).sum(-1, keepdims=True))
  971. c = inner1d(a, b, axis=0, keepdims=False)
  972. assert_array_equal(c, (a * b).sum(0, keepdims=False))
  973. c = inner1d(a, b, axis=0, keepdims=True)
  974. assert_array_equal(c, (a * b).sum(0, keepdims=True))
  975. c = inner1d(a, b, axes=[(-1,), (-1,), ()], keepdims=False)
  976. assert_array_equal(c, (a * b).sum(-1))
  977. c = inner1d(a, b, axes=[(-1,), (-1,), (-1,)], keepdims=True)
  978. assert_array_equal(c, (a * b).sum(-1, keepdims=True))
  979. c = inner1d(a, b, axes=[0, 0], keepdims=False)
  980. assert_array_equal(c, (a * b).sum(0))
  981. c = inner1d(a, b, axes=[0, 0, 0], keepdims=True)
  982. assert_array_equal(c, (a * b).sum(0, keepdims=True))
  983. c = inner1d(a, b, axes=[0, 2], keepdims=False)
  984. assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
  985. c = inner1d(a, b, axes=[0, 2], keepdims=True)
  986. assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
  987. keepdims=True))
  988. c = inner1d(a, b, axes=[0, 2, 2], keepdims=True)
  989. assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
  990. keepdims=True))
  991. c = inner1d(a, b, axes=[0, 2, 0], keepdims=True)
  992. assert_array_equal(c, (a * b.transpose(2, 0, 1)).sum(0, keepdims=True))
  993. # Hardly useful, but should work.
  994. c = inner1d(a, b, axes=[0, 2, 1], keepdims=True)
  995. assert_array_equal(c, (a.transpose(1, 0, 2) * b.transpose(0, 2, 1))
  996. .sum(1, keepdims=True))
  997. # Check with two core dimensions.
  998. a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
  999. expected = uml.det(a)
  1000. c = uml.det(a, keepdims=False)
  1001. assert_array_equal(c, expected)
  1002. c = uml.det(a, keepdims=True)
  1003. assert_array_equal(c, expected[:, np.newaxis, np.newaxis])
  1004. a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
  1005. expected_s, expected_l = uml.slogdet(a)
  1006. cs, cl = uml.slogdet(a, keepdims=False)
  1007. assert_array_equal(cs, expected_s)
  1008. assert_array_equal(cl, expected_l)
  1009. cs, cl = uml.slogdet(a, keepdims=True)
  1010. assert_array_equal(cs, expected_s[:, np.newaxis, np.newaxis])
  1011. assert_array_equal(cl, expected_l[:, np.newaxis, np.newaxis])
  1012. # Sanity check on innerwt.
  1013. a = np.arange(6).reshape((2, 3))
  1014. b = np.arange(10, 16).reshape((2, 3))
  1015. w = np.arange(20, 26).reshape((2, 3))
  1016. assert_array_equal(umt.innerwt(a, b, w, keepdims=True),
  1017. np.sum(a * b * w, axis=-1, keepdims=True))
  1018. assert_array_equal(umt.innerwt(a, b, w, axis=0, keepdims=True),
  1019. np.sum(a * b * w, axis=0, keepdims=True))
  1020. # Check errors.
  1021. # Not a boolean
  1022. assert_raises(TypeError, inner1d, a, b, keepdims='true')
  1023. # More than 1 core dimension, and core output dimensions.
  1024. mm = umt.matrix_multiply
  1025. assert_raises(TypeError, mm, a, b, keepdims=True)
  1026. assert_raises(TypeError, mm, a, b, keepdims=False)
  1027. # Regular ufuncs should not accept keepdims.
  1028. assert_raises(TypeError, np.add, 1., 1., keepdims=False)
  1029. def test_innerwt(self):
  1030. a = np.arange(6).reshape((2, 3))
  1031. b = np.arange(10, 16).reshape((2, 3))
  1032. w = np.arange(20, 26).reshape((2, 3))
  1033. assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1))
  1034. a = np.arange(100, 124).reshape((2, 3, 4))
  1035. b = np.arange(200, 224).reshape((2, 3, 4))
  1036. w = np.arange(300, 324).reshape((2, 3, 4))
  1037. assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1))
  1038. def test_innerwt_empty(self):
  1039. """Test generalized ufunc with zero-sized operands"""
  1040. a = np.array([], dtype='f8')
  1041. b = np.array([], dtype='f8')
  1042. w = np.array([], dtype='f8')
  1043. assert_array_equal(umt.innerwt(a, b, w), np.sum(a*b*w, axis=-1))
  1044. def test_cross1d(self):
  1045. """Test with fixed-sized signature."""
  1046. a = np.eye(3)
  1047. assert_array_equal(umt.cross1d(a, a), np.zeros((3, 3)))
  1048. out = np.zeros((3, 3))
  1049. result = umt.cross1d(a[0], a, out)
  1050. assert_(result is out)
  1051. assert_array_equal(result, np.vstack((np.zeros(3), a[2], -a[1])))
  1052. assert_raises(ValueError, umt.cross1d, np.eye(4), np.eye(4))
  1053. assert_raises(ValueError, umt.cross1d, a, np.arange(4.))
  1054. # Wrong output core dimension.
  1055. assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros((3, 4)))
  1056. # Wrong output broadcast dimension (see gh-15139).
  1057. assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros(3))
  1058. def test_can_ignore_signature(self):
  1059. # Comparing the effects of ? in signature:
  1060. # matrix_multiply: (m,n),(n,p)->(m,p) # all must be there.
  1061. # matmul: (m?,n),(n,p?)->(m?,p?) # allow missing m, p.
  1062. mat = np.arange(12).reshape((2, 3, 2))
  1063. single_vec = np.arange(2)
  1064. col_vec = single_vec[:, np.newaxis]
  1065. col_vec_array = np.arange(8).reshape((2, 2, 2, 1)) + 1
  1066. # matrix @ single column vector with proper dimension
  1067. mm_col_vec = umt.matrix_multiply(mat, col_vec)
  1068. # matmul does the same thing
  1069. matmul_col_vec = umt.matmul(mat, col_vec)
  1070. assert_array_equal(matmul_col_vec, mm_col_vec)
  1071. # matrix @ vector without dimension making it a column vector.
  1072. # matrix multiply fails -> missing core dim.
  1073. assert_raises(ValueError, umt.matrix_multiply, mat, single_vec)
  1074. # matmul mimicker passes, and returns a vector.
  1075. matmul_col = umt.matmul(mat, single_vec)
  1076. assert_array_equal(matmul_col, mm_col_vec.squeeze())
  1077. # Now with a column array: same as for column vector,
  1078. # broadcasting sensibly.
  1079. mm_col_vec = umt.matrix_multiply(mat, col_vec_array)
  1080. matmul_col_vec = umt.matmul(mat, col_vec_array)
  1081. assert_array_equal(matmul_col_vec, mm_col_vec)
  1082. # As above, but for row vector
  1083. single_vec = np.arange(3)
  1084. row_vec = single_vec[np.newaxis, :]
  1085. row_vec_array = np.arange(24).reshape((4, 2, 1, 1, 3)) + 1
  1086. # row vector @ matrix
  1087. mm_row_vec = umt.matrix_multiply(row_vec, mat)
  1088. matmul_row_vec = umt.matmul(row_vec, mat)
  1089. assert_array_equal(matmul_row_vec, mm_row_vec)
  1090. # single row vector @ matrix
  1091. assert_raises(ValueError, umt.matrix_multiply, single_vec, mat)
  1092. matmul_row = umt.matmul(single_vec, mat)
  1093. assert_array_equal(matmul_row, mm_row_vec.squeeze())
  1094. # row vector array @ matrix
  1095. mm_row_vec = umt.matrix_multiply(row_vec_array, mat)
  1096. matmul_row_vec = umt.matmul(row_vec_array, mat)
  1097. assert_array_equal(matmul_row_vec, mm_row_vec)
  1098. # Now for vector combinations
  1099. # row vector @ column vector
  1100. col_vec = row_vec.T
  1101. col_vec_array = row_vec_array.swapaxes(-2, -1)
  1102. mm_row_col_vec = umt.matrix_multiply(row_vec, col_vec)
  1103. matmul_row_col_vec = umt.matmul(row_vec, col_vec)
  1104. assert_array_equal(matmul_row_col_vec, mm_row_col_vec)
  1105. # single row vector @ single col vector
  1106. assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec)
  1107. matmul_row_col = umt.matmul(single_vec, single_vec)
  1108. assert_array_equal(matmul_row_col, mm_row_col_vec.squeeze())
  1109. # row vector array @ matrix
  1110. mm_row_col_array = umt.matrix_multiply(row_vec_array, col_vec_array)
  1111. matmul_row_col_array = umt.matmul(row_vec_array, col_vec_array)
  1112. assert_array_equal(matmul_row_col_array, mm_row_col_array)
  1113. # Finally, check that things are *not* squeezed if one gives an
  1114. # output.
  1115. out = np.zeros_like(mm_row_col_array)
  1116. out = umt.matrix_multiply(row_vec_array, col_vec_array, out=out)
  1117. assert_array_equal(out, mm_row_col_array)
  1118. out[:] = 0
  1119. out = umt.matmul(row_vec_array, col_vec_array, out=out)
  1120. assert_array_equal(out, mm_row_col_array)
  1121. # And check one cannot put missing dimensions back.
  1122. out = np.zeros_like(mm_row_col_vec)
  1123. assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec,
  1124. out)
  1125. # But fine for matmul, since it is just a broadcast.
  1126. out = umt.matmul(single_vec, single_vec, out)
  1127. assert_array_equal(out, mm_row_col_vec.squeeze())
  1128. def test_matrix_multiply(self):
  1129. self.compare_matrix_multiply_results(np.int64)
  1130. self.compare_matrix_multiply_results(np.double)
  1131. def test_matrix_multiply_umath_empty(self):
  1132. res = umt.matrix_multiply(np.ones((0, 10)), np.ones((10, 0)))
  1133. assert_array_equal(res, np.zeros((0, 0)))
  1134. res = umt.matrix_multiply(np.ones((10, 0)), np.ones((0, 10)))
  1135. assert_array_equal(res, np.zeros((10, 10)))
  1136. def compare_matrix_multiply_results(self, tp):
  1137. d1 = np.array(np.random.rand(2, 3, 4), dtype=tp)
  1138. d2 = np.array(np.random.rand(2, 3, 4), dtype=tp)
  1139. msg = "matrix multiply on type %s" % d1.dtype.name
  1140. def permute_n(n):
  1141. if n == 1:
  1142. return ([0],)
  1143. ret = ()
  1144. base = permute_n(n-1)
  1145. for perm in base:
  1146. for i in range(n):
  1147. new = perm + [n-1]
  1148. new[n-1] = new[i]
  1149. new[i] = n-1
  1150. ret += (new,)
  1151. return ret
  1152. def slice_n(n):
  1153. if n == 0:
  1154. return ((),)
  1155. ret = ()
  1156. base = slice_n(n-1)
  1157. for sl in base:
  1158. ret += (sl+(slice(None),),)
  1159. ret += (sl+(slice(0, 1),),)
  1160. return ret
  1161. def broadcastable(s1, s2):
  1162. return s1 == s2 or s1 == 1 or s2 == 1
  1163. permute_3 = permute_n(3)
  1164. slice_3 = slice_n(3) + ((slice(None, None, -1),)*3,)
  1165. ref = True
  1166. for p1 in permute_3:
  1167. for p2 in permute_3:
  1168. for s1 in slice_3:
  1169. for s2 in slice_3:
  1170. a1 = d1.transpose(p1)[s1]
  1171. a2 = d2.transpose(p2)[s2]
  1172. ref = ref and a1.base is not None
  1173. ref = ref and a2.base is not None
  1174. if (a1.shape[-1] == a2.shape[-2] and
  1175. broadcastable(a1.shape[0], a2.shape[0])):
  1176. assert_array_almost_equal(
  1177. umt.matrix_multiply(a1, a2),
  1178. np.sum(a2[..., np.newaxis].swapaxes(-3, -1) *
  1179. a1[..., np.newaxis,:], axis=-1),
  1180. err_msg=msg + ' %s %s' % (str(a1.shape),
  1181. str(a2.shape)))
  1182. assert_equal(ref, True, err_msg="reference check")
  1183. def test_euclidean_pdist(self):
  1184. a = np.arange(12, dtype=float).reshape(4, 3)
  1185. out = np.empty((a.shape[0] * (a.shape[0] - 1) // 2,), dtype=a.dtype)
  1186. umt.euclidean_pdist(a, out)
  1187. b = np.sqrt(np.sum((a[:, None] - a)**2, axis=-1))
  1188. b = b[~np.tri(a.shape[0], dtype=bool)]
  1189. assert_almost_equal(out, b)
  1190. # An output array is required to determine p with signature (n,d)->(p)
  1191. assert_raises(ValueError, umt.euclidean_pdist, a)
  1192. def test_cumsum(self):
  1193. a = np.arange(10)
  1194. result = umt.cumsum(a)
  1195. assert_array_equal(result, a.cumsum())
  1196. def test_object_logical(self):
  1197. a = np.array([3, None, True, False, "test", ""], dtype=object)
  1198. assert_equal(np.logical_or(a, None),
  1199. np.array([x or None for x in a], dtype=object))
  1200. assert_equal(np.logical_or(a, True),
  1201. np.array([x or True for x in a], dtype=object))
  1202. assert_equal(np.logical_or(a, 12),
  1203. np.array([x or 12 for x in a], dtype=object))
  1204. assert_equal(np.logical_or(a, "blah"),
  1205. np.array([x or "blah" for x in a], dtype=object))
  1206. assert_equal(np.logical_and(a, None),
  1207. np.array([x and None for x in a], dtype=object))
  1208. assert_equal(np.logical_and(a, True),
  1209. np.array([x and True for x in a], dtype=object))
  1210. assert_equal(np.logical_and(a, 12),
  1211. np.array([x and 12 for x in a], dtype=object))
  1212. assert_equal(np.logical_and(a, "blah"),
  1213. np.array([x and "blah" for x in a], dtype=object))
  1214. assert_equal(np.logical_not(a),
  1215. np.array([not x for x in a], dtype=object))
  1216. assert_equal(np.logical_or.reduce(a), 3)
  1217. assert_equal(np.logical_and.reduce(a), None)
  1218. def test_object_comparison(self):
  1219. class HasComparisons:
  1220. def __eq__(self, other):
  1221. return '=='
  1222. arr0d = np.array(HasComparisons())
  1223. assert_equal(arr0d == arr0d, True)
  1224. assert_equal(np.equal(arr0d, arr0d), True) # normal behavior is a cast
  1225. arr1d = np.array([HasComparisons()])
  1226. assert_equal(arr1d == arr1d, np.array([True]))
  1227. assert_equal(np.equal(arr1d, arr1d), np.array([True])) # normal behavior is a cast
  1228. assert_equal(np.equal(arr1d, arr1d, dtype=object), np.array(['==']))
  1229. def test_object_array_reduction(self):
  1230. # Reductions on object arrays
  1231. a = np.array(['a', 'b', 'c'], dtype=object)
  1232. assert_equal(np.sum(a), 'abc')
  1233. assert_equal(np.max(a), 'c')
  1234. assert_equal(np.min(a), 'a')
  1235. a = np.array([True, False, True], dtype=object)
  1236. assert_equal(np.sum(a), 2)
  1237. assert_equal(np.prod(a), 0)
  1238. assert_equal(np.any(a), True)
  1239. assert_equal(np.all(a), False)
  1240. assert_equal(np.max(a), True)
  1241. assert_equal(np.min(a), False)
  1242. assert_equal(np.array([[1]], dtype=object).sum(), 1)
  1243. assert_equal(np.array([[[1, 2]]], dtype=object).sum((0, 1)), [1, 2])
  1244. assert_equal(np.array([1], dtype=object).sum(initial=1), 2)
  1245. assert_equal(np.array([[1], [2, 3]], dtype=object)
  1246. .sum(initial=[0], where=[False, True]), [0, 2, 3])
  1247. def test_object_array_accumulate_inplace(self):
  1248. # Checks that in-place accumulates work, see also gh-7402
  1249. arr = np.ones(4, dtype=object)
  1250. arr[:] = [[1] for i in range(4)]
  1251. # Twice reproduced also for tuples:
  1252. np.add.accumulate(arr, out=arr)
  1253. np.add.accumulate(arr, out=arr)
  1254. assert_array_equal(arr,
  1255. np.array([[1]*i for i in [1, 3, 6, 10]], dtype=object),
  1256. )
  1257. # And the same if the axis argument is used
  1258. arr = np.ones((2, 4), dtype=object)
  1259. arr[0, :] = [[2] for i in range(4)]
  1260. np.add.accumulate(arr, out=arr, axis=-1)
  1261. np.add.accumulate(arr, out=arr, axis=-1)
  1262. assert_array_equal(arr[0, :],
  1263. np.array([[2]*i for i in [1, 3, 6, 10]], dtype=object),
  1264. )
  1265. def test_object_array_accumulate_failure(self):
  1266. # Typical accumulation on object works as expected:
  1267. res = np.add.accumulate(np.array([1, 0, 2], dtype=object))
  1268. assert_array_equal(res, np.array([1, 1, 3], dtype=object))
  1269. # But errors are propagated from the inner-loop if they occur:
  1270. with pytest.raises(TypeError):
  1271. np.add.accumulate([1, None, 2])
  1272. def test_object_array_reduceat_inplace(self):
  1273. # Checks that in-place reduceats work, see also gh-7465
  1274. arr = np.empty(4, dtype=object)
  1275. arr[:] = [[1] for i in range(4)]
  1276. out = np.empty(4, dtype=object)
  1277. out[:] = [[1] for i in range(4)]
  1278. np.add.reduceat(arr, np.arange(4), out=arr)
  1279. np.add.reduceat(arr, np.arange(4), out=arr)
  1280. assert_array_equal(arr, out)
  1281. # And the same if the axis argument is used
  1282. arr = np.ones((2, 4), dtype=object)
  1283. arr[0, :] = [[2] for i in range(4)]
  1284. out = np.ones((2, 4), dtype=object)
  1285. out[0, :] = [[2] for i in range(4)]
  1286. np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
  1287. np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
  1288. assert_array_equal(arr, out)
  1289. def test_object_array_reduceat_failure(self):
  1290. # Reduceat works as expected when no invalid operation occurs (None is
  1291. # not involved in an operation here)
  1292. res = np.add.reduceat(np.array([1, None, 2], dtype=object), [1, 2])
  1293. assert_array_equal(res, np.array([None, 2], dtype=object))
  1294. # But errors when None would be involved in an operation:
  1295. with pytest.raises(TypeError):
  1296. np.add.reduceat([1, None, 2], [0, 2])
  1297. def test_zerosize_reduction(self):
  1298. # Test with default dtype and object dtype
  1299. for a in [[], np.array([], dtype=object)]:
  1300. assert_equal(np.sum(a), 0)
  1301. assert_equal(np.prod(a), 1)
  1302. assert_equal(np.any(a), False)
  1303. assert_equal(np.all(a), True)
  1304. assert_raises(ValueError, np.max, a)
  1305. assert_raises(ValueError, np.min, a)
  1306. def test_axis_out_of_bounds(self):
  1307. a = np.array([False, False])
  1308. assert_raises(np.AxisError, a.all, axis=1)
  1309. a = np.array([False, False])
  1310. assert_raises(np.AxisError, a.all, axis=-2)
  1311. a = np.array([False, False])
  1312. assert_raises(np.AxisError, a.any, axis=1)
  1313. a = np.array([False, False])
  1314. assert_raises(np.AxisError, a.any, axis=-2)
  1315. def test_scalar_reduction(self):
  1316. # The functions 'sum', 'prod', etc allow specifying axis=0
  1317. # even for scalars
  1318. assert_equal(np.sum(3, axis=0), 3)
  1319. assert_equal(np.prod(3.5, axis=0), 3.5)
  1320. assert_equal(np.any(True, axis=0), True)
  1321. assert_equal(np.all(False, axis=0), False)
  1322. assert_equal(np.max(3, axis=0), 3)
  1323. assert_equal(np.min(2.5, axis=0), 2.5)
  1324. # Check scalar behaviour for ufuncs without an identity
  1325. assert_equal(np.power.reduce(3), 3)
  1326. # Make sure that scalars are coming out from this operation
  1327. assert_(type(np.prod(np.float32(2.5), axis=0)) is np.float32)
  1328. assert_(type(np.sum(np.float32(2.5), axis=0)) is np.float32)
  1329. assert_(type(np.max(np.float32(2.5), axis=0)) is np.float32)
  1330. assert_(type(np.min(np.float32(2.5), axis=0)) is np.float32)
  1331. # check if scalars/0-d arrays get cast
  1332. assert_(type(np.any(0, axis=0)) is np.bool_)
  1333. # assert that 0-d arrays get wrapped
  1334. class MyArray(np.ndarray):
  1335. pass
  1336. a = np.array(1).view(MyArray)
  1337. assert_(type(np.any(a)) is MyArray)
  1338. def test_casting_out_param(self):
  1339. # Test that it's possible to do casts on output
  1340. a = np.ones((200, 100), np.int64)
  1341. b = np.ones((200, 100), np.int64)
  1342. c = np.ones((200, 100), np.float64)
  1343. np.add(a, b, out=c)
  1344. assert_equal(c, 2)
  1345. a = np.zeros(65536)
  1346. b = np.zeros(65536, dtype=np.float32)
  1347. np.subtract(a, 0, out=b)
  1348. assert_equal(b, 0)
  1349. def test_where_param(self):
  1350. # Test that the where= ufunc parameter works with regular arrays
  1351. a = np.arange(7)
  1352. b = np.ones(7)
  1353. c = np.zeros(7)
  1354. np.add(a, b, out=c, where=(a % 2 == 1))
  1355. assert_equal(c, [0, 2, 0, 4, 0, 6, 0])
  1356. a = np.arange(4).reshape(2, 2) + 2
  1357. np.power(a, [2, 3], out=a, where=[[0, 1], [1, 0]])
  1358. assert_equal(a, [[2, 27], [16, 5]])
  1359. # Broadcasting the where= parameter
  1360. np.subtract(a, 2, out=a, where=[True, False])
  1361. assert_equal(a, [[0, 27], [14, 5]])
  1362. def test_where_param_buffer_output(self):
  1363. # This test is temporarily skipped because it requires
  1364. # adding masking features to the nditer to work properly
  1365. # With casting on output
  1366. a = np.ones(10, np.int64)
  1367. b = np.ones(10, np.int64)
  1368. c = 1.5 * np.ones(10, np.float64)
  1369. np.add(a, b, out=c, where=[1, 0, 0, 1, 0, 0, 1, 1, 1, 0])
  1370. assert_equal(c, [2, 1.5, 1.5, 2, 1.5, 1.5, 2, 2, 2, 1.5])
  1371. def test_where_param_alloc(self):
  1372. # With casting and allocated output
  1373. a = np.array([1], dtype=np.int64)
  1374. m = np.array([True], dtype=bool)
  1375. assert_equal(np.sqrt(a, where=m), [1])
  1376. # No casting and allocated output
  1377. a = np.array([1], dtype=np.float64)
  1378. m = np.array([True], dtype=bool)
  1379. assert_equal(np.sqrt(a, where=m), [1])
  1380. def test_where_with_broadcasting(self):
  1381. # See gh-17198
  1382. a = np.random.random((5000, 4))
  1383. b = np.random.random((5000, 1))
  1384. where = a > 0.3
  1385. out = np.full_like(a, 0)
  1386. np.less(a, b, where=where, out=out)
  1387. b_where = np.broadcast_to(b, a.shape)[where]
  1388. assert_array_equal((a[where] < b_where), out[where].astype(bool))
  1389. assert not out[~where].any() # outside mask, out remains all 0
  1390. def check_identityless_reduction(self, a):
  1391. # np.minimum.reduce is an identityless reduction
  1392. # Verify that it sees the zero at various positions
  1393. a[...] = 1
  1394. a[1, 0, 0] = 0
  1395. assert_equal(np.minimum.reduce(a, axis=None), 0)
  1396. assert_equal(np.minimum.reduce(a, axis=(0, 1)), [0, 1, 1, 1])
  1397. assert_equal(np.minimum.reduce(a, axis=(0, 2)), [0, 1, 1])
  1398. assert_equal(np.minimum.reduce(a, axis=(1, 2)), [1, 0])
  1399. assert_equal(np.minimum.reduce(a, axis=0),
  1400. [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
  1401. assert_equal(np.minimum.reduce(a, axis=1),
  1402. [[1, 1, 1, 1], [0, 1, 1, 1]])
  1403. assert_equal(np.minimum.reduce(a, axis=2),
  1404. [[1, 1, 1], [0, 1, 1]])
  1405. assert_equal(np.minimum.reduce(a, axis=()), a)
  1406. a[...] = 1
  1407. a[0, 1, 0] = 0
  1408. assert_equal(np.minimum.reduce(a, axis=None), 0)
  1409. assert_equal(np.minimum.reduce(a, axis=(0, 1)), [0, 1, 1, 1])
  1410. assert_equal(np.minimum.reduce(a, axis=(0, 2)), [1, 0, 1])
  1411. assert_equal(np.minimum.reduce(a, axis=(1, 2)), [0, 1])
  1412. assert_equal(np.minimum.reduce(a, axis=0),
  1413. [[1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]])
  1414. assert_equal(np.minimum.reduce(a, axis=1),
  1415. [[0, 1, 1, 1], [1, 1, 1, 1]])
  1416. assert_equal(np.minimum.reduce(a, axis=2),
  1417. [[1, 0, 1], [1, 1, 1]])
  1418. assert_equal(np.minimum.reduce(a, axis=()), a)
  1419. a[...] = 1
  1420. a[0, 0, 1] = 0
  1421. assert_equal(np.minimum.reduce(a, axis=None), 0)
  1422. assert_equal(np.minimum.reduce(a, axis=(0, 1)), [1, 0, 1, 1])
  1423. assert_equal(np.minimum.reduce(a, axis=(0, 2)), [0, 1, 1])
  1424. assert_equal(np.minimum.reduce(a, axis=(1, 2)), [0, 1])
  1425. assert_equal(np.minimum.reduce(a, axis=0),
  1426. [[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
  1427. assert_equal(np.minimum.reduce(a, axis=1),
  1428. [[1, 0, 1, 1], [1, 1, 1, 1]])
  1429. assert_equal(np.minimum.reduce(a, axis=2),
  1430. [[0, 1, 1], [1, 1, 1]])
  1431. assert_equal(np.minimum.reduce(a, axis=()), a)
  1432. @requires_memory(6 * 1024**3)
  1433. def test_identityless_reduction_huge_array(self):
  1434. # Regression test for gh-20921 (copying identity incorrectly failed)
  1435. arr = np.zeros((2, 2**31), 'uint8')
  1436. arr[:, 0] = [1, 3]
  1437. arr[:, -1] = [4, 1]
  1438. res = np.maximum.reduce(arr, axis=0)
  1439. del arr
  1440. assert res[0] == 3
  1441. assert res[-1] == 4
  1442. def test_identityless_reduction_corder(self):
  1443. a = np.empty((2, 3, 4), order='C')
  1444. self.check_identityless_reduction(a)
  1445. def test_identityless_reduction_forder(self):
  1446. a = np.empty((2, 3, 4), order='F')
  1447. self.check_identityless_reduction(a)
  1448. def test_identityless_reduction_otherorder(self):
  1449. a = np.empty((2, 4, 3), order='C').swapaxes(1, 2)
  1450. self.check_identityless_reduction(a)
  1451. def test_identityless_reduction_noncontig(self):
  1452. a = np.empty((3, 5, 4), order='C').swapaxes(1, 2)
  1453. a = a[1:, 1:, 1:]
  1454. self.check_identityless_reduction(a)
  1455. def test_identityless_reduction_noncontig_unaligned(self):
  1456. a = np.empty((3*4*5*8 + 1,), dtype='i1')
  1457. a = a[1:].view(dtype='f8')
  1458. a.shape = (3, 4, 5)
  1459. a = a[1:, 1:, 1:]
  1460. self.check_identityless_reduction(a)
  1461. def test_initial_reduction(self):
  1462. # np.minimum.reduce is an identityless reduction
  1463. # For cases like np.maximum(np.abs(...), initial=0)
  1464. # More generally, a supremum over non-negative numbers.
  1465. assert_equal(np.maximum.reduce([], initial=0), 0)
  1466. # For cases like reduction of an empty array over the reals.
  1467. assert_equal(np.minimum.reduce([], initial=np.inf), np.inf)
  1468. assert_equal(np.maximum.reduce([], initial=-np.inf), -np.inf)
  1469. # Random tests
  1470. assert_equal(np.minimum.reduce([5], initial=4), 4)
  1471. assert_equal(np.maximum.reduce([4], initial=5), 5)
  1472. assert_equal(np.maximum.reduce([5], initial=4), 5)
  1473. assert_equal(np.minimum.reduce([4], initial=5), 4)
  1474. # Check initial=None raises ValueError for both types of ufunc reductions
  1475. assert_raises(ValueError, np.minimum.reduce, [], initial=None)
  1476. assert_raises(ValueError, np.add.reduce, [], initial=None)
  1477. # Check that np._NoValue gives default behavior.
  1478. assert_equal(np.add.reduce([], initial=np._NoValue), 0)
  1479. # Check that initial kwarg behaves as intended for dtype=object
  1480. a = np.array([10], dtype=object)
  1481. res = np.add.reduce(a, initial=5)
  1482. assert_equal(res, 15)
  1483. @pytest.mark.parametrize('axis', (0, 1, None))
  1484. @pytest.mark.parametrize('where', (np.array([False, True, True]),
  1485. np.array([[True], [False], [True]]),
  1486. np.array([[True, False, False],
  1487. [False, True, False],
  1488. [False, True, True]])))
  1489. def test_reduction_with_where(self, axis, where):
  1490. a = np.arange(9.).reshape(3, 3)
  1491. a_copy = a.copy()
  1492. a_check = np.zeros_like(a)
  1493. np.positive(a, out=a_check, where=where)
  1494. res = np.add.reduce(a, axis=axis, where=where)
  1495. check = a_check.sum(axis)
  1496. assert_equal(res, check)
  1497. # Check we do not overwrite elements of a internally.
  1498. assert_array_equal(a, a_copy)
  1499. @pytest.mark.parametrize(('axis', 'where'),
  1500. ((0, np.array([True, False, True])),
  1501. (1, [True, True, False]),
  1502. (None, True)))
  1503. @pytest.mark.parametrize('initial', (-np.inf, 5.))
  1504. def test_reduction_with_where_and_initial(self, axis, where, initial):
  1505. a = np.arange(9.).reshape(3, 3)
  1506. a_copy = a.copy()
  1507. a_check = np.full(a.shape, -np.inf)
  1508. np.positive(a, out=a_check, where=where)
  1509. res = np.maximum.reduce(a, axis=axis, where=where, initial=initial)
  1510. check = a_check.max(axis, initial=initial)
  1511. assert_equal(res, check)
  1512. def test_reduction_where_initial_needed(self):
  1513. a = np.arange(9.).reshape(3, 3)
  1514. m = [False, True, False]
  1515. assert_raises(ValueError, np.maximum.reduce, a, where=m)
  1516. def test_identityless_reduction_nonreorderable(self):
  1517. a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]])
  1518. res = np.divide.reduce(a, axis=0)
  1519. assert_equal(res, [8.0, 4.0, 8.0])
  1520. res = np.divide.reduce(a, axis=1)
  1521. assert_equal(res, [2.0, 8.0])
  1522. res = np.divide.reduce(a, axis=())
  1523. assert_equal(res, a)
  1524. assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1))
  1525. def test_reduce_zero_axis(self):
  1526. # If we have a n x m array and do a reduction with axis=1, then we are
  1527. # doing n reductions, and each reduction takes an m-element array. For
  1528. # a reduction operation without an identity, then:
  1529. # n > 0, m > 0: fine
  1530. # n = 0, m > 0: fine, doing 0 reductions of m-element arrays
  1531. # n > 0, m = 0: can't reduce a 0-element array, ValueError
  1532. # n = 0, m = 0: can't reduce a 0-element array, ValueError (for
  1533. # consistency with the above case)
  1534. # This test doesn't actually look at return values, it just checks to
  1535. # make sure that error we get an error in exactly those cases where we
  1536. # expect one, and assumes the calculations themselves are done
  1537. # correctly.
  1538. def ok(f, *args, **kwargs):
  1539. f(*args, **kwargs)
  1540. def err(f, *args, **kwargs):
  1541. assert_raises(ValueError, f, *args, **kwargs)
  1542. def t(expect, func, n, m):
  1543. expect(func, np.zeros((n, m)), axis=1)
  1544. expect(func, np.zeros((m, n)), axis=0)
  1545. expect(func, np.zeros((n // 2, n // 2, m)), axis=2)
  1546. expect(func, np.zeros((n // 2, m, n // 2)), axis=1)
  1547. expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2))
  1548. expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2))
  1549. expect(func, np.zeros((m // 3, m // 3, m // 3,
  1550. n // 2, n // 2)),
  1551. axis=(0, 1, 2))
  1552. # Check what happens if the inner (resp. outer) dimensions are a
  1553. # mix of zero and non-zero:
  1554. expect(func, np.zeros((10, m, n)), axis=(0, 1))
  1555. expect(func, np.zeros((10, n, m)), axis=(0, 2))
  1556. expect(func, np.zeros((m, 10, n)), axis=0)
  1557. expect(func, np.zeros((10, m, n)), axis=1)
  1558. expect(func, np.zeros((10, n, m)), axis=2)
  1559. # np.maximum is just an arbitrary ufunc with no reduction identity
  1560. assert_equal(np.maximum.identity, None)
  1561. t(ok, np.maximum.reduce, 30, 30)
  1562. t(ok, np.maximum.reduce, 0, 30)
  1563. t(err, np.maximum.reduce, 30, 0)
  1564. t(err, np.maximum.reduce, 0, 0)
  1565. err(np.maximum.reduce, [])
  1566. np.maximum.reduce(np.zeros((0, 0)), axis=())
  1567. # all of the combinations are fine for a reduction that has an
  1568. # identity
  1569. t(ok, np.add.reduce, 30, 30)
  1570. t(ok, np.add.reduce, 0, 30)
  1571. t(ok, np.add.reduce, 30, 0)
  1572. t(ok, np.add.reduce, 0, 0)
  1573. np.add.reduce([])
  1574. np.add.reduce(np.zeros((0, 0)), axis=())
  1575. # OTOH, accumulate always makes sense for any combination of n and m,
  1576. # because it maps an m-element array to an m-element array. These
  1577. # tests are simpler because accumulate doesn't accept multiple axes.
  1578. for uf in (np.maximum, np.add):
  1579. uf.accumulate(np.zeros((30, 0)), axis=0)
  1580. uf.accumulate(np.zeros((0, 30)), axis=0)
  1581. uf.accumulate(np.zeros((30, 30)), axis=0)
  1582. uf.accumulate(np.zeros((0, 0)), axis=0)
  1583. def test_safe_casting(self):
  1584. # In old versions of numpy, in-place operations used the 'unsafe'
  1585. # casting rules. In versions >= 1.10, 'same_kind' is the
  1586. # default and an exception is raised instead of a warning.
  1587. # when 'same_kind' is not satisfied.
  1588. a = np.array([1, 2, 3], dtype=int)
  1589. # Non-in-place addition is fine
  1590. assert_array_equal(assert_no_warnings(np.add, a, 1.1),
  1591. [2.1, 3.1, 4.1])
  1592. assert_raises(TypeError, np.add, a, 1.1, out=a)
  1593. def add_inplace(a, b):
  1594. a += b
  1595. assert_raises(TypeError, add_inplace, a, 1.1)
  1596. # Make sure that explicitly overriding the exception is allowed:
  1597. assert_no_warnings(np.add, a, 1.1, out=a, casting="unsafe")
  1598. assert_array_equal(a, [2, 3, 4])
  1599. def test_ufunc_custom_out(self):
  1600. # Test ufunc with built in input types and custom output type
  1601. a = np.array([0, 1, 2], dtype='i8')
  1602. b = np.array([0, 1, 2], dtype='i8')
  1603. c = np.empty(3, dtype=_rational_tests.rational)
  1604. # Output must be specified so numpy knows what
  1605. # ufunc signature to look for
  1606. result = _rational_tests.test_add(a, b, c)
  1607. target = np.array([0, 2, 4], dtype=_rational_tests.rational)
  1608. assert_equal(result, target)
  1609. # The new resolution means that we can (usually) find custom loops
  1610. # as long as they match exactly:
  1611. result = _rational_tests.test_add(a, b)
  1612. assert_equal(result, target)
  1613. # This works even more generally, so long the default common-dtype
  1614. # promoter works out:
  1615. result = _rational_tests.test_add(a, b.astype(np.uint16), out=c)
  1616. assert_equal(result, target)
  1617. # But, it can be fooled, e.g. (use scalars, which forces legacy
  1618. # type resolution to kick in, which then fails):
  1619. with assert_raises(TypeError):
  1620. _rational_tests.test_add(a, np.uint16(2))
  1621. def test_operand_flags(self):
  1622. a = np.arange(16, dtype='l').reshape(4, 4)
  1623. b = np.arange(9, dtype='l').reshape(3, 3)
  1624. opflag_tests.inplace_add(a[:-1, :-1], b)
  1625. assert_equal(a, np.array([[0, 2, 4, 3], [7, 9, 11, 7],
  1626. [14, 16, 18, 11], [12, 13, 14, 15]], dtype='l'))
  1627. a = np.array(0)
  1628. opflag_tests.inplace_add(a, 3)
  1629. assert_equal(a, 3)
  1630. opflag_tests.inplace_add(a, [3, 4])
  1631. assert_equal(a, 10)
  1632. def test_struct_ufunc(self):
  1633. import numpy.core._struct_ufunc_tests as struct_ufunc
  1634. a = np.array([(1, 2, 3)], dtype='u8,u8,u8')
  1635. b = np.array([(1, 2, 3)], dtype='u8,u8,u8')
  1636. result = struct_ufunc.add_triplet(a, b)
  1637. assert_equal(result, np.array([(2, 4, 6)], dtype='u8,u8,u8'))
  1638. assert_raises(RuntimeError, struct_ufunc.register_fail)
  1639. def test_custom_ufunc(self):
  1640. a = np.array(
  1641. [_rational_tests.rational(1, 2),
  1642. _rational_tests.rational(1, 3),
  1643. _rational_tests.rational(1, 4)],
  1644. dtype=_rational_tests.rational)
  1645. b = np.array(
  1646. [_rational_tests.rational(1, 2),
  1647. _rational_tests.rational(1, 3),
  1648. _rational_tests.rational(1, 4)],
  1649. dtype=_rational_tests.rational)
  1650. result = _rational_tests.test_add_rationals(a, b)
  1651. expected = np.array(
  1652. [_rational_tests.rational(1),
  1653. _rational_tests.rational(2, 3),
  1654. _rational_tests.rational(1, 2)],
  1655. dtype=_rational_tests.rational)
  1656. assert_equal(result, expected)
  1657. def test_custom_ufunc_forced_sig(self):
  1658. # gh-9351 - looking for a non-first userloop would previously hang
  1659. with assert_raises(TypeError):
  1660. np.multiply(_rational_tests.rational(1), 1,
  1661. signature=(_rational_tests.rational, int, None))
  1662. def test_custom_array_like(self):
  1663. class MyThing:
  1664. __array_priority__ = 1000
  1665. rmul_count = 0
  1666. getitem_count = 0
  1667. def __init__(self, shape):
  1668. self.shape = shape
  1669. def __len__(self):
  1670. return self.shape[0]
  1671. def __getitem__(self, i):
  1672. MyThing.getitem_count += 1
  1673. if not isinstance(i, tuple):
  1674. i = (i,)
  1675. if len(i) > self.ndim:
  1676. raise IndexError("boo")
  1677. return MyThing(self.shape[len(i):])
  1678. def __rmul__(self, other):
  1679. MyThing.rmul_count += 1
  1680. return self
  1681. np.float64(5)*MyThing((3, 3))
  1682. assert_(MyThing.rmul_count == 1, MyThing.rmul_count)
  1683. assert_(MyThing.getitem_count <= 2, MyThing.getitem_count)
  1684. def test_inplace_fancy_indexing(self):
  1685. a = np.arange(10)
  1686. np.add.at(a, [2, 5, 2], 1)
  1687. assert_equal(a, [0, 1, 4, 3, 4, 6, 6, 7, 8, 9])
  1688. a = np.arange(10)
  1689. b = np.array([100, 100, 100])
  1690. np.add.at(a, [2, 5, 2], b)
  1691. assert_equal(a, [0, 1, 202, 3, 4, 105, 6, 7, 8, 9])
  1692. a = np.arange(9).reshape(3, 3)
  1693. b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
  1694. np.add.at(a, (slice(None), [1, 2, 1]), b)
  1695. assert_equal(a, [[0, 201, 102], [3, 404, 205], [6, 607, 308]])
  1696. a = np.arange(27).reshape(3, 3, 3)
  1697. b = np.array([100, 200, 300])
  1698. np.add.at(a, (slice(None), slice(None), [1, 2, 1]), b)
  1699. assert_equal(a,
  1700. [[[0, 401, 202],
  1701. [3, 404, 205],
  1702. [6, 407, 208]],
  1703. [[9, 410, 211],
  1704. [12, 413, 214],
  1705. [15, 416, 217]],
  1706. [[18, 419, 220],
  1707. [21, 422, 223],
  1708. [24, 425, 226]]])
  1709. a = np.arange(9).reshape(3, 3)
  1710. b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
  1711. np.add.at(a, ([1, 2, 1], slice(None)), b)
  1712. assert_equal(a, [[0, 1, 2], [403, 404, 405], [206, 207, 208]])
  1713. a = np.arange(27).reshape(3, 3, 3)
  1714. b = np.array([100, 200, 300])
  1715. np.add.at(a, (slice(None), [1, 2, 1], slice(None)), b)
  1716. assert_equal(a,
  1717. [[[0, 1, 2],
  1718. [203, 404, 605],
  1719. [106, 207, 308]],
  1720. [[9, 10, 11],
  1721. [212, 413, 614],
  1722. [115, 216, 317]],
  1723. [[18, 19, 20],
  1724. [221, 422, 623],
  1725. [124, 225, 326]]])
  1726. a = np.arange(9).reshape(3, 3)
  1727. b = np.array([100, 200, 300])
  1728. np.add.at(a, (0, [1, 2, 1]), b)
  1729. assert_equal(a, [[0, 401, 202], [3, 4, 5], [6, 7, 8]])
  1730. a = np.arange(27).reshape(3, 3, 3)
  1731. b = np.array([100, 200, 300])
  1732. np.add.at(a, ([1, 2, 1], 0, slice(None)), b)
  1733. assert_equal(a,
  1734. [[[0, 1, 2],
  1735. [3, 4, 5],
  1736. [6, 7, 8]],
  1737. [[209, 410, 611],
  1738. [12, 13, 14],
  1739. [15, 16, 17]],
  1740. [[118, 219, 320],
  1741. [21, 22, 23],
  1742. [24, 25, 26]]])
  1743. a = np.arange(27).reshape(3, 3, 3)
  1744. b = np.array([100, 200, 300])
  1745. np.add.at(a, (slice(None), slice(None), slice(None)), b)
  1746. assert_equal(a,
  1747. [[[100, 201, 302],
  1748. [103, 204, 305],
  1749. [106, 207, 308]],
  1750. [[109, 210, 311],
  1751. [112, 213, 314],
  1752. [115, 216, 317]],
  1753. [[118, 219, 320],
  1754. [121, 222, 323],
  1755. [124, 225, 326]]])
  1756. a = np.arange(10)
  1757. np.negative.at(a, [2, 5, 2])
  1758. assert_equal(a, [0, 1, 2, 3, 4, -5, 6, 7, 8, 9])
  1759. # Test 0-dim array
  1760. a = np.array(0)
  1761. np.add.at(a, (), 1)
  1762. assert_equal(a, 1)
  1763. assert_raises(IndexError, np.add.at, a, 0, 1)
  1764. assert_raises(IndexError, np.add.at, a, [], 1)
  1765. # Test mixed dtypes
  1766. a = np.arange(10)
  1767. np.power.at(a, [1, 2, 3, 2], 3.5)
  1768. assert_equal(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9]))
  1769. # Test boolean indexing and boolean ufuncs
  1770. a = np.arange(10)
  1771. index = a % 2 == 0
  1772. np.equal.at(a, index, [0, 2, 4, 6, 8])
  1773. assert_equal(a, [1, 1, 1, 3, 1, 5, 1, 7, 1, 9])
  1774. # Test unary operator
  1775. a = np.arange(10, dtype='u4')
  1776. np.invert.at(a, [2, 5, 2])
  1777. assert_equal(a, [0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, 7, 8, 9])
  1778. # Test empty subspace
  1779. orig = np.arange(4)
  1780. a = orig[:, None][:, 0:0]
  1781. np.add.at(a, [0, 1], 3)
  1782. assert_array_equal(orig, np.arange(4))
  1783. # Test with swapped byte order
  1784. index = np.array([1, 2, 1], np.dtype('i').newbyteorder())
  1785. values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder())
  1786. np.add.at(values, index, 3)
  1787. assert_array_equal(values, [1, 8, 6, 4])
  1788. # Test exception thrown
  1789. values = np.array(['a', 1], dtype=object)
  1790. assert_raises(TypeError, np.add.at, values, [0, 1], 1)
  1791. assert_array_equal(values, np.array(['a', 1], dtype=object))
  1792. # Test multiple output ufuncs raise error, gh-5665
  1793. assert_raises(ValueError, np.modf.at, np.arange(10), [1])
  1794. # Test maximum
  1795. a = np.array([1, 2, 3])
  1796. np.maximum.at(a, [0], 0)
  1797. assert_equal(np.array([1, 2, 3]), a)
  1798. def test_at_not_none_signature(self):
  1799. # Test ufuncs with non-trivial signature raise a TypeError
  1800. a = np.ones((2, 2, 2))
  1801. b = np.ones((1, 2, 2))
  1802. assert_raises(TypeError, np.matmul.at, a, [0], b)
  1803. a = np.array([[[1, 2], [3, 4]]])
  1804. assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0])
  1805. def test_reduce_arguments(self):
  1806. f = np.add.reduce
  1807. d = np.ones((5,2), dtype=int)
  1808. o = np.ones((2,), dtype=d.dtype)
  1809. r = o * 5
  1810. assert_equal(f(d), r)
  1811. # a, axis=0, dtype=None, out=None, keepdims=False
  1812. assert_equal(f(d, axis=0), r)
  1813. assert_equal(f(d, 0), r)
  1814. assert_equal(f(d, 0, dtype=None), r)
  1815. assert_equal(f(d, 0, dtype='i'), r)
  1816. assert_equal(f(d, 0, 'i'), r)
  1817. assert_equal(f(d, 0, None), r)
  1818. assert_equal(f(d, 0, None, out=None), r)
  1819. assert_equal(f(d, 0, None, out=o), r)
  1820. assert_equal(f(d, 0, None, o), r)
  1821. assert_equal(f(d, 0, None, None), r)
  1822. assert_equal(f(d, 0, None, None, keepdims=False), r)
  1823. assert_equal(f(d, 0, None, None, True), r.reshape((1,) + r.shape))
  1824. assert_equal(f(d, 0, None, None, False, 0), r)
  1825. assert_equal(f(d, 0, None, None, False, initial=0), r)
  1826. assert_equal(f(d, 0, None, None, False, 0, True), r)
  1827. assert_equal(f(d, 0, None, None, False, 0, where=True), r)
  1828. # multiple keywords
  1829. assert_equal(f(d, axis=0, dtype=None, out=None, keepdims=False), r)
  1830. assert_equal(f(d, 0, dtype=None, out=None, keepdims=False), r)
  1831. assert_equal(f(d, 0, None, out=None, keepdims=False), r)
  1832. assert_equal(f(d, 0, None, out=None, keepdims=False, initial=0,
  1833. where=True), r)
  1834. # too little
  1835. assert_raises(TypeError, f)
  1836. # too much
  1837. assert_raises(TypeError, f, d, 0, None, None, False, 0, True, 1)
  1838. # invalid axis
  1839. assert_raises(TypeError, f, d, "invalid")
  1840. assert_raises(TypeError, f, d, axis="invalid")
  1841. assert_raises(TypeError, f, d, axis="invalid", dtype=None,
  1842. keepdims=True)
  1843. # invalid dtype
  1844. assert_raises(TypeError, f, d, 0, "invalid")
  1845. assert_raises(TypeError, f, d, dtype="invalid")
  1846. assert_raises(TypeError, f, d, dtype="invalid", out=None)
  1847. # invalid out
  1848. assert_raises(TypeError, f, d, 0, None, "invalid")
  1849. assert_raises(TypeError, f, d, out="invalid")
  1850. assert_raises(TypeError, f, d, out="invalid", dtype=None)
  1851. # keepdims boolean, no invalid value
  1852. # assert_raises(TypeError, f, d, 0, None, None, "invalid")
  1853. # assert_raises(TypeError, f, d, keepdims="invalid", axis=0, dtype=None)
  1854. # invalid mix
  1855. assert_raises(TypeError, f, d, 0, keepdims="invalid", dtype="invalid",
  1856. out=None)
  1857. # invalid keyword
  1858. assert_raises(TypeError, f, d, axis=0, dtype=None, invalid=0)
  1859. assert_raises(TypeError, f, d, invalid=0)
  1860. assert_raises(TypeError, f, d, 0, keepdims=True, invalid="invalid",
  1861. out=None)
  1862. assert_raises(TypeError, f, d, axis=0, dtype=None, keepdims=True,
  1863. out=None, invalid=0)
  1864. assert_raises(TypeError, f, d, axis=0, dtype=None,
  1865. out=None, invalid=0)
  1866. def test_structured_equal(self):
  1867. # https://github.com/numpy/numpy/issues/4855
  1868. class MyA(np.ndarray):
  1869. def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
  1870. return getattr(ufunc, method)(*(input.view(np.ndarray)
  1871. for input in inputs), **kwargs)
  1872. a = np.arange(12.).reshape(4,3)
  1873. ra = a.view(dtype=('f8,f8,f8')).squeeze()
  1874. mra = ra.view(MyA)
  1875. target = np.array([ True, False, False, False], dtype=bool)
  1876. assert_equal(np.all(target == (mra == ra[0])), True)
  1877. def test_scalar_equal(self):
  1878. # Scalar comparisons should always work, without deprecation warnings.
  1879. # even when the ufunc fails.
  1880. a = np.array(0.)
  1881. b = np.array('a')
  1882. assert_(a != b)
  1883. assert_(b != a)
  1884. assert_(not (a == b))
  1885. assert_(not (b == a))
  1886. def test_NotImplemented_not_returned(self):
  1887. # See gh-5964 and gh-2091. Some of these functions are not operator
  1888. # related and were fixed for other reasons in the past.
  1889. binary_funcs = [
  1890. np.power, np.add, np.subtract, np.multiply, np.divide,
  1891. np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
  1892. np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
  1893. np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
  1894. np.maximum, np.minimum, np.mod,
  1895. np.greater, np.greater_equal, np.less, np.less_equal,
  1896. np.equal, np.not_equal]
  1897. a = np.array('1')
  1898. b = 1
  1899. c = np.array([1., 2.])
  1900. for f in binary_funcs:
  1901. assert_raises(TypeError, f, a, b)
  1902. assert_raises(TypeError, f, c, a)
  1903. @pytest.mark.parametrize("ufunc",
  1904. [np.logical_and, np.logical_or]) # logical_xor object loop is bad
  1905. @pytest.mark.parametrize("signature",
  1906. [(None, None, object), (object, None, None),
  1907. (None, object, None)])
  1908. def test_logical_ufuncs_object_signatures(self, ufunc, signature):
  1909. a = np.array([True, None, False], dtype=object)
  1910. res = ufunc(a, a, signature=signature)
  1911. assert res.dtype == object
  1912. @pytest.mark.parametrize("ufunc",
  1913. [np.logical_and, np.logical_or, np.logical_xor])
  1914. @pytest.mark.parametrize("signature",
  1915. [(bool, None, object), (object, None, bool),
  1916. (None, object, bool)])
  1917. def test_logical_ufuncs_mixed_object_signatures(self, ufunc, signature):
  1918. # Most mixed signatures fail (except those with bool out, e.g. `OO->?`)
  1919. a = np.array([True, None, False])
  1920. with pytest.raises(TypeError):
  1921. ufunc(a, a, signature=signature)
  1922. @pytest.mark.parametrize("ufunc",
  1923. [np.logical_and, np.logical_or, np.logical_xor])
  1924. def test_logical_ufuncs_support_anything(self, ufunc):
  1925. # The logical ufuncs support even input that can't be promoted:
  1926. a = np.array(b'1', dtype="V3")
  1927. c = np.array([1., 2.])
  1928. assert_array_equal(ufunc(a, c), ufunc([True, True], True))
  1929. assert ufunc.reduce(a) == True
  1930. # check that the output has no effect:
  1931. out = np.zeros(2, dtype=np.int32)
  1932. expected = ufunc([True, True], True).astype(out.dtype)
  1933. assert_array_equal(ufunc(a, c, out=out), expected)
  1934. out = np.zeros((), dtype=np.int32)
  1935. assert ufunc.reduce(a, out=out) == True
  1936. # Last check, test reduction when out and a match (the complexity here
  1937. # is that the "i,i->?" may seem right, but should not match.
  1938. a = np.array([3], dtype="i")
  1939. out = np.zeros((), dtype=a.dtype)
  1940. assert ufunc.reduce(a, out=out) == 1
  1941. @pytest.mark.parametrize("ufunc",
  1942. [np.logical_and, np.logical_or, np.logical_xor])
  1943. def test_logical_ufuncs_reject_string(self, ufunc):
  1944. """
  1945. Logical ufuncs are normally well defined by working with the boolean
  1946. equivalent, i.e. casting all inputs to bools should work.
  1947. However, casting strings to bools is *currently* weird, because it
  1948. actually uses `bool(int(str))`. Thus we explicitly reject strings.
  1949. This test should succeed (and can probably just be removed) as soon as
  1950. string to bool casts are well defined in NumPy.
  1951. """
  1952. with pytest.raises(TypeError, match="contain a loop with signature"):
  1953. ufunc(["1"], ["3"])
  1954. with pytest.raises(TypeError, match="contain a loop with signature"):
  1955. ufunc.reduce(["1", "2", "0"])
  1956. @pytest.mark.parametrize("ufunc",
  1957. [np.logical_and, np.logical_or, np.logical_xor])
  1958. def test_logical_ufuncs_out_cast_check(self, ufunc):
  1959. a = np.array('1')
  1960. c = np.array([1., 2.])
  1961. out = a.copy()
  1962. with pytest.raises(TypeError):
  1963. # It would be safe, but not equiv casting:
  1964. ufunc(a, c, out=out, casting="equiv")
  1965. def test_reducelike_byteorder_resolution(self):
  1966. # See gh-20699, byte-order changes need some extra care in the type
  1967. # resolution to make the following succeed:
  1968. arr_be = np.arange(10, dtype=">i8")
  1969. arr_le = np.arange(10, dtype="<i8")
  1970. assert np.add.reduce(arr_be) == np.add.reduce(arr_le)
  1971. assert_array_equal(np.add.accumulate(arr_be), np.add.accumulate(arr_le))
  1972. assert_array_equal(
  1973. np.add.reduceat(arr_be, [1]), np.add.reduceat(arr_le, [1]))
  1974. def test_reducelike_out_promotes(self):
  1975. # Check that the out argument to reductions is considered for
  1976. # promotion. See also gh-20455.
  1977. # Note that these paths could prefer `initial=` in the future and
  1978. # do not up-cast to the default integer for add and prod
  1979. arr = np.ones(1000, dtype=np.uint8)
  1980. out = np.zeros((), dtype=np.uint16)
  1981. assert np.add.reduce(arr, out=out) == 1000
  1982. arr[:10] = 2
  1983. assert np.multiply.reduce(arr, out=out) == 2**10
  1984. # For legacy dtypes, the signature currently has to be forced if `out=`
  1985. # is passed. The two paths below should differ, without `dtype=` the
  1986. # expected result should be: `np.prod(arr.astype("f8")).astype("f4")`!
  1987. arr = np.full(5, 2**25-1, dtype=np.int64)
  1988. # float32 and int64 promote to float64:
  1989. res = np.zeros((), dtype=np.float32)
  1990. # If `dtype=` is passed, the calculation is forced to float32:
  1991. single_res = np.zeros((), dtype=np.float32)
  1992. np.multiply.reduce(arr, out=single_res, dtype=np.float32)
  1993. assert single_res != res
  1994. def test_reducelike_output_needs_identical_cast(self):
  1995. # Checks the case where the we have a simple byte-swap works, maily
  1996. # tests that this is not rejected directly.
  1997. # (interesting because we require descriptor identity in reducelikes).
  1998. arr = np.ones(20, dtype="f8")
  1999. out = np.empty((), dtype=arr.dtype.newbyteorder())
  2000. expected = np.add.reduce(arr)
  2001. np.add.reduce(arr, out=out)
  2002. assert_array_equal(expected, out)
  2003. # Check reduceat:
  2004. out = np.empty(2, dtype=arr.dtype.newbyteorder())
  2005. expected = np.add.reduceat(arr, [0, 1])
  2006. np.add.reduceat(arr, [0, 1], out=out)
  2007. assert_array_equal(expected, out)
  2008. # And accumulate:
  2009. out = np.empty(arr.shape, dtype=arr.dtype.newbyteorder())
  2010. expected = np.add.accumulate(arr)
  2011. np.add.accumulate(arr, out=out)
  2012. assert_array_equal(expected, out)
  2013. def test_reduce_noncontig_output(self):
  2014. # Check that reduction deals with non-contiguous output arrays
  2015. # appropriately.
  2016. #
  2017. # gh-8036
  2018. x = np.arange(7*13*8, dtype=np.int16).reshape(7, 13, 8)
  2019. x = x[4:6,1:11:6,1:5].transpose(1, 2, 0)
  2020. y_base = np.arange(4*4, dtype=np.int16).reshape(4, 4)
  2021. y = y_base[::2,:]
  2022. y_base_copy = y_base.copy()
  2023. r0 = np.add.reduce(x, out=y.copy(), axis=2)
  2024. r1 = np.add.reduce(x, out=y, axis=2)
  2025. # The results should match, and y_base shouldn't get clobbered
  2026. assert_equal(r0, r1)
  2027. assert_equal(y_base[1,:], y_base_copy[1,:])
  2028. assert_equal(y_base[3,:], y_base_copy[3,:])
  2029. @pytest.mark.parametrize("with_cast", [True, False])
  2030. def test_reduceat_and_accumulate_out_shape_mismatch(self, with_cast):
  2031. # Should raise an error mentioning "shape" or "size"
  2032. arr = np.arange(5)
  2033. out = np.arange(3) # definitely wrong shape
  2034. if with_cast:
  2035. # If a cast is necessary on the output, we can be sure to use
  2036. # the generic NpyIter (non-fast) path.
  2037. out = out.astype(np.float64)
  2038. with pytest.raises(ValueError, match="(shape|size)"):
  2039. np.add.reduceat(arr, [0, 3], out=out)
  2040. with pytest.raises(ValueError, match="(shape|size)"):
  2041. np.add.accumulate(arr, out=out)
  2042. @pytest.mark.parametrize('out_shape',
  2043. [(), (1,), (3,), (1, 1), (1, 3), (4, 3)])
  2044. @pytest.mark.parametrize('keepdims', [True, False])
  2045. @pytest.mark.parametrize('f_reduce', [np.add.reduce, np.minimum.reduce])
  2046. def test_reduce_wrong_dimension_output(self, f_reduce, keepdims, out_shape):
  2047. # Test that we're not incorrectly broadcasting dimensions.
  2048. # See gh-15144 (failed for np.add.reduce previously).
  2049. a = np.arange(12.).reshape(4, 3)
  2050. out = np.empty(out_shape, a.dtype)
  2051. correct_out = f_reduce(a, axis=0, keepdims=keepdims)
  2052. if out_shape != correct_out.shape:
  2053. with assert_raises(ValueError):
  2054. f_reduce(a, axis=0, out=out, keepdims=keepdims)
  2055. else:
  2056. check = f_reduce(a, axis=0, out=out, keepdims=keepdims)
  2057. assert_(check is out)
  2058. assert_array_equal(check, correct_out)
  2059. def test_reduce_output_does_not_broadcast_input(self):
  2060. # Test that the output shape cannot broadcast an input dimension
  2061. # (it never can add dimensions, but it might expand an existing one)
  2062. a = np.ones((1, 10))
  2063. out_correct = (np.empty((1, 1)))
  2064. out_incorrect = np.empty((3, 1))
  2065. np.add.reduce(a, axis=-1, out=out_correct, keepdims=True)
  2066. np.add.reduce(a, axis=-1, out=out_correct[:, 0], keepdims=False)
  2067. with assert_raises(ValueError):
  2068. np.add.reduce(a, axis=-1, out=out_incorrect, keepdims=True)
  2069. with assert_raises(ValueError):
  2070. np.add.reduce(a, axis=-1, out=out_incorrect[:, 0], keepdims=False)
  2071. def test_reduce_output_subclass_ok(self):
  2072. class MyArr(np.ndarray):
  2073. pass
  2074. out = np.empty(())
  2075. np.add.reduce(np.ones(5), out=out) # no subclass, all fine
  2076. out = out.view(MyArr)
  2077. assert np.add.reduce(np.ones(5), out=out) is out
  2078. assert type(np.add.reduce(out)) is MyArr
  2079. def test_no_doc_string(self):
  2080. # gh-9337
  2081. assert_('\n' not in umt.inner1d_no_doc.__doc__)
  2082. def test_invalid_args(self):
  2083. # gh-7961
  2084. exc = pytest.raises(TypeError, np.sqrt, None)
  2085. # minimally check the exception text
  2086. assert exc.match('loop of ufunc does not support')
  2087. @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
  2088. def test_nat_is_not_finite(self, nat):
  2089. try:
  2090. assert not np.isfinite(nat)
  2091. except TypeError:
  2092. pass # ok, just not implemented
  2093. @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
  2094. def test_nat_is_nan(self, nat):
  2095. try:
  2096. assert np.isnan(nat)
  2097. except TypeError:
  2098. pass # ok, just not implemented
  2099. @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
  2100. def test_nat_is_not_inf(self, nat):
  2101. try:
  2102. assert not np.isinf(nat)
  2103. except TypeError:
  2104. pass # ok, just not implemented
  2105. @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np)
  2106. if isinstance(getattr(np, x), np.ufunc)])
  2107. def test_ufunc_types(ufunc):
  2108. '''
  2109. Check all ufuncs that the correct type is returned. Avoid
  2110. object and boolean types since many operations are not defined for
  2111. for them.
  2112. Choose the shape so even dot and matmul will succeed
  2113. '''
  2114. for typ in ufunc.types:
  2115. # types is a list of strings like ii->i
  2116. if 'O' in typ or '?' in typ:
  2117. continue
  2118. inp, out = typ.split('->')
  2119. args = [np.ones((3, 3), t) for t in inp]
  2120. with warnings.catch_warnings(record=True):
  2121. warnings.filterwarnings("always")
  2122. res = ufunc(*args)
  2123. if isinstance(res, tuple):
  2124. outs = tuple(out)
  2125. assert len(res) == len(outs)
  2126. for r, t in zip(res, outs):
  2127. assert r.dtype == np.dtype(t)
  2128. else:
  2129. assert res.dtype == np.dtype(out)
  2130. @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np)
  2131. if isinstance(getattr(np, x), np.ufunc)])
  2132. @np._no_nep50_warning()
  2133. def test_ufunc_noncontiguous(ufunc):
  2134. '''
  2135. Check that contiguous and non-contiguous calls to ufuncs
  2136. have the same results for values in range(9)
  2137. '''
  2138. for typ in ufunc.types:
  2139. # types is a list of strings like ii->i
  2140. if any(set('O?mM') & set(typ)):
  2141. # bool, object, datetime are too irregular for this simple test
  2142. continue
  2143. inp, out = typ.split('->')
  2144. args_c = [np.empty(6, t) for t in inp]
  2145. args_n = [np.empty(18, t)[::3] for t in inp]
  2146. for a in args_c:
  2147. a.flat = range(1,7)
  2148. for a in args_n:
  2149. a.flat = range(1,7)
  2150. with warnings.catch_warnings(record=True):
  2151. warnings.filterwarnings("always")
  2152. res_c = ufunc(*args_c)
  2153. res_n = ufunc(*args_n)
  2154. if len(out) == 1:
  2155. res_c = (res_c,)
  2156. res_n = (res_n,)
  2157. for c_ar, n_ar in zip(res_c, res_n):
  2158. dt = c_ar.dtype
  2159. if np.issubdtype(dt, np.floating):
  2160. # for floating point results allow a small fuss in comparisons
  2161. # since different algorithms (libm vs. intrinsics) can be used
  2162. # for different input strides
  2163. res_eps = np.finfo(dt).eps
  2164. tol = 2*res_eps
  2165. assert_allclose(res_c, res_n, atol=tol, rtol=tol)
  2166. else:
  2167. assert_equal(c_ar, n_ar)
  2168. @pytest.mark.parametrize('ufunc', [np.sign, np.equal])
  2169. def test_ufunc_warn_with_nan(ufunc):
  2170. # issue gh-15127
  2171. # test that calling certain ufuncs with a non-standard `nan` value does not
  2172. # emit a warning
  2173. # `b` holds a 64 bit signaling nan: the most significant bit of the
  2174. # significand is zero.
  2175. b = np.array([0x7ff0000000000001], 'i8').view('f8')
  2176. assert np.isnan(b)
  2177. if ufunc.nin == 1:
  2178. ufunc(b)
  2179. elif ufunc.nin == 2:
  2180. ufunc(b, b.copy())
  2181. else:
  2182. raise ValueError('ufunc with more than 2 inputs')
  2183. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2184. def test_ufunc_out_casterrors():
  2185. # Tests that casting errors are correctly reported and buffers are
  2186. # cleared.
  2187. # The following array can be added to itself as an object array, but
  2188. # the result cannot be cast to an integer output:
  2189. value = 123 # relies on python cache (leak-check will still find it)
  2190. arr = np.array([value] * int(np.BUFSIZE * 1.5) +
  2191. ["string"] +
  2192. [value] * int(1.5 * np.BUFSIZE), dtype=object)
  2193. out = np.ones(len(arr), dtype=np.intp)
  2194. count = sys.getrefcount(value)
  2195. with pytest.raises(ValueError):
  2196. # Output casting failure:
  2197. np.add(arr, arr, out=out, casting="unsafe")
  2198. assert count == sys.getrefcount(value)
  2199. # output is unchanged after the error, this shows that the iteration
  2200. # was aborted (this is not necessarily defined behaviour)
  2201. assert out[-1] == 1
  2202. with pytest.raises(ValueError):
  2203. # Input casting failure:
  2204. np.add(arr, arr, out=out, dtype=np.intp, casting="unsafe")
  2205. assert count == sys.getrefcount(value)
  2206. # output is unchanged after the error, this shows that the iteration
  2207. # was aborted (this is not necessarily defined behaviour)
  2208. assert out[-1] == 1
  2209. @pytest.mark.parametrize("bad_offset", [0, int(np.BUFSIZE * 1.5)])
  2210. def test_ufunc_input_casterrors(bad_offset):
  2211. value = 123
  2212. arr = np.array([value] * bad_offset +
  2213. ["string"] +
  2214. [value] * int(1.5 * np.BUFSIZE), dtype=object)
  2215. with pytest.raises(ValueError):
  2216. # Force cast inputs, but the buffered cast of `arr` to intp fails:
  2217. np.add(arr, arr, dtype=np.intp, casting="unsafe")
  2218. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  2219. @pytest.mark.parametrize("bad_offset", [0, int(np.BUFSIZE * 1.5)])
  2220. def test_ufunc_input_floatingpoint_error(bad_offset):
  2221. value = 123
  2222. arr = np.array([value] * bad_offset +
  2223. [np.nan] +
  2224. [value] * int(1.5 * np.BUFSIZE))
  2225. with np.errstate(invalid="raise"), pytest.raises(FloatingPointError):
  2226. # Force cast inputs, but the buffered cast of `arr` to intp fails:
  2227. np.add(arr, arr, dtype=np.intp, casting="unsafe")
  2228. def test_trivial_loop_invalid_cast():
  2229. # This tests the fast-path "invalid cast", see gh-19904.
  2230. with pytest.raises(TypeError,
  2231. match="cast ufunc 'add' input 0"):
  2232. # the void dtype definitely cannot cast to double:
  2233. np.add(np.array(1, "i,i"), 3, signature="dd->d")
  2234. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2235. @pytest.mark.parametrize("offset",
  2236. [0, np.BUFSIZE//2, int(1.5*np.BUFSIZE)])
  2237. def test_reduce_casterrors(offset):
  2238. # Test reporting of casting errors in reductions, we test various
  2239. # offsets to where the casting error will occur, since these may occur
  2240. # at different places during the reduction procedure. For example
  2241. # the first item may be special.
  2242. value = 123 # relies on python cache (leak-check will still find it)
  2243. arr = np.array([value] * offset +
  2244. ["string"] +
  2245. [value] * int(1.5 * np.BUFSIZE), dtype=object)
  2246. out = np.array(-1, dtype=np.intp)
  2247. count = sys.getrefcount(value)
  2248. with pytest.raises(ValueError, match="invalid literal"):
  2249. # This is an unsafe cast, but we currently always allow that.
  2250. # Note that the double loop is picked, but the cast fails.
  2251. np.add.reduce(arr, dtype=np.intp, out=out)
  2252. assert count == sys.getrefcount(value)
  2253. # If an error occurred during casting, the operation is done at most until
  2254. # the error occurs (the result of which would be `value * offset`) and -1
  2255. # if the error happened immediately.
  2256. # This does not define behaviour, the output is invalid and thus undefined
  2257. assert out[()] < value * offset
  2258. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  2259. @pytest.mark.parametrize("method",
  2260. [np.add.accumulate, np.add.reduce,
  2261. pytest.param(lambda x: np.add.reduceat(x, [0]), id="reduceat"),
  2262. pytest.param(lambda x: np.log.at(x, [2]), id="at")])
  2263. def test_ufunc_methods_floaterrors(method):
  2264. # adding inf and -inf (or log(-inf) creates an invalid float and warns
  2265. arr = np.array([np.inf, 0, -np.inf])
  2266. with np.errstate(all="warn"):
  2267. with pytest.warns(RuntimeWarning, match="invalid value"):
  2268. method(arr)
  2269. arr = np.array([np.inf, 0, -np.inf])
  2270. with np.errstate(all="raise"):
  2271. with pytest.raises(FloatingPointError):
  2272. method(arr)
  2273. def _check_neg_zero(value):
  2274. if value != 0.0:
  2275. return False
  2276. if not np.signbit(value.real):
  2277. return False
  2278. if value.dtype.kind == "c":
  2279. return np.signbit(value.imag)
  2280. return True
  2281. @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
  2282. def test_addition_negative_zero(dtype):
  2283. dtype = np.dtype(dtype)
  2284. if dtype.kind == "c":
  2285. neg_zero = dtype.type(complex(-0.0, -0.0))
  2286. else:
  2287. neg_zero = dtype.type(-0.0)
  2288. arr = np.array(neg_zero)
  2289. arr2 = np.array(neg_zero)
  2290. assert _check_neg_zero(arr + arr2)
  2291. # In-place ops may end up on a different path (reduce path) see gh-21211
  2292. arr += arr2
  2293. assert _check_neg_zero(arr)
  2294. @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
  2295. @pytest.mark.parametrize("use_initial", [True, False])
  2296. def test_addition_reduce_negative_zero(dtype, use_initial):
  2297. dtype = np.dtype(dtype)
  2298. if dtype.kind == "c":
  2299. neg_zero = dtype.type(complex(-0.0, -0.0))
  2300. else:
  2301. neg_zero = dtype.type(-0.0)
  2302. kwargs = {}
  2303. if use_initial:
  2304. kwargs["initial"] = neg_zero
  2305. else:
  2306. pytest.xfail("-0. propagation in sum currently requires initial")
  2307. # Test various length, in case SIMD paths or chunking play a role.
  2308. # 150 extends beyond the pairwise blocksize; probably not important.
  2309. for i in range(0, 150):
  2310. arr = np.array([neg_zero] * i, dtype=dtype)
  2311. res = np.sum(arr, **kwargs)
  2312. if i > 0 or use_initial:
  2313. assert _check_neg_zero(res)
  2314. else:
  2315. # `sum([])` should probably be 0.0 and not -0.0 like `sum([-0.0])`
  2316. assert not np.signbit(res.real)
  2317. assert not np.signbit(res.imag)
  2318. class TestLowlevelAPIAccess:
  2319. def test_resolve_dtypes_basic(self):
  2320. # Basic test for dtype resolution:
  2321. i4 = np.dtype("i4")
  2322. f4 = np.dtype("f4")
  2323. f8 = np.dtype("f8")
  2324. r = np.add.resolve_dtypes((i4, f4, None))
  2325. assert r == (f8, f8, f8)
  2326. # Signature uses the same logic to parse as ufunc (less strict)
  2327. # the following is "same-kind" casting so works:
  2328. r = np.add.resolve_dtypes((
  2329. i4, i4, None), signature=(None, None, "f4"))
  2330. assert r == (f4, f4, f4)
  2331. # Check NEP 50 "weak" promotion also:
  2332. r = np.add.resolve_dtypes((f4, int, None))
  2333. assert r == (f4, f4, f4)
  2334. with pytest.raises(TypeError):
  2335. np.add.resolve_dtypes((i4, f4, None), casting="no")
  2336. def test_weird_dtypes(self):
  2337. S0 = np.dtype("S0")
  2338. # S0 is often converted by NumPy to S1, but not here:
  2339. r = np.equal.resolve_dtypes((S0, S0, None))
  2340. assert r == (S0, S0, np.dtype(bool))
  2341. # Subarray dtypes are weird and only really exist nested, they need
  2342. # the shift to full NEP 50 to be implemented nicely:
  2343. dts = np.dtype("10i")
  2344. with pytest.raises(NotImplementedError):
  2345. np.equal.resolve_dtypes((dts, dts, None))
  2346. def test_resolve_dtypes_reduction(self):
  2347. i4 = np.dtype("i4")
  2348. with pytest.raises(NotImplementedError):
  2349. np.add.resolve_dtypes((i4, i4, i4), reduction=True)
  2350. @pytest.mark.parametrize("dtypes", [
  2351. (np.dtype("i"), np.dtype("i")),
  2352. (None, np.dtype("i"), np.dtype("f")),
  2353. (np.dtype("i"), None, np.dtype("f")),
  2354. ("i4", "i4", None)])
  2355. def test_resolve_dtypes_errors(self, dtypes):
  2356. with pytest.raises(TypeError):
  2357. np.add.resolve_dtypes(dtypes)
  2358. def test_resolve_dtypes_reduction(self):
  2359. i2 = np.dtype("i2")
  2360. long_ = np.dtype("long")
  2361. # Check special addition resolution:
  2362. res = np.add.resolve_dtypes((None, i2, None), reduction=True)
  2363. assert res == (long_, long_, long_)
  2364. def test_resolve_dtypes_reduction_errors(self):
  2365. i2 = np.dtype("i2")
  2366. with pytest.raises(TypeError):
  2367. np.add.resolve_dtypes((None, i2, i2))
  2368. with pytest.raises(TypeError):
  2369. np.add.signature((None, None, "i4"))
  2370. @pytest.mark.skipif(not hasattr(ct, "pythonapi"),
  2371. reason="`ctypes.pythonapi` required for capsule unpacking.")
  2372. def test_loop_access(self):
  2373. # This is a basic test for the full strided loop access
  2374. data_t = ct.ARRAY(ct.c_char_p, 2)
  2375. dim_t = ct.ARRAY(ct.c_ssize_t, 1)
  2376. strides_t = ct.ARRAY(ct.c_ssize_t, 2)
  2377. strided_loop_t = ct.CFUNCTYPE(
  2378. ct.c_int, ct.c_void_p, data_t, dim_t, strides_t, ct.c_void_p)
  2379. class call_info_t(ct.Structure):
  2380. _fields_ = [
  2381. ("strided_loop", strided_loop_t),
  2382. ("context", ct.c_void_p),
  2383. ("auxdata", ct.c_void_p),
  2384. ("requires_pyapi", ct.c_byte),
  2385. ("no_floatingpoint_errors", ct.c_byte),
  2386. ]
  2387. i4 = np.dtype("i4")
  2388. dt, call_info_obj = np.negative._resolve_dtypes_and_context((i4, i4))
  2389. assert dt == (i4, i4) # can be used without casting
  2390. # Fill in the rest of the information:
  2391. np.negative._get_strided_loop(call_info_obj)
  2392. ct.pythonapi.PyCapsule_GetPointer.restype = ct.c_void_p
  2393. call_info = ct.pythonapi.PyCapsule_GetPointer(
  2394. ct.py_object(call_info_obj),
  2395. ct.c_char_p(b"numpy_1.24_ufunc_call_info"))
  2396. call_info = ct.cast(call_info, ct.POINTER(call_info_t)).contents
  2397. arr = np.arange(10, dtype=i4)
  2398. call_info.strided_loop(
  2399. call_info.context,
  2400. data_t(arr.ctypes.data, arr.ctypes.data),
  2401. arr.ctypes.shape, # is a C-array with 10 here
  2402. strides_t(arr.ctypes.strides[0], arr.ctypes.strides[0]),
  2403. call_info.auxdata)
  2404. # We just directly called the negative inner-loop in-place:
  2405. assert_array_equal(arr, -np.arange(10, dtype=i4))
  2406. @pytest.mark.parametrize("strides", [1, (1, 2, 3), (1, "2")])
  2407. def test__get_strided_loop_errors_bad_strides(self, strides):
  2408. i4 = np.dtype("i4")
  2409. dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
  2410. with pytest.raises(TypeError, match="fixed_strides.*tuple.*or None"):
  2411. np.negative._get_strided_loop(call_info, fixed_strides=strides)
  2412. def test__get_strided_loop_errors_bad_call_info(self):
  2413. i4 = np.dtype("i4")
  2414. dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
  2415. with pytest.raises(ValueError, match="PyCapsule"):
  2416. np.negative._get_strided_loop("not the capsule!")
  2417. with pytest.raises(TypeError, match=".*incompatible context"):
  2418. np.add._get_strided_loop(call_info)
  2419. np.negative._get_strided_loop(call_info)
  2420. with pytest.raises(TypeError):
  2421. # cannot call it a second time:
  2422. np.negative._get_strided_loop(call_info)
  2423. def test_long_arrays(self):
  2424. t = np.zeros((1029, 917), dtype=np.single)
  2425. t[0][0] = 1
  2426. t[28][414] = 1
  2427. tc = np.cos(t)
  2428. assert_equal(tc[0][0], tc[28][414])