numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of numpy might be problematic. Click here for more details.

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,4928 @@
1
+ import fnmatch
2
+ import itertools
3
+ import operator
4
+ import platform
5
+ import sys
6
+ import warnings
7
+ from collections import namedtuple
8
+ from fractions import Fraction
9
+ from functools import reduce
10
+
11
+ import pytest
12
+
13
+ import numpy as np
14
+ import numpy._core.umath as ncu
15
+ from numpy._core import _umath_tests as ncu_tests
16
+ from numpy._core import sctypes
17
+ from numpy.testing import (
18
+ HAS_REFCOUNT,
19
+ IS_MUSL,
20
+ IS_PYPY,
21
+ IS_WASM,
22
+ _gen_alignment_data,
23
+ assert_,
24
+ assert_allclose,
25
+ assert_almost_equal,
26
+ assert_array_almost_equal,
27
+ assert_array_almost_equal_nulp,
28
+ assert_array_equal,
29
+ assert_array_max_ulp,
30
+ assert_equal,
31
+ assert_no_warnings,
32
+ assert_raises,
33
+ assert_raises_regex,
34
+ suppress_warnings,
35
+ )
36
+ from numpy.testing._private.utils import _glibc_older_than
37
+
38
+ UFUNCS = [obj for obj in np._core.umath.__dict__.values()
39
+ if isinstance(obj, np.ufunc)]
40
+
41
+ UFUNCS_UNARY = [
42
+ uf for uf in UFUNCS if uf.nin == 1
43
+ ]
44
+ UFUNCS_UNARY_FP = [
45
+ uf for uf in UFUNCS_UNARY if 'f->f' in uf.types
46
+ ]
47
+
48
+ UFUNCS_BINARY = [
49
+ uf for uf in UFUNCS if uf.nin == 2
50
+ ]
51
+ UFUNCS_BINARY_ACC = [
52
+ uf for uf in UFUNCS_BINARY if hasattr(uf, "accumulate") and uf.nout == 1
53
+ ]
54
+
55
+ def interesting_binop_operands(val1, val2, dtype):
56
+ """
57
+ Helper to create "interesting" operands to cover common code paths:
58
+ * scalar inputs
59
+ * only first "values" is an array (e.g. scalar division fast-paths)
60
+ * Longer array (SIMD) placing the value of interest at different positions
61
+ * Oddly strided arrays which may not be SIMD compatible
62
+
63
+ It does not attempt to cover unaligned access or mixed dtypes.
64
+ These are normally handled by the casting/buffering machinery.
65
+
66
+ This is not a fixture (currently), since I believe a fixture normally
67
+ only yields once?
68
+ """
69
+ fill_value = 1 # could be a parameter, but maybe not an optional one?
70
+
71
+ arr1 = np.full(10003, dtype=dtype, fill_value=fill_value)
72
+ arr2 = np.full(10003, dtype=dtype, fill_value=fill_value)
73
+
74
+ arr1[0] = val1
75
+ arr2[0] = val2
76
+
77
+ extractor = lambda res: res
78
+ yield arr1[0], arr2[0], extractor, "scalars"
79
+
80
+ extractor = lambda res: res
81
+ yield arr1[0, ...], arr2[0, ...], extractor, "scalar-arrays"
82
+
83
+ # reset array values to fill_value:
84
+ arr1[0] = fill_value
85
+ arr2[0] = fill_value
86
+
87
+ for pos in [0, 1, 2, 3, 4, 5, -1, -2, -3, -4]:
88
+ arr1[pos] = val1
89
+ arr2[pos] = val2
90
+
91
+ extractor = lambda res: res[pos]
92
+ yield arr1, arr2, extractor, f"off-{pos}"
93
+ yield arr1, arr2[pos], extractor, f"off-{pos}-with-scalar"
94
+
95
+ arr1[pos] = fill_value
96
+ arr2[pos] = fill_value
97
+
98
+ for stride in [-1, 113]:
99
+ op1 = arr1[::stride]
100
+ op2 = arr2[::stride]
101
+ op1[10] = val1
102
+ op2[10] = val2
103
+
104
+ extractor = lambda res: res[10]
105
+ yield op1, op2, extractor, f"stride-{stride}"
106
+
107
+ op1[10] = fill_value
108
+ op2[10] = fill_value
109
+
110
+
111
+ def on_powerpc():
112
+ """ True if we are running on a Power PC platform."""
113
+ return platform.processor() == 'powerpc' or \
114
+ platform.machine().startswith('ppc')
115
+
116
+
117
+ def bad_arcsinh():
118
+ """The blocklisted trig functions are not accurate on aarch64/PPC for
119
+ complex256. Rather than dig through the actual problem skip the
120
+ test. This should be fixed when we can move past glibc2.17
121
+ which is the version in manylinux2014
122
+ """
123
+ if platform.machine() == 'aarch64':
124
+ x = 1.78e-10
125
+ elif on_powerpc():
126
+ x = 2.16e-10
127
+ else:
128
+ return False
129
+ v1 = np.arcsinh(np.float128(x))
130
+ v2 = np.arcsinh(np.complex256(x)).real
131
+ # The eps for float128 is 1-e33, so this is way bigger
132
+ return abs((v1 / v2) - 1.0) > 1e-23
133
+
134
+
135
+ class _FilterInvalids:
136
+ def setup_method(self):
137
+ self.olderr = np.seterr(invalid='ignore')
138
+
139
+ def teardown_method(self):
140
+ np.seterr(**self.olderr)
141
+
142
+
143
+ class TestConstants:
144
+ def test_pi(self):
145
+ assert_allclose(ncu.pi, 3.141592653589793, 1e-15)
146
+
147
+ def test_e(self):
148
+ assert_allclose(ncu.e, 2.718281828459045, 1e-15)
149
+
150
+ def test_euler_gamma(self):
151
+ assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15)
152
+
153
+
154
+ class TestOut:
155
+ def test_out_subok(self):
156
+ for subok in (True, False):
157
+ a = np.array(0.5)
158
+ o = np.empty(())
159
+
160
+ r = np.add(a, 2, o, subok=subok)
161
+ assert_(r is o)
162
+ r = np.add(a, 2, out=o, subok=subok)
163
+ assert_(r is o)
164
+ r = np.add(a, 2, out=(o,), subok=subok)
165
+ assert_(r is o)
166
+
167
+ d = np.array(5.7)
168
+ o1 = np.empty(())
169
+ o2 = np.empty((), dtype=np.int32)
170
+
171
+ r1, r2 = np.frexp(d, o1, None, subok=subok)
172
+ assert_(r1 is o1)
173
+ r1, r2 = np.frexp(d, None, o2, subok=subok)
174
+ assert_(r2 is o2)
175
+ r1, r2 = np.frexp(d, o1, o2, subok=subok)
176
+ assert_(r1 is o1)
177
+ assert_(r2 is o2)
178
+
179
+ r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
180
+ assert_(r1 is o1)
181
+ r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
182
+ assert_(r2 is o2)
183
+ r1, r2 = np.frexp(d, out=(o1, o2), subok=subok)
184
+ assert_(r1 is o1)
185
+ assert_(r2 is o2)
186
+
187
+ with assert_raises(TypeError):
188
+ # Out argument must be tuple, since there are multiple outputs.
189
+ r1, r2 = np.frexp(d, out=o1, subok=subok)
190
+
191
+ assert_raises(TypeError, np.add, a, 2, o, o, subok=subok)
192
+ assert_raises(TypeError, np.add, a, 2, o, out=o, subok=subok)
193
+ assert_raises(TypeError, np.add, a, 2, None, out=o, subok=subok)
194
+ assert_raises(ValueError, np.add, a, 2, out=(o, o), subok=subok)
195
+ assert_raises(ValueError, np.add, a, 2, out=(), subok=subok)
196
+ assert_raises(TypeError, np.add, a, 2, [], subok=subok)
197
+ assert_raises(TypeError, np.add, a, 2, out=[], subok=subok)
198
+ assert_raises(TypeError, np.add, a, 2, out=([],), subok=subok)
199
+ o.flags.writeable = False
200
+ assert_raises(ValueError, np.add, a, 2, o, subok=subok)
201
+ assert_raises(ValueError, np.add, a, 2, out=o, subok=subok)
202
+ assert_raises(ValueError, np.add, a, 2, out=(o,), subok=subok)
203
+
204
+ def test_out_wrap_subok(self):
205
+ class ArrayWrap(np.ndarray):
206
+ __array_priority__ = 10
207
+
208
+ def __new__(cls, arr):
209
+ return np.asarray(arr).view(cls).copy()
210
+
211
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
212
+ return arr.view(type(self))
213
+
214
+ for subok in (True, False):
215
+ a = ArrayWrap([0.5])
216
+
217
+ r = np.add(a, 2, subok=subok)
218
+ if subok:
219
+ assert_(isinstance(r, ArrayWrap))
220
+ else:
221
+ assert_(type(r) == np.ndarray)
222
+
223
+ r = np.add(a, 2, None, subok=subok)
224
+ if subok:
225
+ assert_(isinstance(r, ArrayWrap))
226
+ else:
227
+ assert_(type(r) == np.ndarray)
228
+
229
+ r = np.add(a, 2, out=None, subok=subok)
230
+ if subok:
231
+ assert_(isinstance(r, ArrayWrap))
232
+ else:
233
+ assert_(type(r) == np.ndarray)
234
+
235
+ r = np.add(a, 2, out=(None,), subok=subok)
236
+ if subok:
237
+ assert_(isinstance(r, ArrayWrap))
238
+ else:
239
+ assert_(type(r) == np.ndarray)
240
+
241
+ d = ArrayWrap([5.7])
242
+ o1 = np.empty((1,))
243
+ o2 = np.empty((1,), dtype=np.int32)
244
+
245
+ r1, r2 = np.frexp(d, o1, subok=subok)
246
+ if subok:
247
+ assert_(isinstance(r2, ArrayWrap))
248
+ else:
249
+ assert_(type(r2) == np.ndarray)
250
+
251
+ r1, r2 = np.frexp(d, o1, None, subok=subok)
252
+ if subok:
253
+ assert_(isinstance(r2, ArrayWrap))
254
+ else:
255
+ assert_(type(r2) == np.ndarray)
256
+
257
+ r1, r2 = np.frexp(d, None, o2, subok=subok)
258
+ if subok:
259
+ assert_(isinstance(r1, ArrayWrap))
260
+ else:
261
+ assert_(type(r1) == np.ndarray)
262
+
263
+ r1, r2 = np.frexp(d, out=(o1, None), subok=subok)
264
+ if subok:
265
+ assert_(isinstance(r2, ArrayWrap))
266
+ else:
267
+ assert_(type(r2) == np.ndarray)
268
+
269
+ r1, r2 = np.frexp(d, out=(None, o2), subok=subok)
270
+ if subok:
271
+ assert_(isinstance(r1, ArrayWrap))
272
+ else:
273
+ assert_(type(r1) == np.ndarray)
274
+
275
+ with assert_raises(TypeError):
276
+ # Out argument must be tuple, since there are multiple outputs.
277
+ r1, r2 = np.frexp(d, out=o1, subok=subok)
278
+
279
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
280
+ def test_out_wrap_no_leak(self):
281
+ # Regression test for gh-26545
282
+ class ArrSubclass(np.ndarray):
283
+ pass
284
+
285
+ arr = np.arange(10).view(ArrSubclass)
286
+ orig_refcount = sys.getrefcount(arr)
287
+ arr *= 1
288
+ assert sys.getrefcount(arr) == orig_refcount
289
+
290
+
291
+ class TestComparisons:
292
+ import operator
293
+
294
+ @pytest.mark.parametrize('dtype', sctypes['uint'] + sctypes['int'] +
295
+ sctypes['float'] + [np.bool])
296
+ @pytest.mark.parametrize('py_comp,np_comp', [
297
+ (operator.lt, np.less),
298
+ (operator.le, np.less_equal),
299
+ (operator.gt, np.greater),
300
+ (operator.ge, np.greater_equal),
301
+ (operator.eq, np.equal),
302
+ (operator.ne, np.not_equal)
303
+ ])
304
+ def test_comparison_functions(self, dtype, py_comp, np_comp):
305
+ # Initialize input arrays
306
+ if dtype == np.bool:
307
+ a = np.random.choice(a=[False, True], size=1000)
308
+ b = np.random.choice(a=[False, True], size=1000)
309
+ scalar = True
310
+ else:
311
+ a = np.random.randint(low=1, high=10, size=1000).astype(dtype)
312
+ b = np.random.randint(low=1, high=10, size=1000).astype(dtype)
313
+ scalar = 5
314
+ np_scalar = np.dtype(dtype).type(scalar)
315
+ a_lst = a.tolist()
316
+ b_lst = b.tolist()
317
+
318
+ # (Binary) Comparison (x1=array, x2=array)
319
+ comp_b = np_comp(a, b).view(np.uint8)
320
+ comp_b_list = [int(py_comp(x, y)) for x, y in zip(a_lst, b_lst)]
321
+
322
+ # (Scalar1) Comparison (x1=scalar, x2=array)
323
+ comp_s1 = np_comp(np_scalar, b).view(np.uint8)
324
+ comp_s1_list = [int(py_comp(scalar, x)) for x in b_lst]
325
+
326
+ # (Scalar2) Comparison (x1=array, x2=scalar)
327
+ comp_s2 = np_comp(a, np_scalar).view(np.uint8)
328
+ comp_s2_list = [int(py_comp(x, scalar)) for x in a_lst]
329
+
330
+ # Sequence: Binary, Scalar1 and Scalar2
331
+ assert_(comp_b.tolist() == comp_b_list,
332
+ f"Failed comparison ({py_comp.__name__})")
333
+ assert_(comp_s1.tolist() == comp_s1_list,
334
+ f"Failed comparison ({py_comp.__name__})")
335
+ assert_(comp_s2.tolist() == comp_s2_list,
336
+ f"Failed comparison ({py_comp.__name__})")
337
+
338
+ def test_ignore_object_identity_in_equal(self):
339
+ # Check comparing identical objects whose comparison
340
+ # is not a simple boolean, e.g., arrays that are compared elementwise.
341
+ a = np.array([np.array([1, 2, 3]), None], dtype=object)
342
+ assert_raises(ValueError, np.equal, a, a)
343
+
344
+ # Check error raised when comparing identical non-comparable objects.
345
+ class FunkyType:
346
+ def __eq__(self, other):
347
+ raise TypeError("I won't compare")
348
+
349
+ a = np.array([FunkyType()])
350
+ assert_raises(TypeError, np.equal, a, a)
351
+
352
+ # Check identity doesn't override comparison mismatch.
353
+ a = np.array([np.nan], dtype=object)
354
+ assert_equal(np.equal(a, a), [False])
355
+
356
+ def test_ignore_object_identity_in_not_equal(self):
357
+ # Check comparing identical objects whose comparison
358
+ # is not a simple boolean, e.g., arrays that are compared elementwise.
359
+ a = np.array([np.array([1, 2, 3]), None], dtype=object)
360
+ assert_raises(ValueError, np.not_equal, a, a)
361
+
362
+ # Check error raised when comparing identical non-comparable objects.
363
+ class FunkyType:
364
+ def __ne__(self, other):
365
+ raise TypeError("I won't compare")
366
+
367
+ a = np.array([FunkyType()])
368
+ assert_raises(TypeError, np.not_equal, a, a)
369
+
370
+ # Check identity doesn't override comparison mismatch.
371
+ a = np.array([np.nan], dtype=object)
372
+ assert_equal(np.not_equal(a, a), [True])
373
+
374
+ def test_error_in_equal_reduce(self):
375
+ # gh-20929
376
+ # make sure np.equal.reduce raises a TypeError if an array is passed
377
+ # without specifying the dtype
378
+ a = np.array([0, 0])
379
+ assert_equal(np.equal.reduce(a, dtype=bool), True)
380
+ assert_raises(TypeError, np.equal.reduce, a)
381
+
382
+ def test_object_dtype(self):
383
+ assert np.equal(1, [1], dtype=object).dtype == object
384
+ assert np.equal(1, [1], signature=(None, None, "O")).dtype == object
385
+
386
+ def test_object_nonbool_dtype_error(self):
387
+ # bool output dtype is fine of course:
388
+ assert np.equal(1, [1], dtype=bool).dtype == bool
389
+
390
+ # but the following are examples do not have a loop:
391
+ with pytest.raises(TypeError, match="No loop matching"):
392
+ np.equal(1, 1, dtype=np.int64)
393
+
394
+ with pytest.raises(TypeError, match="No loop matching"):
395
+ np.equal(1, 1, sig=(None, None, "l"))
396
+
397
+ @pytest.mark.parametrize("dtypes", ["qQ", "Qq"])
398
+ @pytest.mark.parametrize('py_comp, np_comp', [
399
+ (operator.lt, np.less),
400
+ (operator.le, np.less_equal),
401
+ (operator.gt, np.greater),
402
+ (operator.ge, np.greater_equal),
403
+ (operator.eq, np.equal),
404
+ (operator.ne, np.not_equal)
405
+ ])
406
+ @pytest.mark.parametrize("vals", [(2**60, 2**60 + 1), (2**60 + 1, 2**60)])
407
+ def test_large_integer_direct_comparison(
408
+ self, dtypes, py_comp, np_comp, vals):
409
+ # Note that float(2**60) + 1 == float(2**60).
410
+ a1 = np.array([2**60], dtype=dtypes[0])
411
+ a2 = np.array([2**60 + 1], dtype=dtypes[1])
412
+ expected = py_comp(2**60, 2**60 + 1)
413
+
414
+ assert py_comp(a1, a2) == expected
415
+ assert np_comp(a1, a2) == expected
416
+ # Also check the scalars:
417
+ s1 = a1[0]
418
+ s2 = a2[0]
419
+ assert isinstance(s1, np.integer)
420
+ assert isinstance(s2, np.integer)
421
+ # The Python operator here is mainly interesting:
422
+ assert py_comp(s1, s2) == expected
423
+ assert np_comp(s1, s2) == expected
424
+
425
+ @pytest.mark.parametrize("dtype", np.typecodes['UnsignedInteger'])
426
+ @pytest.mark.parametrize('py_comp_func, np_comp_func', [
427
+ (operator.lt, np.less),
428
+ (operator.le, np.less_equal),
429
+ (operator.gt, np.greater),
430
+ (operator.ge, np.greater_equal),
431
+ (operator.eq, np.equal),
432
+ (operator.ne, np.not_equal)
433
+ ])
434
+ @pytest.mark.parametrize("flip", [True, False])
435
+ def test_unsigned_signed_direct_comparison(
436
+ self, dtype, py_comp_func, np_comp_func, flip):
437
+ if flip:
438
+ py_comp = lambda x, y: py_comp_func(y, x)
439
+ np_comp = lambda x, y: np_comp_func(y, x)
440
+ else:
441
+ py_comp = py_comp_func
442
+ np_comp = np_comp_func
443
+
444
+ arr = np.array([np.iinfo(dtype).max], dtype=dtype)
445
+ expected = py_comp(int(arr[0]), -1)
446
+
447
+ assert py_comp(arr, -1) == expected
448
+ assert np_comp(arr, -1) == expected
449
+
450
+ scalar = arr[0]
451
+ assert isinstance(scalar, np.integer)
452
+ # The Python operator here is mainly interesting:
453
+ assert py_comp(scalar, -1) == expected
454
+ assert np_comp(scalar, -1) == expected
455
+
456
+
457
+ class TestAdd:
458
+ def test_reduce_alignment(self):
459
+ # gh-9876
460
+ # make sure arrays with weird strides work with the optimizations in
461
+ # pairwise_sum_@TYPE@. On x86, the 'b' field will count as aligned at a
462
+ # 4 byte offset, even though its itemsize is 8.
463
+ a = np.zeros(2, dtype=[('a', np.int32), ('b', np.float64)])
464
+ a['a'] = -1
465
+ assert_equal(a['b'].sum(), 0)
466
+
467
+
468
+ class TestDivision:
469
+ def test_division_int(self):
470
+ # int division should follow Python
471
+ x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120])
472
+ if 5 / 10 == 0.5:
473
+ assert_equal(x / 100, [0.05, 0.1, 0.9, 1,
474
+ -0.05, -0.1, -0.9, -1, -1.2])
475
+ else:
476
+ assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
477
+ assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])
478
+ assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80])
479
+
480
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
481
+ @pytest.mark.parametrize("dtype,ex_val", itertools.product(
482
+ sctypes['int'] + sctypes['uint'], (
483
+ (
484
+ # dividend
485
+ "np.array(range(fo.max-lsize, fo.max)).astype(dtype),"
486
+ # divisors
487
+ "np.arange(lsize).astype(dtype),"
488
+ # scalar divisors
489
+ "range(15)"
490
+ ),
491
+ (
492
+ # dividend
493
+ "np.arange(fo.min, fo.min+lsize).astype(dtype),"
494
+ # divisors
495
+ "np.arange(lsize//-2, lsize//2).astype(dtype),"
496
+ # scalar divisors
497
+ "range(fo.min, fo.min + 15)"
498
+ ), (
499
+ # dividend
500
+ "np.array(range(fo.max-lsize, fo.max)).astype(dtype),"
501
+ # divisors
502
+ "np.arange(lsize).astype(dtype),"
503
+ # scalar divisors
504
+ "[1,3,9,13,neg, fo.min+1, fo.min//2, fo.max//3, fo.max//4]"
505
+ )
506
+ )
507
+ ))
508
+ def test_division_int_boundary(self, dtype, ex_val):
509
+ fo = np.iinfo(dtype)
510
+ neg = -1 if fo.min < 0 else 1
511
+ # Large enough to test SIMD loops and remainder elements
512
+ lsize = 512 + 7
513
+ a, b, divisors = eval(ex_val)
514
+ a_lst, b_lst = a.tolist(), b.tolist()
515
+
516
+ c_div = lambda n, d: (
517
+ 0 if d == 0 else (
518
+ fo.min if (n and n == fo.min and d == -1) else n // d
519
+ )
520
+ )
521
+ with np.errstate(divide='ignore'):
522
+ ac = a.copy()
523
+ ac //= b
524
+ div_ab = a // b
525
+ div_lst = [c_div(x, y) for x, y in zip(a_lst, b_lst)]
526
+
527
+ msg = "Integer arrays floor division check (//)"
528
+ assert all(div_ab == div_lst), msg
529
+ msg_eq = "Integer arrays floor division check (//=)"
530
+ assert all(ac == div_lst), msg_eq
531
+
532
+ for divisor in divisors:
533
+ ac = a.copy()
534
+ with np.errstate(divide='ignore', over='ignore'):
535
+ div_a = a // divisor
536
+ ac //= divisor
537
+ div_lst = [c_div(i, divisor) for i in a_lst]
538
+
539
+ assert all(div_a == div_lst), msg
540
+ assert all(ac == div_lst), msg_eq
541
+
542
+ with np.errstate(divide='raise', over='raise'):
543
+ if 0 in b:
544
+ # Verify overflow case
545
+ with pytest.raises(FloatingPointError,
546
+ match="divide by zero encountered in floor_divide"):
547
+ a // b
548
+ else:
549
+ a // b
550
+ if fo.min and fo.min in a:
551
+ with pytest.raises(FloatingPointError,
552
+ match='overflow encountered in floor_divide'):
553
+ a // -1
554
+ elif fo.min:
555
+ a // -1
556
+ with pytest.raises(FloatingPointError,
557
+ match="divide by zero encountered in floor_divide"):
558
+ a // 0
559
+ with pytest.raises(FloatingPointError,
560
+ match="divide by zero encountered in floor_divide"):
561
+ ac = a.copy()
562
+ ac //= 0
563
+
564
+ np.array([], dtype=dtype) // 0
565
+
566
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
567
+ @pytest.mark.parametrize("dtype,ex_val", itertools.product(
568
+ sctypes['int'] + sctypes['uint'], (
569
+ "np.array([fo.max, 1, 2, 1, 1, 2, 3], dtype=dtype)",
570
+ "np.array([fo.min, 1, -2, 1, 1, 2, -3]).astype(dtype)",
571
+ "np.arange(fo.min, fo.min+(100*10), 10, dtype=dtype)",
572
+ "np.array(range(fo.max-(100*7), fo.max, 7)).astype(dtype)",
573
+ )
574
+ ))
575
+ def test_division_int_reduce(self, dtype, ex_val):
576
+ fo = np.iinfo(dtype)
577
+ a = eval(ex_val)
578
+ lst = a.tolist()
579
+ c_div = lambda n, d: (
580
+ 0 if d == 0 or (n and n == fo.min and d == -1) else n // d
581
+ )
582
+
583
+ with np.errstate(divide='ignore'):
584
+ div_a = np.floor_divide.reduce(a)
585
+ div_lst = reduce(c_div, lst)
586
+ msg = "Reduce floor integer division check"
587
+ assert div_a == div_lst, msg
588
+
589
+ with np.errstate(divide='raise', over='raise'):
590
+ with pytest.raises(FloatingPointError,
591
+ match="divide by zero encountered in reduce"):
592
+ np.floor_divide.reduce(np.arange(-100, 100).astype(dtype))
593
+ if fo.min:
594
+ with pytest.raises(FloatingPointError,
595
+ match='overflow encountered in reduce'):
596
+ np.floor_divide.reduce(
597
+ np.array([fo.min, 1, -1], dtype=dtype)
598
+ )
599
+
600
+ @pytest.mark.parametrize(
601
+ "dividend,divisor,quotient",
602
+ [(np.timedelta64(2, 'Y'), np.timedelta64(2, 'M'), 12),
603
+ (np.timedelta64(2, 'Y'), np.timedelta64(-2, 'M'), -12),
604
+ (np.timedelta64(-2, 'Y'), np.timedelta64(2, 'M'), -12),
605
+ (np.timedelta64(-2, 'Y'), np.timedelta64(-2, 'M'), 12),
606
+ (np.timedelta64(2, 'M'), np.timedelta64(-2, 'Y'), -1),
607
+ (np.timedelta64(2, 'Y'), np.timedelta64(0, 'M'), 0),
608
+ (np.timedelta64(2, 'Y'), 2, np.timedelta64(1, 'Y')),
609
+ (np.timedelta64(2, 'Y'), -2, np.timedelta64(-1, 'Y')),
610
+ (np.timedelta64(-2, 'Y'), 2, np.timedelta64(-1, 'Y')),
611
+ (np.timedelta64(-2, 'Y'), -2, np.timedelta64(1, 'Y')),
612
+ (np.timedelta64(-2, 'Y'), -2, np.timedelta64(1, 'Y')),
613
+ (np.timedelta64(-2, 'Y'), -3, np.timedelta64(0, 'Y')),
614
+ (np.timedelta64(-2, 'Y'), 0, np.timedelta64('Nat', 'Y')),
615
+ ])
616
+ def test_division_int_timedelta(self, dividend, divisor, quotient):
617
+ # If either divisor is 0 or quotient is Nat, check for division by 0
618
+ if divisor and (isinstance(quotient, int) or not np.isnat(quotient)):
619
+ msg = "Timedelta floor division check"
620
+ assert dividend // divisor == quotient, msg
621
+
622
+ # Test for arrays as well
623
+ msg = "Timedelta arrays floor division check"
624
+ dividend_array = np.array([dividend] * 5)
625
+ quotient_array = np.array([quotient] * 5)
626
+ assert all(dividend_array // divisor == quotient_array), msg
627
+ else:
628
+ if IS_WASM:
629
+ pytest.skip("fp errors don't work in wasm")
630
+ with np.errstate(divide='raise', invalid='raise'):
631
+ with pytest.raises(FloatingPointError):
632
+ dividend // divisor
633
+
634
+ def test_division_complex(self):
635
+ # check that implementation is correct
636
+ msg = "Complex division implementation check"
637
+ x = np.array([1. + 1. * 1j, 1. + .5 * 1j, 1. + 2. * 1j], dtype=np.complex128)
638
+ assert_almost_equal(x**2 / x, x, err_msg=msg)
639
+ # check overflow, underflow
640
+ msg = "Complex division overflow/underflow check"
641
+ x = np.array([1.e+110, 1.e-110], dtype=np.complex128)
642
+ y = x**2 / x
643
+ assert_almost_equal(y / x, [1, 1], err_msg=msg)
644
+
645
+ def test_zero_division_complex(self):
646
+ with np.errstate(invalid="ignore", divide="ignore"):
647
+ x = np.array([0.0], dtype=np.complex128)
648
+ y = 1.0 / x
649
+ assert_(np.isinf(y)[0])
650
+ y = complex(np.inf, np.nan) / x
651
+ assert_(np.isinf(y)[0])
652
+ y = complex(np.nan, np.inf) / x
653
+ assert_(np.isinf(y)[0])
654
+ y = complex(np.inf, np.inf) / x
655
+ assert_(np.isinf(y)[0])
656
+ y = 0.0 / x
657
+ assert_(np.isnan(y)[0])
658
+
659
+ def test_floor_division_complex(self):
660
+ # check that floor division, divmod and remainder raises type errors
661
+ x = np.array([.9 + 1j, -.1 + 1j, .9 + .5 * 1j, .9 + 2. * 1j], dtype=np.complex128)
662
+ with pytest.raises(TypeError):
663
+ x // 7
664
+ with pytest.raises(TypeError):
665
+ np.divmod(x, 7)
666
+ with pytest.raises(TypeError):
667
+ np.remainder(x, 7)
668
+
669
+ def test_floor_division_signed_zero(self):
670
+ # Check that the sign bit is correctly set when dividing positive and
671
+ # negative zero by one.
672
+ x = np.zeros(10)
673
+ assert_equal(np.signbit(x // 1), 0)
674
+ assert_equal(np.signbit((-x) // 1), 1)
675
+
676
+ @pytest.mark.skipif(hasattr(np.__config__, "blas_ssl2_info"),
677
+ reason="gh-22982")
678
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
679
+ @pytest.mark.parametrize('dtype', np.typecodes['Float'])
680
+ def test_floor_division_errors(self, dtype):
681
+ fnan = np.array(np.nan, dtype=dtype)
682
+ fone = np.array(1.0, dtype=dtype)
683
+ fzer = np.array(0.0, dtype=dtype)
684
+ finf = np.array(np.inf, dtype=dtype)
685
+ # divide by zero error check
686
+ with np.errstate(divide='raise', invalid='ignore'):
687
+ assert_raises(FloatingPointError, np.floor_divide, fone, fzer)
688
+ with np.errstate(divide='ignore', invalid='raise'):
689
+ np.floor_divide(fone, fzer)
690
+
691
+ # The following already contain a NaN and should not warn
692
+ with np.errstate(all='raise'):
693
+ np.floor_divide(fnan, fone)
694
+ np.floor_divide(fone, fnan)
695
+ np.floor_divide(fnan, fzer)
696
+ np.floor_divide(fzer, fnan)
697
+
698
+ @pytest.mark.parametrize('dtype', np.typecodes['Float'])
699
+ def test_floor_division_corner_cases(self, dtype):
700
+ # test corner cases like 1.0//0.0 for errors and return vals
701
+ x = np.zeros(10, dtype=dtype)
702
+ y = np.ones(10, dtype=dtype)
703
+ fnan = np.array(np.nan, dtype=dtype)
704
+ fone = np.array(1.0, dtype=dtype)
705
+ fzer = np.array(0.0, dtype=dtype)
706
+ finf = np.array(np.inf, dtype=dtype)
707
+ with suppress_warnings() as sup:
708
+ sup.filter(RuntimeWarning, "invalid value encountered in floor_divide")
709
+ div = np.floor_divide(fnan, fone)
710
+ assert np.isnan(div), f"div: {div}"
711
+ div = np.floor_divide(fone, fnan)
712
+ assert np.isnan(div), f"div: {div}"
713
+ div = np.floor_divide(fnan, fzer)
714
+ assert np.isnan(div), f"div: {div}"
715
+ # verify 1.0//0.0 computations return inf
716
+ with np.errstate(divide='ignore'):
717
+ z = np.floor_divide(y, x)
718
+ assert_(np.isinf(z).all())
719
+
720
+ def floor_divide_and_remainder(x, y):
721
+ return (np.floor_divide(x, y), np.remainder(x, y))
722
+
723
+
724
+ def _signs(dt):
725
+ if dt in np.typecodes['UnsignedInteger']:
726
+ return (+1,)
727
+ else:
728
+ return (+1, -1)
729
+
730
+
731
+ class TestRemainder:
732
+
733
+ def test_remainder_basic(self):
734
+ dt = np.typecodes['AllInteger'] + np.typecodes['Float']
735
+ for op in [floor_divide_and_remainder, np.divmod]:
736
+ for dt1, dt2 in itertools.product(dt, dt):
737
+ for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
738
+ fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
739
+ msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
740
+ a = np.array(sg1 * 71, dtype=dt1)
741
+ b = np.array(sg2 * 19, dtype=dt2)
742
+ div, rem = op(a, b)
743
+ assert_equal(div * b + rem, a, err_msg=msg)
744
+ if sg2 == -1:
745
+ assert_(b < rem <= 0, msg)
746
+ else:
747
+ assert_(b > rem >= 0, msg)
748
+
749
+ def test_float_remainder_exact(self):
750
+ # test that float results are exact for small integers. This also
751
+ # holds for the same integers scaled by powers of two.
752
+ nlst = list(range(-127, 0))
753
+ plst = list(range(1, 128))
754
+ dividend = nlst + [0] + plst
755
+ divisor = nlst + plst
756
+ arg = list(itertools.product(dividend, divisor))
757
+ tgt = [divmod(*t) for t in arg]
758
+
759
+ a, b = np.array(arg, dtype=int).T
760
+ # convert exact integer results from Python to float so that
761
+ # signed zero can be used, it is checked.
762
+ tgtdiv, tgtrem = np.array(tgt, dtype=float).T
763
+ tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
764
+ tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
765
+
766
+ for op in [floor_divide_and_remainder, np.divmod]:
767
+ for dt in np.typecodes['Float']:
768
+ msg = f'op: {op.__name__}, dtype: {dt}'
769
+ fa = a.astype(dt)
770
+ fb = b.astype(dt)
771
+ div, rem = op(fa, fb)
772
+ assert_equal(div, tgtdiv, err_msg=msg)
773
+ assert_equal(rem, tgtrem, err_msg=msg)
774
+
775
+ def test_float_remainder_roundoff(self):
776
+ # gh-6127
777
+ dt = np.typecodes['Float']
778
+ for op in [floor_divide_and_remainder, np.divmod]:
779
+ for dt1, dt2 in itertools.product(dt, dt):
780
+ for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
781
+ fmt = 'op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s'
782
+ msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
783
+ a = np.array(sg1 * 78 * 6e-8, dtype=dt1)
784
+ b = np.array(sg2 * 6e-8, dtype=dt2)
785
+ div, rem = op(a, b)
786
+ # Equal assertion should hold when fmod is used
787
+ assert_equal(div * b + rem, a, err_msg=msg)
788
+ if sg2 == -1:
789
+ assert_(b < rem <= 0, msg)
790
+ else:
791
+ assert_(b > rem >= 0, msg)
792
+
793
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
794
+ @pytest.mark.xfail(sys.platform.startswith("darwin"),
795
+ reason="MacOS seems to not give the correct 'invalid' warning for "
796
+ "`fmod`. Hopefully, others always do.")
797
+ @pytest.mark.parametrize('dtype', np.typecodes['Float'])
798
+ def test_float_divmod_errors(self, dtype):
799
+ # Check valid errors raised for divmod and remainder
800
+ fzero = np.array(0.0, dtype=dtype)
801
+ fone = np.array(1.0, dtype=dtype)
802
+ finf = np.array(np.inf, dtype=dtype)
803
+ fnan = np.array(np.nan, dtype=dtype)
804
+ # since divmod is combination of both remainder and divide
805
+ # ops it will set both dividebyzero and invalid flags
806
+ with np.errstate(divide='raise', invalid='ignore'):
807
+ assert_raises(FloatingPointError, np.divmod, fone, fzero)
808
+ with np.errstate(divide='ignore', invalid='raise'):
809
+ assert_raises(FloatingPointError, np.divmod, fone, fzero)
810
+ with np.errstate(invalid='raise'):
811
+ assert_raises(FloatingPointError, np.divmod, fzero, fzero)
812
+ with np.errstate(invalid='raise'):
813
+ assert_raises(FloatingPointError, np.divmod, finf, finf)
814
+ with np.errstate(divide='ignore', invalid='raise'):
815
+ assert_raises(FloatingPointError, np.divmod, finf, fzero)
816
+ with np.errstate(divide='raise', invalid='ignore'):
817
+ # inf / 0 does not set any flags, only the modulo creates a NaN
818
+ np.divmod(finf, fzero)
819
+
820
+ @pytest.mark.skipif(hasattr(np.__config__, "blas_ssl2_info"),
821
+ reason="gh-22982")
822
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
823
+ @pytest.mark.xfail(sys.platform.startswith("darwin"),
824
+ reason="MacOS seems to not give the correct 'invalid' warning for "
825
+ "`fmod`. Hopefully, others always do.")
826
+ @pytest.mark.parametrize('dtype', np.typecodes['Float'])
827
+ @pytest.mark.parametrize('fn', [np.fmod, np.remainder])
828
+ def test_float_remainder_errors(self, dtype, fn):
829
+ fzero = np.array(0.0, dtype=dtype)
830
+ fone = np.array(1.0, dtype=dtype)
831
+ finf = np.array(np.inf, dtype=dtype)
832
+ fnan = np.array(np.nan, dtype=dtype)
833
+
834
+ # The following already contain a NaN and should not warn.
835
+ with np.errstate(all='raise'):
836
+ with pytest.raises(FloatingPointError,
837
+ match="invalid value"):
838
+ fn(fone, fzero)
839
+ fn(fnan, fzero)
840
+ fn(fzero, fnan)
841
+ fn(fone, fnan)
842
+ fn(fnan, fone)
843
+
844
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
845
+ def test_float_remainder_overflow(self):
846
+ a = np.finfo(np.float64).tiny
847
+ with np.errstate(over='ignore', invalid='ignore'):
848
+ div, mod = np.divmod(4, a)
849
+ np.isinf(div)
850
+ assert_(mod == 0)
851
+ with np.errstate(over='raise', invalid='ignore'):
852
+ assert_raises(FloatingPointError, np.divmod, 4, a)
853
+ with np.errstate(invalid='raise', over='ignore'):
854
+ assert_raises(FloatingPointError, np.divmod, 4, a)
855
+
856
+ def test_float_divmod_corner_cases(self):
857
+ # check nan cases
858
+ for dt in np.typecodes['Float']:
859
+ fnan = np.array(np.nan, dtype=dt)
860
+ fone = np.array(1.0, dtype=dt)
861
+ fzer = np.array(0.0, dtype=dt)
862
+ finf = np.array(np.inf, dtype=dt)
863
+ with suppress_warnings() as sup:
864
+ sup.filter(RuntimeWarning, "invalid value encountered in divmod")
865
+ sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
866
+ div, rem = np.divmod(fone, fzer)
867
+ assert np.isinf(div), f'dt: {dt}, div: {rem}'
868
+ assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
869
+ div, rem = np.divmod(fzer, fzer)
870
+ assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
871
+ assert_(np.isnan(div)), f'dt: {dt}, rem: {rem}'
872
+ div, rem = np.divmod(finf, finf)
873
+ assert np.isnan(div), f'dt: {dt}, rem: {rem}'
874
+ assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
875
+ div, rem = np.divmod(finf, fzer)
876
+ assert np.isinf(div), f'dt: {dt}, rem: {rem}'
877
+ assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
878
+ div, rem = np.divmod(fnan, fone)
879
+ assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
880
+ assert np.isnan(div), f"dt: {dt}, rem: {rem}"
881
+ div, rem = np.divmod(fone, fnan)
882
+ assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
883
+ assert np.isnan(div), f"dt: {dt}, rem: {rem}"
884
+ div, rem = np.divmod(fnan, fzer)
885
+ assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
886
+ assert np.isnan(div), f"dt: {dt}, rem: {rem}"
887
+
888
+ def test_float_remainder_corner_cases(self):
889
+ # Check remainder magnitude.
890
+ for dt in np.typecodes['Float']:
891
+ fone = np.array(1.0, dtype=dt)
892
+ fzer = np.array(0.0, dtype=dt)
893
+ fnan = np.array(np.nan, dtype=dt)
894
+ b = np.array(1.0, dtype=dt)
895
+ a = np.nextafter(np.array(0.0, dtype=dt), -b)
896
+ rem = np.remainder(a, b)
897
+ assert_(rem <= b, f'dt: {dt}')
898
+ rem = np.remainder(-a, -b)
899
+ assert_(rem >= -b, f'dt: {dt}')
900
+
901
+ # Check nans, inf
902
+ with suppress_warnings() as sup:
903
+ sup.filter(RuntimeWarning, "invalid value encountered in remainder")
904
+ sup.filter(RuntimeWarning, "invalid value encountered in fmod")
905
+ for dt in np.typecodes['Float']:
906
+ fone = np.array(1.0, dtype=dt)
907
+ fzer = np.array(0.0, dtype=dt)
908
+ finf = np.array(np.inf, dtype=dt)
909
+ fnan = np.array(np.nan, dtype=dt)
910
+ rem = np.remainder(fone, fzer)
911
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
912
+ # MSVC 2008 returns NaN here, so disable the check.
913
+ #rem = np.remainder(fone, finf)
914
+ #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
915
+ rem = np.remainder(finf, fone)
916
+ fmod = np.fmod(finf, fone)
917
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
918
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
919
+ rem = np.remainder(finf, finf)
920
+ fmod = np.fmod(finf, fone)
921
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
922
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
923
+ rem = np.remainder(finf, fzer)
924
+ fmod = np.fmod(finf, fzer)
925
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
926
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
927
+ rem = np.remainder(fone, fnan)
928
+ fmod = np.fmod(fone, fnan)
929
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
930
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
931
+ rem = np.remainder(fnan, fzer)
932
+ fmod = np.fmod(fnan, fzer)
933
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
934
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {rem}')
935
+ rem = np.remainder(fnan, fone)
936
+ fmod = np.fmod(fnan, fone)
937
+ assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
938
+ assert_(np.isnan(fmod), f'dt: {dt}, fmod: {rem}')
939
+
940
+
941
+ class TestDivisionIntegerOverflowsAndDivideByZero:
942
+ result_type = namedtuple('result_type',
943
+ ['nocast', 'casted'])
944
+ helper_lambdas = {
945
+ 'zero': lambda dtype: 0,
946
+ 'min': lambda dtype: np.iinfo(dtype).min,
947
+ 'neg_min': lambda dtype: -np.iinfo(dtype).min,
948
+ 'min-zero': lambda dtype: (np.iinfo(dtype).min, 0),
949
+ 'neg_min-zero': lambda dtype: (-np.iinfo(dtype).min, 0),
950
+ }
951
+ overflow_results = {
952
+ np.remainder: result_type(
953
+ helper_lambdas['zero'], helper_lambdas['zero']),
954
+ np.fmod: result_type(
955
+ helper_lambdas['zero'], helper_lambdas['zero']),
956
+ operator.mod: result_type(
957
+ helper_lambdas['zero'], helper_lambdas['zero']),
958
+ operator.floordiv: result_type(
959
+ helper_lambdas['min'], helper_lambdas['neg_min']),
960
+ np.floor_divide: result_type(
961
+ helper_lambdas['min'], helper_lambdas['neg_min']),
962
+ np.divmod: result_type(
963
+ helper_lambdas['min-zero'], helper_lambdas['neg_min-zero'])
964
+ }
965
+
966
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
967
+ @pytest.mark.parametrize("dtype", np.typecodes["Integer"])
968
+ def test_signed_division_overflow(self, dtype):
969
+ to_check = interesting_binop_operands(np.iinfo(dtype).min, -1, dtype)
970
+ for op1, op2, extractor, operand_identifier in to_check:
971
+ with pytest.warns(RuntimeWarning, match="overflow encountered"):
972
+ res = op1 // op2
973
+
974
+ assert res.dtype == op1.dtype
975
+ assert extractor(res) == np.iinfo(op1.dtype).min
976
+
977
+ # Remainder is well defined though, and does not warn:
978
+ res = op1 % op2
979
+ assert res.dtype == op1.dtype
980
+ assert extractor(res) == 0
981
+ # Check fmod as well:
982
+ res = np.fmod(op1, op2)
983
+ assert extractor(res) == 0
984
+
985
+ # Divmod warns for the division part:
986
+ with pytest.warns(RuntimeWarning, match="overflow encountered"):
987
+ res1, res2 = np.divmod(op1, op2)
988
+
989
+ assert res1.dtype == res2.dtype == op1.dtype
990
+ assert extractor(res1) == np.iinfo(op1.dtype).min
991
+ assert extractor(res2) == 0
992
+
993
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
994
+ @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
995
+ def test_divide_by_zero(self, dtype):
996
+ # Note that the return value cannot be well defined here, but NumPy
997
+ # currently uses 0 consistently. This could be changed.
998
+ to_check = interesting_binop_operands(1, 0, dtype)
999
+ for op1, op2, extractor, operand_identifier in to_check:
1000
+ with pytest.warns(RuntimeWarning, match="divide by zero"):
1001
+ res = op1 // op2
1002
+
1003
+ assert res.dtype == op1.dtype
1004
+ assert extractor(res) == 0
1005
+
1006
+ with pytest.warns(RuntimeWarning, match="divide by zero"):
1007
+ res1, res2 = np.divmod(op1, op2)
1008
+
1009
+ assert res1.dtype == res2.dtype == op1.dtype
1010
+ assert extractor(res1) == 0
1011
+ assert extractor(res2) == 0
1012
+
1013
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1014
+ @pytest.mark.parametrize("dividend_dtype", sctypes['int'])
1015
+ @pytest.mark.parametrize("divisor_dtype", sctypes['int'])
1016
+ @pytest.mark.parametrize("operation",
1017
+ [np.remainder, np.fmod, np.divmod, np.floor_divide,
1018
+ operator.mod, operator.floordiv])
1019
+ @np.errstate(divide='warn', over='warn')
1020
+ def test_overflows(self, dividend_dtype, divisor_dtype, operation):
1021
+ # SIMD tries to perform the operation on as many elements as possible
1022
+ # that is a multiple of the register's size. We resort to the
1023
+ # default implementation for the leftover elements.
1024
+ # We try to cover all paths here.
1025
+ arrays = [np.array([np.iinfo(dividend_dtype).min] * i,
1026
+ dtype=dividend_dtype) for i in range(1, 129)]
1027
+ divisor = np.array([-1], dtype=divisor_dtype)
1028
+ # If dividend is a larger type than the divisor (`else` case),
1029
+ # then, result will be a larger type than dividend and will not
1030
+ # result in an overflow for `divmod` and `floor_divide`.
1031
+ if np.dtype(dividend_dtype).itemsize >= np.dtype(
1032
+ divisor_dtype).itemsize and operation in (
1033
+ np.divmod, np.floor_divide, operator.floordiv):
1034
+ with pytest.warns(
1035
+ RuntimeWarning,
1036
+ match="overflow encountered in"):
1037
+ result = operation(
1038
+ dividend_dtype(np.iinfo(dividend_dtype).min),
1039
+ divisor_dtype(-1)
1040
+ )
1041
+ assert result == self.overflow_results[operation].nocast(
1042
+ dividend_dtype)
1043
+
1044
+ # Arrays
1045
+ for a in arrays:
1046
+ # In case of divmod, we need to flatten the result
1047
+ # column first as we get a column vector of quotient and
1048
+ # remainder and a normal flatten of the expected result.
1049
+ with pytest.warns(
1050
+ RuntimeWarning,
1051
+ match="overflow encountered in"):
1052
+ result = np.array(operation(a, divisor)).flatten('f')
1053
+ expected_array = np.array(
1054
+ [self.overflow_results[operation].nocast(
1055
+ dividend_dtype)] * len(a)).flatten()
1056
+ assert_array_equal(result, expected_array)
1057
+ else:
1058
+ # Scalars
1059
+ result = operation(
1060
+ dividend_dtype(np.iinfo(dividend_dtype).min),
1061
+ divisor_dtype(-1)
1062
+ )
1063
+ assert result == self.overflow_results[operation].casted(
1064
+ dividend_dtype)
1065
+
1066
+ # Arrays
1067
+ for a in arrays:
1068
+ # See above comment on flatten
1069
+ result = np.array(operation(a, divisor)).flatten('f')
1070
+ expected_array = np.array(
1071
+ [self.overflow_results[operation].casted(
1072
+ dividend_dtype)] * len(a)).flatten()
1073
+ assert_array_equal(result, expected_array)
1074
+
1075
+
1076
+ class TestCbrt:
1077
+ def test_cbrt_scalar(self):
1078
+ assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5)
1079
+
1080
+ def test_cbrt(self):
1081
+ x = np.array([1., 2., -3., np.inf, -np.inf])
1082
+ assert_almost_equal(np.cbrt(x**3), x)
1083
+
1084
+ assert_(np.isnan(np.cbrt(np.nan)))
1085
+ assert_equal(np.cbrt(np.inf), np.inf)
1086
+ assert_equal(np.cbrt(-np.inf), -np.inf)
1087
+
1088
+
1089
+ class TestPower:
1090
+ def test_power_float(self):
1091
+ x = np.array([1., 2., 3.])
1092
+ assert_equal(x**0, [1., 1., 1.])
1093
+ assert_equal(x**1, x)
1094
+ assert_equal(x**2, [1., 4., 9.])
1095
+ y = x.copy()
1096
+ y **= 2
1097
+ assert_equal(y, [1., 4., 9.])
1098
+ assert_almost_equal(x**(-1), [1., 0.5, 1. / 3])
1099
+ assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
1100
+
1101
+ for out, inp, msg in _gen_alignment_data(dtype=np.float32,
1102
+ type='unary',
1103
+ max_size=11):
1104
+ exp = [ncu.sqrt(i) for i in inp]
1105
+ assert_almost_equal(inp**(0.5), exp, err_msg=msg)
1106
+ np.sqrt(inp, out=out)
1107
+ assert_equal(out, exp, err_msg=msg)
1108
+
1109
+ for out, inp, msg in _gen_alignment_data(dtype=np.float64,
1110
+ type='unary',
1111
+ max_size=7):
1112
+ exp = [ncu.sqrt(i) for i in inp]
1113
+ assert_almost_equal(inp**(0.5), exp, err_msg=msg)
1114
+ np.sqrt(inp, out=out)
1115
+ assert_equal(out, exp, err_msg=msg)
1116
+
1117
+ def test_power_complex(self):
1118
+ x = np.array([1 + 2j, 2 + 3j, 3 + 4j])
1119
+ assert_equal(x**0, [1., 1., 1.])
1120
+ assert_equal(x**1, x)
1121
+ assert_almost_equal(x**2, [-3 + 4j, -5 + 12j, -7 + 24j])
1122
+ assert_almost_equal(x**3, [(1 + 2j)**3, (2 + 3j)**3, (3 + 4j)**3])
1123
+ assert_almost_equal(x**4, [(1 + 2j)**4, (2 + 3j)**4, (3 + 4j)**4])
1124
+ assert_almost_equal(x**(-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)])
1125
+ assert_almost_equal(x**(-2), [1 / (1 + 2j)**2, 1 / (2 + 3j)**2, 1 / (3 + 4j)**2])
1126
+ assert_almost_equal(x**(-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197,
1127
+ (-117 - 44j) / 15625])
1128
+ assert_almost_equal(x**(0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j),
1129
+ ncu.sqrt(3 + 4j)])
1130
+ norm = 1. / ((x**14)[0])
1131
+ assert_almost_equal(x**14 * norm,
1132
+ [i * norm for i in [-76443 + 16124j, 23161315 + 58317492j,
1133
+ 5583548873 + 2465133864j]])
1134
+
1135
+ # Ticket #836
1136
+ def assert_complex_equal(x, y):
1137
+ assert_array_equal(x.real, y.real)
1138
+ assert_array_equal(x.imag, y.imag)
1139
+
1140
+ for z in [complex(0, np.inf), complex(1, np.inf)]:
1141
+ z = np.array([z], dtype=np.complex128)
1142
+ with np.errstate(invalid="ignore"):
1143
+ assert_complex_equal(z**1, z)
1144
+ assert_complex_equal(z**2, z * z)
1145
+ assert_complex_equal(z**3, z * z * z)
1146
+
1147
+ def test_power_zero(self):
1148
+ # ticket #1271
1149
+ zero = np.array([0j])
1150
+ one = np.array([1 + 0j])
1151
+ cnan = np.array([complex(np.nan, np.nan)])
1152
+ # FIXME cinf not tested.
1153
+ #cinf = np.array([complex(np.inf, 0)])
1154
+
1155
+ def assert_complex_equal(x, y):
1156
+ x, y = np.asarray(x), np.asarray(y)
1157
+ assert_array_equal(x.real, y.real)
1158
+ assert_array_equal(x.imag, y.imag)
1159
+
1160
+ # positive powers
1161
+ for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
1162
+ assert_complex_equal(np.power(zero, p), zero)
1163
+
1164
+ # zero power
1165
+ assert_complex_equal(np.power(zero, 0), one)
1166
+ with np.errstate(invalid="ignore"):
1167
+ assert_complex_equal(np.power(zero, 0 + 1j), cnan)
1168
+
1169
+ # negative power
1170
+ for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]:
1171
+ assert_complex_equal(np.power(zero, -p), cnan)
1172
+ assert_complex_equal(np.power(zero, -1 + 0.2j), cnan)
1173
+
1174
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1175
+ def test_zero_power_nonzero(self):
1176
+ # Testing 0^{Non-zero} issue 18378
1177
+ zero = np.array([0.0 + 0.0j])
1178
+ cnan = np.array([complex(np.nan, np.nan)])
1179
+
1180
+ def assert_complex_equal(x, y):
1181
+ assert_array_equal(x.real, y.real)
1182
+ assert_array_equal(x.imag, y.imag)
1183
+
1184
+ # Complex powers with positive real part will not generate a warning
1185
+ assert_complex_equal(np.power(zero, 1 + 4j), zero)
1186
+ assert_complex_equal(np.power(zero, 2 - 3j), zero)
1187
+ # Testing zero values when real part is greater than zero
1188
+ assert_complex_equal(np.power(zero, 1 + 1j), zero)
1189
+ assert_complex_equal(np.power(zero, 1 + 0j), zero)
1190
+ assert_complex_equal(np.power(zero, 1 - 1j), zero)
1191
+ # Complex powers will negative real part or 0 (provided imaginary
1192
+ # part is not zero) will generate a NAN and hence a RUNTIME warning
1193
+ with pytest.warns(expected_warning=RuntimeWarning) as r:
1194
+ assert_complex_equal(np.power(zero, -1 + 1j), cnan)
1195
+ assert_complex_equal(np.power(zero, -2 - 3j), cnan)
1196
+ assert_complex_equal(np.power(zero, -7 + 0j), cnan)
1197
+ assert_complex_equal(np.power(zero, 0 + 1j), cnan)
1198
+ assert_complex_equal(np.power(zero, 0 - 1j), cnan)
1199
+ assert len(r) == 5
1200
+
1201
+ def test_fast_power(self):
1202
+ x = np.array([1, 2, 3], np.int16)
1203
+ res = x**2.0
1204
+ assert_((x**2.00001).dtype is res.dtype)
1205
+ assert_array_equal(res, [1, 4, 9])
1206
+ # check the inplace operation on the casted copy doesn't mess with x
1207
+ assert_(not np.may_share_memory(res, x))
1208
+ assert_array_equal(x, [1, 2, 3])
1209
+
1210
+ # Check that the fast path ignores 1-element not 0-d arrays
1211
+ res = x ** np.array([[[2]]])
1212
+ assert_equal(res.shape, (1, 1, 3))
1213
+
1214
+ def test_integer_power(self):
1215
+ a = np.array([15, 15], 'i8')
1216
+ b = np.power(a, a)
1217
+ assert_equal(b, [437893890380859375, 437893890380859375])
1218
+
1219
+ def test_integer_power_with_integer_zero_exponent(self):
1220
+ dtypes = np.typecodes['Integer']
1221
+ for dt in dtypes:
1222
+ arr = np.arange(-10, 10, dtype=dt)
1223
+ assert_equal(np.power(arr, 0), np.ones_like(arr))
1224
+
1225
+ dtypes = np.typecodes['UnsignedInteger']
1226
+ for dt in dtypes:
1227
+ arr = np.arange(10, dtype=dt)
1228
+ assert_equal(np.power(arr, 0), np.ones_like(arr))
1229
+
1230
+ def test_integer_power_of_1(self):
1231
+ dtypes = np.typecodes['AllInteger']
1232
+ for dt in dtypes:
1233
+ arr = np.arange(10, dtype=dt)
1234
+ assert_equal(np.power(1, arr), np.ones_like(arr))
1235
+
1236
+ def test_integer_power_of_zero(self):
1237
+ dtypes = np.typecodes['AllInteger']
1238
+ for dt in dtypes:
1239
+ arr = np.arange(1, 10, dtype=dt)
1240
+ assert_equal(np.power(0, arr), np.zeros_like(arr))
1241
+
1242
+ def test_integer_to_negative_power(self):
1243
+ dtypes = np.typecodes['Integer']
1244
+ for dt in dtypes:
1245
+ a = np.array([0, 1, 2, 3], dtype=dt)
1246
+ b = np.array([0, 1, 2, -3], dtype=dt)
1247
+ one = np.array(1, dtype=dt)
1248
+ minusone = np.array(-1, dtype=dt)
1249
+ assert_raises(ValueError, np.power, a, b)
1250
+ assert_raises(ValueError, np.power, a, minusone)
1251
+ assert_raises(ValueError, np.power, one, b)
1252
+ assert_raises(ValueError, np.power, one, minusone)
1253
+
1254
+ def test_float_to_inf_power(self):
1255
+ for dt in [np.float32, np.float64]:
1256
+ a = np.array([1, 1, 2, 2, -2, -2, np.inf, -np.inf], dt)
1257
+ b = np.array([np.inf, -np.inf, np.inf, -np.inf,
1258
+ np.inf, -np.inf, np.inf, -np.inf], dt)
1259
+ r = np.array([1, 1, np.inf, 0, np.inf, 0, np.inf, 0], dt)
1260
+ assert_equal(np.power(a, b), r)
1261
+
1262
+ def test_power_fast_paths(self):
1263
+ # gh-26055
1264
+ for dt in [np.float32, np.float64]:
1265
+ a = np.array([0, 1.1, 2, 12e12, -10., np.inf, -np.inf], dt)
1266
+ expected = np.array([0.0, 1.21, 4., 1.44e+26, 100, np.inf, np.inf])
1267
+ result = np.power(a, 2.)
1268
+ assert_array_max_ulp(result, expected.astype(dt), maxulp=1)
1269
+
1270
+ a = np.array([0, 1.1, 2, 12e12], dt)
1271
+ expected = np.sqrt(a).astype(dt)
1272
+ result = np.power(a, 0.5)
1273
+ assert_array_max_ulp(result, expected, maxulp=1)
1274
+
1275
+
1276
+ class TestFloat_power:
1277
+ def test_type_conversion(self):
1278
+ arg_type = '?bhilBHILefdgFDG'
1279
+ res_type = 'ddddddddddddgDDG'
1280
+ for dtin, dtout in zip(arg_type, res_type):
1281
+ msg = f"dtin: {dtin}, dtout: {dtout}"
1282
+ arg = np.ones(1, dtype=dtin)
1283
+ res = np.float_power(arg, arg)
1284
+ assert_(res.dtype.name == np.dtype(dtout).name, msg)
1285
+
1286
+
1287
+ class TestLog2:
1288
+ @pytest.mark.parametrize('dt', ['f', 'd', 'g'])
1289
+ def test_log2_values(self, dt):
1290
+ x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
1291
+ y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1292
+ xf = np.array(x, dtype=dt)
1293
+ yf = np.array(y, dtype=dt)
1294
+ assert_almost_equal(np.log2(xf), yf)
1295
+
1296
+ @pytest.mark.parametrize("i", range(1, 65))
1297
+ def test_log2_ints(self, i):
1298
+ # a good log2 implementation should provide this,
1299
+ # might fail on OS with bad libm
1300
+ v = np.log2(2.**i)
1301
+ assert_equal(v, float(i), err_msg='at exponent %d' % i)
1302
+
1303
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1304
+ def test_log2_special(self):
1305
+ assert_equal(np.log2(1.), 0.)
1306
+ assert_equal(np.log2(np.inf), np.inf)
1307
+ assert_(np.isnan(np.log2(np.nan)))
1308
+
1309
+ with warnings.catch_warnings(record=True) as w:
1310
+ warnings.filterwarnings('always', '', RuntimeWarning)
1311
+ assert_(np.isnan(np.log2(-1.)))
1312
+ assert_(np.isnan(np.log2(-np.inf)))
1313
+ assert_equal(np.log2(0.), -np.inf)
1314
+ assert_(w[0].category is RuntimeWarning)
1315
+ assert_(w[1].category is RuntimeWarning)
1316
+ assert_(w[2].category is RuntimeWarning)
1317
+
1318
+
1319
+ class TestExp2:
1320
+ def test_exp2_values(self):
1321
+ x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
1322
+ y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1323
+ for dt in ['f', 'd', 'g']:
1324
+ xf = np.array(x, dtype=dt)
1325
+ yf = np.array(y, dtype=dt)
1326
+ assert_almost_equal(np.exp2(yf), xf)
1327
+
1328
+
1329
+ class TestLogAddExp2(_FilterInvalids):
1330
+ # Need test for intermediate precisions
1331
+ def test_logaddexp2_values(self):
1332
+ x = [1, 2, 3, 4, 5]
1333
+ y = [5, 4, 3, 2, 1]
1334
+ z = [6, 6, 6, 6, 6]
1335
+ for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
1336
+ xf = np.log2(np.array(x, dtype=dt))
1337
+ yf = np.log2(np.array(y, dtype=dt))
1338
+ zf = np.log2(np.array(z, dtype=dt))
1339
+ assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec_)
1340
+
1341
+ def test_logaddexp2_range(self):
1342
+ x = [1000000, -1000000, 1000200, -1000200]
1343
+ y = [1000200, -1000200, 1000000, -1000000]
1344
+ z = [1000200, -1000000, 1000200, -1000000]
1345
+ for dt in ['f', 'd', 'g']:
1346
+ logxf = np.array(x, dtype=dt)
1347
+ logyf = np.array(y, dtype=dt)
1348
+ logzf = np.array(z, dtype=dt)
1349
+ assert_almost_equal(np.logaddexp2(logxf, logyf), logzf)
1350
+
1351
+ def test_inf(self):
1352
+ inf = np.inf
1353
+ x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] # noqa: E221
1354
+ y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] # noqa: E221
1355
+ z = [inf, inf, inf, -inf, inf, inf, 1, 1]
1356
+ with np.errstate(invalid='raise'):
1357
+ for dt in ['f', 'd', 'g']:
1358
+ logxf = np.array(x, dtype=dt)
1359
+ logyf = np.array(y, dtype=dt)
1360
+ logzf = np.array(z, dtype=dt)
1361
+ assert_equal(np.logaddexp2(logxf, logyf), logzf)
1362
+
1363
+ def test_nan(self):
1364
+ assert_(np.isnan(np.logaddexp2(np.nan, np.inf)))
1365
+ assert_(np.isnan(np.logaddexp2(np.inf, np.nan)))
1366
+ assert_(np.isnan(np.logaddexp2(np.nan, 0)))
1367
+ assert_(np.isnan(np.logaddexp2(0, np.nan)))
1368
+ assert_(np.isnan(np.logaddexp2(np.nan, np.nan)))
1369
+
1370
+ def test_reduce(self):
1371
+ assert_equal(np.logaddexp2.identity, -np.inf)
1372
+ assert_equal(np.logaddexp2.reduce([]), -np.inf)
1373
+ assert_equal(np.logaddexp2.reduce([-np.inf]), -np.inf)
1374
+ assert_equal(np.logaddexp2.reduce([-np.inf, 0]), 0)
1375
+
1376
+
1377
+ class TestLog:
1378
+ def test_log_values(self):
1379
+ x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
1380
+ y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1381
+ for dt in ['f', 'd', 'g']:
1382
+ log2_ = 0.69314718055994530943
1383
+ xf = np.array(x, dtype=dt)
1384
+ yf = np.array(y, dtype=dt) * log2_
1385
+ assert_almost_equal(np.log(xf), yf)
1386
+
1387
+ # test aliasing(issue #17761)
1388
+ x = np.array([2, 0.937500, 3, 0.947500, 1.054697])
1389
+ xf = np.log(x)
1390
+ assert_almost_equal(np.log(x, out=x), xf)
1391
+
1392
+ def test_log_values_maxofdtype(self):
1393
+ # test log() of max for dtype does not raise
1394
+ dtypes = [np.float32, np.float64]
1395
+ # This is failing at least on linux aarch64 (see gh-25460), and on most
1396
+ # other non x86-64 platforms checking `longdouble` isn't too useful as
1397
+ # it's an alias for float64.
1398
+ if platform.machine() == 'x86_64':
1399
+ dtypes += [np.longdouble]
1400
+
1401
+ for dt in dtypes:
1402
+ with np.errstate(all='raise'):
1403
+ x = np.finfo(dt).max
1404
+ np.log(x)
1405
+
1406
+ def test_log_strides(self):
1407
+ np.random.seed(42)
1408
+ strides = np.array([-4, -3, -2, -1, 1, 2, 3, 4])
1409
+ sizes = np.arange(2, 100)
1410
+ for ii in sizes:
1411
+ x_f64 = np.float64(np.random.uniform(low=0.01, high=100.0, size=ii))
1412
+ x_special = x_f64.copy()
1413
+ x_special[3:-1:4] = 1.0
1414
+ y_true = np.log(x_f64)
1415
+ y_special = np.log(x_special)
1416
+ for jj in strides:
1417
+ assert_array_almost_equal_nulp(np.log(x_f64[::jj]), y_true[::jj], nulp=2)
1418
+ assert_array_almost_equal_nulp(np.log(x_special[::jj]), y_special[::jj], nulp=2)
1419
+
1420
+ # Reference values were computed with mpmath, with mp.dps = 200.
1421
+ @pytest.mark.parametrize(
1422
+ 'z, wref',
1423
+ [(1 + 1e-12j, 5e-25 + 1e-12j),
1424
+ (1.000000000000001 + 3e-08j,
1425
+ 1.5602230246251546e-15 + 2.999999999999996e-08j),
1426
+ (0.9999995000000417 + 0.0009999998333333417j,
1427
+ 7.831475869017683e-18 + 0.001j),
1428
+ (0.9999999999999996 + 2.999999999999999e-08j,
1429
+ 5.9107901499372034e-18 + 3e-08j),
1430
+ (0.99995000042 - 0.009999833j,
1431
+ -7.015159763822903e-15 - 0.009999999665816696j)],
1432
+ )
1433
+ def test_log_precision_float64(self, z, wref):
1434
+ w = np.log(z)
1435
+ assert_allclose(w, wref, rtol=1e-15)
1436
+
1437
+ # Reference values were computed with mpmath, with mp.dps = 200.
1438
+ @pytest.mark.parametrize(
1439
+ 'z, wref',
1440
+ [(np.complex64(1.0 + 3e-6j), np.complex64(4.5e-12 + 3e-06j)),
1441
+ (np.complex64(1.0 - 2e-5j), np.complex64(1.9999999e-10 - 2e-5j)),
1442
+ (np.complex64(0.9999999 + 1e-06j),
1443
+ np.complex64(-1.192088e-07 + 1.0000001e-06j))],
1444
+ )
1445
+ def test_log_precision_float32(self, z, wref):
1446
+ w = np.log(z)
1447
+ assert_allclose(w, wref, rtol=1e-6)
1448
+
1449
+
1450
+ class TestExp:
1451
+ def test_exp_values(self):
1452
+ x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
1453
+ y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1454
+ for dt in ['f', 'd', 'g']:
1455
+ log2_ = 0.69314718055994530943
1456
+ xf = np.array(x, dtype=dt)
1457
+ yf = np.array(y, dtype=dt) * log2_
1458
+ assert_almost_equal(np.exp(yf), xf)
1459
+
1460
+ def test_exp_strides(self):
1461
+ np.random.seed(42)
1462
+ strides = np.array([-4, -3, -2, -1, 1, 2, 3, 4])
1463
+ sizes = np.arange(2, 100)
1464
+ for ii in sizes:
1465
+ x_f64 = np.float64(np.random.uniform(low=0.01, high=709.1, size=ii))
1466
+ y_true = np.exp(x_f64)
1467
+ for jj in strides:
1468
+ assert_array_almost_equal_nulp(np.exp(x_f64[::jj]), y_true[::jj], nulp=2)
1469
+
1470
+ class TestSpecialFloats:
1471
+ def test_exp_values(self):
1472
+ with np.errstate(under='raise', over='raise'):
1473
+ x = [np.nan, np.nan, np.inf, 0.]
1474
+ y = [np.nan, -np.nan, np.inf, -np.inf]
1475
+ for dt in ['e', 'f', 'd', 'g']:
1476
+ xf = np.array(x, dtype=dt)
1477
+ yf = np.array(y, dtype=dt)
1478
+ assert_equal(np.exp(yf), xf)
1479
+
1480
+ # See: https://github.com/numpy/numpy/issues/19192
1481
+ @pytest.mark.xfail(
1482
+ _glibc_older_than("2.17"),
1483
+ reason="Older glibc versions may not raise appropriate FP exceptions"
1484
+ )
1485
+ def test_exp_exceptions(self):
1486
+ with np.errstate(over='raise'):
1487
+ assert_raises(FloatingPointError, np.exp, np.float16(11.0899))
1488
+ assert_raises(FloatingPointError, np.exp, np.float32(100.))
1489
+ assert_raises(FloatingPointError, np.exp, np.float32(1E19))
1490
+ assert_raises(FloatingPointError, np.exp, np.float64(800.))
1491
+ assert_raises(FloatingPointError, np.exp, np.float64(1E19))
1492
+
1493
+ with np.errstate(under='raise'):
1494
+ assert_raises(FloatingPointError, np.exp, np.float16(-17.5))
1495
+ assert_raises(FloatingPointError, np.exp, np.float32(-1000.))
1496
+ assert_raises(FloatingPointError, np.exp, np.float32(-1E19))
1497
+ assert_raises(FloatingPointError, np.exp, np.float64(-1000.))
1498
+ assert_raises(FloatingPointError, np.exp, np.float64(-1E19))
1499
+
1500
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1501
+ def test_log_values(self):
1502
+ with np.errstate(all='ignore'):
1503
+ x = [np.nan, np.nan, np.inf, np.nan, -np.inf, np.nan]
1504
+ y = [np.nan, -np.nan, np.inf, -np.inf, 0.0, -1.0]
1505
+ y1p = [np.nan, -np.nan, np.inf, -np.inf, -1.0, -2.0]
1506
+ for dt in ['e', 'f', 'd', 'g']:
1507
+ xf = np.array(x, dtype=dt)
1508
+ yf = np.array(y, dtype=dt)
1509
+ yf1p = np.array(y1p, dtype=dt)
1510
+ assert_equal(np.log(yf), xf)
1511
+ assert_equal(np.log2(yf), xf)
1512
+ assert_equal(np.log10(yf), xf)
1513
+ assert_equal(np.log1p(yf1p), xf)
1514
+
1515
+ with np.errstate(divide='raise'):
1516
+ for dt in ['e', 'f', 'd']:
1517
+ assert_raises(FloatingPointError, np.log,
1518
+ np.array(0.0, dtype=dt))
1519
+ assert_raises(FloatingPointError, np.log2,
1520
+ np.array(0.0, dtype=dt))
1521
+ assert_raises(FloatingPointError, np.log10,
1522
+ np.array(0.0, dtype=dt))
1523
+ assert_raises(FloatingPointError, np.log1p,
1524
+ np.array(-1.0, dtype=dt))
1525
+
1526
+ with np.errstate(invalid='raise'):
1527
+ for dt in ['e', 'f', 'd']:
1528
+ assert_raises(FloatingPointError, np.log,
1529
+ np.array(-np.inf, dtype=dt))
1530
+ assert_raises(FloatingPointError, np.log,
1531
+ np.array(-1.0, dtype=dt))
1532
+ assert_raises(FloatingPointError, np.log2,
1533
+ np.array(-np.inf, dtype=dt))
1534
+ assert_raises(FloatingPointError, np.log2,
1535
+ np.array(-1.0, dtype=dt))
1536
+ assert_raises(FloatingPointError, np.log10,
1537
+ np.array(-np.inf, dtype=dt))
1538
+ assert_raises(FloatingPointError, np.log10,
1539
+ np.array(-1.0, dtype=dt))
1540
+ assert_raises(FloatingPointError, np.log1p,
1541
+ np.array(-np.inf, dtype=dt))
1542
+ assert_raises(FloatingPointError, np.log1p,
1543
+ np.array(-2.0, dtype=dt))
1544
+
1545
+ # See https://github.com/numpy/numpy/issues/18005
1546
+ with assert_no_warnings():
1547
+ a = np.array(1e9, dtype='float32')
1548
+ np.log(a)
1549
+
1550
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1551
+ @pytest.mark.parametrize('dtype', ['e', 'f', 'd', 'g'])
1552
+ def test_sincos_values(self, dtype):
1553
+ with np.errstate(all='ignore'):
1554
+ x = [np.nan, np.nan, np.nan, np.nan]
1555
+ y = [np.nan, -np.nan, np.inf, -np.inf]
1556
+ xf = np.array(x, dtype=dtype)
1557
+ yf = np.array(y, dtype=dtype)
1558
+ assert_equal(np.sin(yf), xf)
1559
+ assert_equal(np.cos(yf), xf)
1560
+
1561
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1562
+ @pytest.mark.xfail(
1563
+ sys.platform.startswith("darwin"),
1564
+ reason="underflow is triggered for scalar 'sin'"
1565
+ )
1566
+ def test_sincos_underflow(self):
1567
+ with np.errstate(under='raise'):
1568
+ underflow_trigger = np.array(
1569
+ float.fromhex("0x1.f37f47a03f82ap-511"),
1570
+ dtype=np.float64
1571
+ )
1572
+ np.sin(underflow_trigger)
1573
+ np.cos(underflow_trigger)
1574
+
1575
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1576
+ @pytest.mark.parametrize('callable', [np.sin, np.cos])
1577
+ @pytest.mark.parametrize('dtype', ['e', 'f', 'd'])
1578
+ @pytest.mark.parametrize('value', [np.inf, -np.inf])
1579
+ def test_sincos_errors(self, callable, dtype, value):
1580
+ with np.errstate(invalid='raise'):
1581
+ assert_raises(FloatingPointError, callable,
1582
+ np.array([value], dtype=dtype))
1583
+
1584
+ @pytest.mark.parametrize('callable', [np.sin, np.cos])
1585
+ @pytest.mark.parametrize('dtype', ['f', 'd'])
1586
+ @pytest.mark.parametrize('stride', [-1, 1, 2, 4, 5])
1587
+ def test_sincos_overlaps(self, callable, dtype, stride):
1588
+ N = 100
1589
+ M = N // abs(stride)
1590
+ rng = np.random.default_rng(42)
1591
+ x = rng.standard_normal(N, dtype)
1592
+ y = callable(x[::stride])
1593
+ callable(x[::stride], out=x[:M])
1594
+ assert_equal(x[:M], y)
1595
+
1596
+ @pytest.mark.parametrize('dt', ['e', 'f', 'd', 'g'])
1597
+ def test_sqrt_values(self, dt):
1598
+ with np.errstate(all='ignore'):
1599
+ x = [np.nan, np.nan, np.inf, np.nan, 0.]
1600
+ y = [np.nan, -np.nan, np.inf, -np.inf, 0.]
1601
+ xf = np.array(x, dtype=dt)
1602
+ yf = np.array(y, dtype=dt)
1603
+ assert_equal(np.sqrt(yf), xf)
1604
+
1605
+ # with np.errstate(invalid='raise'):
1606
+ # assert_raises(
1607
+ # FloatingPointError, np.sqrt, np.array(-100., dtype=dt)
1608
+ # )
1609
+
1610
+ def test_abs_values(self):
1611
+ x = [np.nan, np.nan, np.inf, np.inf, 0., 0., 1.0, 1.0]
1612
+ y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0., -1.0, 1.0]
1613
+ for dt in ['e', 'f', 'd', 'g']:
1614
+ xf = np.array(x, dtype=dt)
1615
+ yf = np.array(y, dtype=dt)
1616
+ assert_equal(np.abs(yf), xf)
1617
+
1618
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1619
+ def test_square_values(self):
1620
+ x = [np.nan, np.nan, np.inf, np.inf]
1621
+ y = [np.nan, -np.nan, np.inf, -np.inf]
1622
+ with np.errstate(all='ignore'):
1623
+ for dt in ['e', 'f', 'd', 'g']:
1624
+ xf = np.array(x, dtype=dt)
1625
+ yf = np.array(y, dtype=dt)
1626
+ assert_equal(np.square(yf), xf)
1627
+
1628
+ with np.errstate(over='raise'):
1629
+ assert_raises(FloatingPointError, np.square,
1630
+ np.array(1E3, dtype='e'))
1631
+ assert_raises(FloatingPointError, np.square,
1632
+ np.array(1E32, dtype='f'))
1633
+ assert_raises(FloatingPointError, np.square,
1634
+ np.array(1E200, dtype='d'))
1635
+
1636
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1637
+ def test_reciprocal_values(self):
1638
+ with np.errstate(all='ignore'):
1639
+ x = [np.nan, np.nan, 0.0, -0.0, np.inf, -np.inf]
1640
+ y = [np.nan, -np.nan, np.inf, -np.inf, 0., -0.]
1641
+ for dt in ['e', 'f', 'd', 'g']:
1642
+ xf = np.array(x, dtype=dt)
1643
+ yf = np.array(y, dtype=dt)
1644
+ assert_equal(np.reciprocal(yf), xf)
1645
+
1646
+ with np.errstate(divide='raise'):
1647
+ for dt in ['e', 'f', 'd', 'g']:
1648
+ assert_raises(FloatingPointError, np.reciprocal,
1649
+ np.array(-0.0, dtype=dt))
1650
+
1651
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1652
+ def test_tan(self):
1653
+ with np.errstate(all='ignore'):
1654
+ in_ = [np.nan, -np.nan, 0.0, -0.0, np.inf, -np.inf]
1655
+ out = [np.nan, np.nan, 0.0, -0.0, np.nan, np.nan]
1656
+ for dt in ['e', 'f', 'd']:
1657
+ in_arr = np.array(in_, dtype=dt)
1658
+ out_arr = np.array(out, dtype=dt)
1659
+ assert_equal(np.tan(in_arr), out_arr)
1660
+
1661
+ with np.errstate(invalid='raise'):
1662
+ for dt in ['e', 'f', 'd']:
1663
+ assert_raises(FloatingPointError, np.tan,
1664
+ np.array(np.inf, dtype=dt))
1665
+ assert_raises(FloatingPointError, np.tan,
1666
+ np.array(-np.inf, dtype=dt))
1667
+
1668
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1669
+ def test_arcsincos(self):
1670
+ with np.errstate(all='ignore'):
1671
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1672
+ out = [np.nan, np.nan, np.nan, np.nan]
1673
+ for dt in ['e', 'f', 'd']:
1674
+ in_arr = np.array(in_, dtype=dt)
1675
+ out_arr = np.array(out, dtype=dt)
1676
+ assert_equal(np.arcsin(in_arr), out_arr)
1677
+ assert_equal(np.arccos(in_arr), out_arr)
1678
+
1679
+ for callable in [np.arcsin, np.arccos]:
1680
+ for value in [np.inf, -np.inf, 2.0, -2.0]:
1681
+ for dt in ['e', 'f', 'd']:
1682
+ with np.errstate(invalid='raise'):
1683
+ assert_raises(FloatingPointError, callable,
1684
+ np.array(value, dtype=dt))
1685
+
1686
+ def test_arctan(self):
1687
+ with np.errstate(all='ignore'):
1688
+ in_ = [np.nan, -np.nan]
1689
+ out = [np.nan, np.nan]
1690
+ for dt in ['e', 'f', 'd']:
1691
+ in_arr = np.array(in_, dtype=dt)
1692
+ out_arr = np.array(out, dtype=dt)
1693
+ assert_equal(np.arctan(in_arr), out_arr)
1694
+
1695
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1696
+ def test_sinh(self):
1697
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1698
+ out = [np.nan, np.nan, np.inf, -np.inf]
1699
+ for dt in ['e', 'f', 'd']:
1700
+ in_arr = np.array(in_, dtype=dt)
1701
+ out_arr = np.array(out, dtype=dt)
1702
+ assert_equal(np.sinh(in_arr), out_arr)
1703
+
1704
+ with np.errstate(over='raise'):
1705
+ assert_raises(FloatingPointError, np.sinh,
1706
+ np.array(12.0, dtype='e'))
1707
+ assert_raises(FloatingPointError, np.sinh,
1708
+ np.array(120.0, dtype='f'))
1709
+ assert_raises(FloatingPointError, np.sinh,
1710
+ np.array(1200.0, dtype='d'))
1711
+
1712
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1713
+ @pytest.mark.skipif('bsd' in sys.platform,
1714
+ reason="fallback implementation may not raise, see gh-2487")
1715
+ def test_cosh(self):
1716
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1717
+ out = [np.nan, np.nan, np.inf, np.inf]
1718
+ for dt in ['e', 'f', 'd']:
1719
+ in_arr = np.array(in_, dtype=dt)
1720
+ out_arr = np.array(out, dtype=dt)
1721
+ assert_equal(np.cosh(in_arr), out_arr)
1722
+
1723
+ with np.errstate(over='raise'):
1724
+ assert_raises(FloatingPointError, np.cosh,
1725
+ np.array(12.0, dtype='e'))
1726
+ assert_raises(FloatingPointError, np.cosh,
1727
+ np.array(120.0, dtype='f'))
1728
+ assert_raises(FloatingPointError, np.cosh,
1729
+ np.array(1200.0, dtype='d'))
1730
+
1731
+ def test_tanh(self):
1732
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1733
+ out = [np.nan, np.nan, 1.0, -1.0]
1734
+ for dt in ['e', 'f', 'd']:
1735
+ in_arr = np.array(in_, dtype=dt)
1736
+ out_arr = np.array(out, dtype=dt)
1737
+ assert_array_max_ulp(np.tanh(in_arr), out_arr, 3)
1738
+
1739
+ def test_arcsinh(self):
1740
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1741
+ out = [np.nan, np.nan, np.inf, -np.inf]
1742
+ for dt in ['e', 'f', 'd']:
1743
+ in_arr = np.array(in_, dtype=dt)
1744
+ out_arr = np.array(out, dtype=dt)
1745
+ assert_equal(np.arcsinh(in_arr), out_arr)
1746
+
1747
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1748
+ def test_arccosh(self):
1749
+ with np.errstate(all='ignore'):
1750
+ in_ = [np.nan, -np.nan, np.inf, -np.inf, 1.0, 0.0]
1751
+ out = [np.nan, np.nan, np.inf, np.nan, 0.0, np.nan]
1752
+ for dt in ['e', 'f', 'd']:
1753
+ in_arr = np.array(in_, dtype=dt)
1754
+ out_arr = np.array(out, dtype=dt)
1755
+ assert_equal(np.arccosh(in_arr), out_arr)
1756
+
1757
+ for value in [0.0, -np.inf]:
1758
+ with np.errstate(invalid='raise'):
1759
+ for dt in ['e', 'f', 'd']:
1760
+ assert_raises(FloatingPointError, np.arccosh,
1761
+ np.array(value, dtype=dt))
1762
+
1763
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1764
+ def test_arctanh(self):
1765
+ with np.errstate(all='ignore'):
1766
+ in_ = [np.nan, -np.nan, np.inf, -np.inf, 1.0, -1.0, 2.0]
1767
+ out = [np.nan, np.nan, np.nan, np.nan, np.inf, -np.inf, np.nan]
1768
+ for dt in ['e', 'f', 'd']:
1769
+ in_arr = np.array(in_, dtype=dt)
1770
+ out_arr = np.array(out, dtype=dt)
1771
+ assert_equal(np.arctanh(in_arr), out_arr)
1772
+
1773
+ for value in [1.01, np.inf, -np.inf, 1.0, -1.0]:
1774
+ with np.errstate(invalid='raise', divide='raise'):
1775
+ for dt in ['e', 'f', 'd']:
1776
+ assert_raises(FloatingPointError, np.arctanh,
1777
+ np.array(value, dtype=dt))
1778
+
1779
+ # Make sure glibc < 2.18 atanh is not used, issue 25087
1780
+ assert np.signbit(np.arctanh(-1j).real)
1781
+
1782
+ # See: https://github.com/numpy/numpy/issues/20448
1783
+ @pytest.mark.xfail(
1784
+ _glibc_older_than("2.17"),
1785
+ reason="Older glibc versions may not raise appropriate FP exceptions"
1786
+ )
1787
+ def test_exp2(self):
1788
+ with np.errstate(all='ignore'):
1789
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1790
+ out = [np.nan, np.nan, np.inf, 0.0]
1791
+ for dt in ['e', 'f', 'd']:
1792
+ in_arr = np.array(in_, dtype=dt)
1793
+ out_arr = np.array(out, dtype=dt)
1794
+ assert_equal(np.exp2(in_arr), out_arr)
1795
+
1796
+ for value in [2000.0, -2000.0]:
1797
+ with np.errstate(over='raise', under='raise'):
1798
+ for dt in ['e', 'f', 'd']:
1799
+ assert_raises(FloatingPointError, np.exp2,
1800
+ np.array(value, dtype=dt))
1801
+
1802
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1803
+ def test_expm1(self):
1804
+ with np.errstate(all='ignore'):
1805
+ in_ = [np.nan, -np.nan, np.inf, -np.inf]
1806
+ out = [np.nan, np.nan, np.inf, -1.0]
1807
+ for dt in ['e', 'f', 'd']:
1808
+ in_arr = np.array(in_, dtype=dt)
1809
+ out_arr = np.array(out, dtype=dt)
1810
+ assert_equal(np.expm1(in_arr), out_arr)
1811
+
1812
+ for value in [200.0, 2000.0]:
1813
+ with np.errstate(over='raise'):
1814
+ for dt in ['e', 'f']:
1815
+ assert_raises(FloatingPointError, np.expm1,
1816
+ np.array(value, dtype=dt))
1817
+
1818
+ # test to ensure no spurious FP exceptions are raised due to SIMD
1819
+ INF_INVALID_ERR = [
1820
+ np.cos, np.sin, np.tan, np.arccos, np.arcsin, np.spacing, np.arctanh
1821
+ ]
1822
+ NEG_INVALID_ERR = [
1823
+ np.log, np.log2, np.log10, np.log1p, np.sqrt, np.arccosh,
1824
+ np.arctanh
1825
+ ]
1826
+ ONE_INVALID_ERR = [
1827
+ np.arctanh,
1828
+ ]
1829
+ LTONE_INVALID_ERR = [
1830
+ np.arccosh,
1831
+ ]
1832
+ BYZERO_ERR = [
1833
+ np.log, np.log2, np.log10, np.reciprocal, np.arccosh
1834
+ ]
1835
+
1836
+ @pytest.mark.parametrize("ufunc", UFUNCS_UNARY_FP)
1837
+ @pytest.mark.parametrize("dtype", ('e', 'f', 'd'))
1838
+ @pytest.mark.parametrize("data, escape", (
1839
+ ([0.03], LTONE_INVALID_ERR),
1840
+ ([0.03] * 32, LTONE_INVALID_ERR),
1841
+ # neg
1842
+ ([-1.0], NEG_INVALID_ERR),
1843
+ ([-1.0] * 32, NEG_INVALID_ERR),
1844
+ # flat
1845
+ ([1.0], ONE_INVALID_ERR),
1846
+ ([1.0] * 32, ONE_INVALID_ERR),
1847
+ # zero
1848
+ ([0.0], BYZERO_ERR),
1849
+ ([0.0] * 32, BYZERO_ERR),
1850
+ ([-0.0], BYZERO_ERR),
1851
+ ([-0.0] * 32, BYZERO_ERR),
1852
+ # nan
1853
+ ([0.5, 0.5, 0.5, np.nan], LTONE_INVALID_ERR),
1854
+ ([0.5, 0.5, 0.5, np.nan] * 32, LTONE_INVALID_ERR),
1855
+ ([np.nan, 1.0, 1.0, 1.0], ONE_INVALID_ERR),
1856
+ ([np.nan, 1.0, 1.0, 1.0] * 32, ONE_INVALID_ERR),
1857
+ ([np.nan], []),
1858
+ ([np.nan] * 32, []),
1859
+ # inf
1860
+ ([0.5, 0.5, 0.5, np.inf], INF_INVALID_ERR + LTONE_INVALID_ERR),
1861
+ ([0.5, 0.5, 0.5, np.inf] * 32, INF_INVALID_ERR + LTONE_INVALID_ERR),
1862
+ ([np.inf, 1.0, 1.0, 1.0], INF_INVALID_ERR),
1863
+ ([np.inf, 1.0, 1.0, 1.0] * 32, INF_INVALID_ERR),
1864
+ ([np.inf], INF_INVALID_ERR),
1865
+ ([np.inf] * 32, INF_INVALID_ERR),
1866
+ # ninf
1867
+ ([0.5, 0.5, 0.5, -np.inf],
1868
+ NEG_INVALID_ERR + INF_INVALID_ERR + LTONE_INVALID_ERR),
1869
+ ([0.5, 0.5, 0.5, -np.inf] * 32,
1870
+ NEG_INVALID_ERR + INF_INVALID_ERR + LTONE_INVALID_ERR),
1871
+ ([-np.inf, 1.0, 1.0, 1.0], NEG_INVALID_ERR + INF_INVALID_ERR),
1872
+ ([-np.inf, 1.0, 1.0, 1.0] * 32, NEG_INVALID_ERR + INF_INVALID_ERR),
1873
+ ([-np.inf], NEG_INVALID_ERR + INF_INVALID_ERR),
1874
+ ([-np.inf] * 32, NEG_INVALID_ERR + INF_INVALID_ERR),
1875
+ ))
1876
+ def test_unary_spurious_fpexception(self, ufunc, dtype, data, escape):
1877
+ if escape and ufunc in escape:
1878
+ return
1879
+ # FIXME: NAN raises FP invalid exception:
1880
+ # - ceil/float16 on MSVC:32-bit
1881
+ # - spacing/float16 on almost all platforms
1882
+ # - spacing all floats on MSVC vs2022
1883
+ if ufunc == np.spacing:
1884
+ return
1885
+ if ufunc == np.ceil and dtype == 'e':
1886
+ return
1887
+ array = np.array(data, dtype=dtype)
1888
+ with assert_no_warnings():
1889
+ ufunc(array)
1890
+
1891
+ @pytest.mark.parametrize("dtype", ('e', 'f', 'd'))
1892
+ def test_divide_spurious_fpexception(self, dtype):
1893
+ dt = np.dtype(dtype)
1894
+ dt_info = np.finfo(dt)
1895
+ subnorm = dt_info.smallest_subnormal
1896
+ # Verify a bug fix caused due to filling the remaining lanes of the
1897
+ # partially loaded dividend SIMD vector with ones, which leads to
1898
+ # raising an overflow warning when the divisor is denormal.
1899
+ # see https://github.com/numpy/numpy/issues/25097
1900
+ with assert_no_warnings():
1901
+ np.zeros(128 + 1, dtype=dt) / subnorm
1902
+
1903
+ class TestFPClass:
1904
+ @pytest.mark.parametrize("stride", [-5, -4, -3, -2, -1, 1,
1905
+ 2, 4, 5, 6, 7, 8, 9, 10])
1906
+ def test_fpclass(self, stride):
1907
+ arr_f64 = np.array([np.nan, -np.nan, np.inf, -np.inf, -1.0, 1.0, -0.0, 0.0, 2.2251e-308, -2.2251e-308], dtype='d')
1908
+ arr_f32 = np.array([np.nan, -np.nan, np.inf, -np.inf, -1.0, 1.0, -0.0, 0.0, 1.4013e-045, -1.4013e-045], dtype='f')
1909
+ nan = np.array([True, True, False, False, False, False, False, False, False, False]) # noqa: E221
1910
+ inf = np.array([False, False, True, True, False, False, False, False, False, False]) # noqa: E221
1911
+ sign = np.array([False, True, False, True, True, False, True, False, False, True]) # noqa: E221
1912
+ finite = np.array([False, False, False, False, True, True, True, True, True, True]) # noqa: E221
1913
+ assert_equal(np.isnan(arr_f32[::stride]), nan[::stride])
1914
+ assert_equal(np.isnan(arr_f64[::stride]), nan[::stride])
1915
+ assert_equal(np.isinf(arr_f32[::stride]), inf[::stride])
1916
+ assert_equal(np.isinf(arr_f64[::stride]), inf[::stride])
1917
+ if platform.machine() == 'riscv64':
1918
+ # On RISC-V, many operations that produce NaNs, such as converting
1919
+ # a -NaN from f64 to f32, return a canonical NaN. The canonical
1920
+ # NaNs are always positive. See section 11.3 NaN Generation and
1921
+ # Propagation of the RISC-V Unprivileged ISA for more details.
1922
+ # We disable the sign test on riscv64 for -np.nan as we
1923
+ # cannot assume that its sign will be honoured in these tests.
1924
+ arr_f64_rv = np.copy(arr_f64)
1925
+ arr_f32_rv = np.copy(arr_f32)
1926
+ arr_f64_rv[1] = -1.0
1927
+ arr_f32_rv[1] = -1.0
1928
+ assert_equal(np.signbit(arr_f32_rv[::stride]), sign[::stride])
1929
+ assert_equal(np.signbit(arr_f64_rv[::stride]), sign[::stride])
1930
+ else:
1931
+ assert_equal(np.signbit(arr_f32[::stride]), sign[::stride])
1932
+ assert_equal(np.signbit(arr_f64[::stride]), sign[::stride])
1933
+ assert_equal(np.isfinite(arr_f32[::stride]), finite[::stride])
1934
+ assert_equal(np.isfinite(arr_f64[::stride]), finite[::stride])
1935
+
1936
+ @pytest.mark.parametrize("dtype", ['d', 'f'])
1937
+ def test_fp_noncontiguous(self, dtype):
1938
+ data = np.array([np.nan, -np.nan, np.inf, -np.inf, -1.0,
1939
+ 1.0, -0.0, 0.0, 2.2251e-308,
1940
+ -2.2251e-308], dtype=dtype)
1941
+ nan = np.array([True, True, False, False, False, False,
1942
+ False, False, False, False])
1943
+ inf = np.array([False, False, True, True, False, False,
1944
+ False, False, False, False])
1945
+ sign = np.array([False, True, False, True, True, False,
1946
+ True, False, False, True])
1947
+ finite = np.array([False, False, False, False, True, True,
1948
+ True, True, True, True])
1949
+ out = np.ndarray(data.shape, dtype='bool')
1950
+ ncontig_in = data[1::3]
1951
+ ncontig_out = out[1::3]
1952
+ contig_in = np.array(ncontig_in)
1953
+
1954
+ if platform.machine() == 'riscv64':
1955
+ # Disable the -np.nan signbit tests on riscv64. See comments in
1956
+ # test_fpclass for more details.
1957
+ data_rv = np.copy(data)
1958
+ data_rv[1] = -1.0
1959
+ ncontig_sign_in = data_rv[1::3]
1960
+ contig_sign_in = np.array(ncontig_sign_in)
1961
+ else:
1962
+ ncontig_sign_in = ncontig_in
1963
+ contig_sign_in = contig_in
1964
+
1965
+ assert_equal(ncontig_in.flags.c_contiguous, False)
1966
+ assert_equal(ncontig_out.flags.c_contiguous, False)
1967
+ assert_equal(contig_in.flags.c_contiguous, True)
1968
+ assert_equal(ncontig_sign_in.flags.c_contiguous, False)
1969
+ assert_equal(contig_sign_in.flags.c_contiguous, True)
1970
+ # ncontig in, ncontig out
1971
+ assert_equal(np.isnan(ncontig_in, out=ncontig_out), nan[1::3])
1972
+ assert_equal(np.isinf(ncontig_in, out=ncontig_out), inf[1::3])
1973
+ assert_equal(np.signbit(ncontig_sign_in, out=ncontig_out), sign[1::3])
1974
+ assert_equal(np.isfinite(ncontig_in, out=ncontig_out), finite[1::3])
1975
+ # contig in, ncontig out
1976
+ assert_equal(np.isnan(contig_in, out=ncontig_out), nan[1::3])
1977
+ assert_equal(np.isinf(contig_in, out=ncontig_out), inf[1::3])
1978
+ assert_equal(np.signbit(contig_sign_in, out=ncontig_out), sign[1::3])
1979
+ assert_equal(np.isfinite(contig_in, out=ncontig_out), finite[1::3])
1980
+ # ncontig in, contig out
1981
+ assert_equal(np.isnan(ncontig_in), nan[1::3])
1982
+ assert_equal(np.isinf(ncontig_in), inf[1::3])
1983
+ assert_equal(np.signbit(ncontig_sign_in), sign[1::3])
1984
+ assert_equal(np.isfinite(ncontig_in), finite[1::3])
1985
+ # contig in, contig out, nd stride
1986
+ data_split = np.array(np.array_split(data, 2))
1987
+ nan_split = np.array(np.array_split(nan, 2))
1988
+ inf_split = np.array(np.array_split(inf, 2))
1989
+ sign_split = np.array(np.array_split(sign, 2))
1990
+ finite_split = np.array(np.array_split(finite, 2))
1991
+ assert_equal(np.isnan(data_split), nan_split)
1992
+ assert_equal(np.isinf(data_split), inf_split)
1993
+ if platform.machine() == 'riscv64':
1994
+ data_split_rv = np.array(np.array_split(data_rv, 2))
1995
+ assert_equal(np.signbit(data_split_rv), sign_split)
1996
+ else:
1997
+ assert_equal(np.signbit(data_split), sign_split)
1998
+ assert_equal(np.isfinite(data_split), finite_split)
1999
+
2000
+ class TestLDExp:
2001
+ @pytest.mark.parametrize("stride", [-4, -2, -1, 1, 2, 4])
2002
+ @pytest.mark.parametrize("dtype", ['f', 'd'])
2003
+ def test_ldexp(self, dtype, stride):
2004
+ mant = np.array([0.125, 0.25, 0.5, 1., 1., 2., 4., 8.], dtype=dtype)
2005
+ exp = np.array([3, 2, 1, 0, 0, -1, -2, -3], dtype='i')
2006
+ out = np.zeros(8, dtype=dtype)
2007
+ assert_equal(np.ldexp(mant[::stride], exp[::stride], out=out[::stride]), np.ones(8, dtype=dtype)[::stride])
2008
+ assert_equal(out[::stride], np.ones(8, dtype=dtype)[::stride])
2009
+
2010
+ class TestFRExp:
2011
+ @pytest.mark.parametrize("stride", [-4, -2, -1, 1, 2, 4])
2012
+ @pytest.mark.parametrize("dtype", ['f', 'd'])
2013
+ @pytest.mark.skipif(not sys.platform.startswith('linux'),
2014
+ reason="np.frexp gives different answers for NAN/INF on windows and linux")
2015
+ @pytest.mark.xfail(IS_MUSL, reason="gh23049")
2016
+ def test_frexp(self, dtype, stride):
2017
+ arr = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 1.0, -1.0], dtype=dtype)
2018
+ mant_true = np.array([np.nan, np.nan, np.inf, -np.inf, 0.0, -0.0, 0.5, -0.5], dtype=dtype)
2019
+ exp_true = np.array([0, 0, 0, 0, 0, 0, 1, 1], dtype='i')
2020
+ out_mant = np.ones(8, dtype=dtype)
2021
+ out_exp = 2 * np.ones(8, dtype='i')
2022
+ mant, exp = np.frexp(arr[::stride], out=(out_mant[::stride], out_exp[::stride]))
2023
+ assert_equal(mant_true[::stride], mant)
2024
+ assert_equal(exp_true[::stride], exp)
2025
+ assert_equal(out_mant[::stride], mant_true[::stride])
2026
+ assert_equal(out_exp[::stride], exp_true[::stride])
2027
+
2028
+
2029
+ # func : [maxulperror, low, high]
2030
+ avx_ufuncs = {'sqrt' : [1, 0., 100.], # noqa: E203
2031
+ 'absolute' : [0, -100., 100.], # noqa: E203
2032
+ 'reciprocal' : [1, 1., 100.], # noqa: E203
2033
+ 'square' : [1, -100., 100.], # noqa: E203
2034
+ 'rint' : [0, -100., 100.], # noqa: E203
2035
+ 'floor' : [0, -100., 100.], # noqa: E203
2036
+ 'ceil' : [0, -100., 100.], # noqa: E203
2037
+ 'trunc' : [0, -100., 100.]} # noqa: E203
2038
+
2039
+ class TestAVXUfuncs:
2040
+ def test_avx_based_ufunc(self):
2041
+ strides = np.array([-4, -3, -2, -1, 1, 2, 3, 4])
2042
+ np.random.seed(42)
2043
+ for func, prop in avx_ufuncs.items():
2044
+ maxulperr = prop[0]
2045
+ minval = prop[1]
2046
+ maxval = prop[2]
2047
+ # various array sizes to ensure masking in AVX is tested
2048
+ for size in range(1, 32):
2049
+ myfunc = getattr(np, func)
2050
+ x_f32 = np.random.uniform(low=minval, high=maxval,
2051
+ size=size).astype(np.float32)
2052
+ x_f64 = x_f32.astype(np.float64)
2053
+ x_f128 = x_f32.astype(np.longdouble)
2054
+ y_true128 = myfunc(x_f128)
2055
+ if maxulperr == 0:
2056
+ assert_equal(myfunc(x_f32), y_true128.astype(np.float32))
2057
+ assert_equal(myfunc(x_f64), y_true128.astype(np.float64))
2058
+ else:
2059
+ assert_array_max_ulp(myfunc(x_f32),
2060
+ y_true128.astype(np.float32),
2061
+ maxulp=maxulperr)
2062
+ assert_array_max_ulp(myfunc(x_f64),
2063
+ y_true128.astype(np.float64),
2064
+ maxulp=maxulperr)
2065
+ # various strides to test gather instruction
2066
+ if size > 1:
2067
+ y_true32 = myfunc(x_f32)
2068
+ y_true64 = myfunc(x_f64)
2069
+ for jj in strides:
2070
+ assert_equal(myfunc(x_f64[::jj]), y_true64[::jj])
2071
+ assert_equal(myfunc(x_f32[::jj]), y_true32[::jj])
2072
+
2073
+ class TestAVXFloat32Transcendental:
2074
+ def test_exp_float32(self):
2075
+ np.random.seed(42)
2076
+ x_f32 = np.float32(np.random.uniform(low=0.0, high=88.1, size=1000000))
2077
+ x_f64 = np.float64(x_f32)
2078
+ assert_array_max_ulp(np.exp(x_f32), np.float32(np.exp(x_f64)), maxulp=3)
2079
+
2080
+ def test_log_float32(self):
2081
+ np.random.seed(42)
2082
+ x_f32 = np.float32(np.random.uniform(low=0.0, high=1000, size=1000000))
2083
+ x_f64 = np.float64(x_f32)
2084
+ assert_array_max_ulp(np.log(x_f32), np.float32(np.log(x_f64)), maxulp=4)
2085
+
2086
+ def test_sincos_float32(self):
2087
+ np.random.seed(42)
2088
+ N = 1000000
2089
+ M = np.int_(N / 20)
2090
+ index = np.random.randint(low=0, high=N, size=M)
2091
+ x_f32 = np.float32(np.random.uniform(low=-100., high=100., size=N))
2092
+ if not _glibc_older_than("2.17"):
2093
+ # test coverage for elements > 117435.992f for which glibc is used
2094
+ # this is known to be problematic on old glibc, so skip it there
2095
+ x_f32[index] = np.float32(10E+10 * np.random.rand(M))
2096
+ x_f64 = np.float64(x_f32)
2097
+ assert_array_max_ulp(np.sin(x_f32), np.float32(np.sin(x_f64)), maxulp=2)
2098
+ assert_array_max_ulp(np.cos(x_f32), np.float32(np.cos(x_f64)), maxulp=2)
2099
+ # test aliasing(issue #17761)
2100
+ tx_f32 = x_f32.copy()
2101
+ assert_array_max_ulp(np.sin(x_f32, out=x_f32), np.float32(np.sin(x_f64)), maxulp=2)
2102
+ assert_array_max_ulp(np.cos(tx_f32, out=tx_f32), np.float32(np.cos(x_f64)), maxulp=2)
2103
+
2104
+ def test_strided_float32(self):
2105
+ np.random.seed(42)
2106
+ strides = np.array([-4, -3, -2, -1, 1, 2, 3, 4])
2107
+ sizes = np.arange(2, 100)
2108
+ for ii in sizes:
2109
+ x_f32 = np.float32(np.random.uniform(low=0.01, high=88.1, size=ii))
2110
+ x_f32_large = x_f32.copy()
2111
+ x_f32_large[3:-1:4] = 120000.0
2112
+ exp_true = np.exp(x_f32)
2113
+ log_true = np.log(x_f32)
2114
+ sin_true = np.sin(x_f32_large)
2115
+ cos_true = np.cos(x_f32_large)
2116
+ for jj in strides:
2117
+ assert_array_almost_equal_nulp(np.exp(x_f32[::jj]), exp_true[::jj], nulp=2)
2118
+ assert_array_almost_equal_nulp(np.log(x_f32[::jj]), log_true[::jj], nulp=2)
2119
+ assert_array_almost_equal_nulp(np.sin(x_f32_large[::jj]), sin_true[::jj], nulp=2)
2120
+ assert_array_almost_equal_nulp(np.cos(x_f32_large[::jj]), cos_true[::jj], nulp=2)
2121
+
2122
+ class TestLogAddExp(_FilterInvalids):
2123
+ def test_logaddexp_values(self):
2124
+ x = [1, 2, 3, 4, 5]
2125
+ y = [5, 4, 3, 2, 1]
2126
+ z = [6, 6, 6, 6, 6]
2127
+ for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
2128
+ xf = np.log(np.array(x, dtype=dt))
2129
+ yf = np.log(np.array(y, dtype=dt))
2130
+ zf = np.log(np.array(z, dtype=dt))
2131
+ assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_)
2132
+
2133
+ def test_logaddexp_range(self):
2134
+ x = [1000000, -1000000, 1000200, -1000200]
2135
+ y = [1000200, -1000200, 1000000, -1000000]
2136
+ z = [1000200, -1000000, 1000200, -1000000]
2137
+ for dt in ['f', 'd', 'g']:
2138
+ logxf = np.array(x, dtype=dt)
2139
+ logyf = np.array(y, dtype=dt)
2140
+ logzf = np.array(z, dtype=dt)
2141
+ assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
2142
+
2143
+ def test_inf(self):
2144
+ inf = np.inf
2145
+ x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] # noqa: E221
2146
+ y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] # noqa: E221
2147
+ z = [inf, inf, inf, -inf, inf, inf, 1, 1]
2148
+ with np.errstate(invalid='raise'):
2149
+ for dt in ['f', 'd', 'g']:
2150
+ logxf = np.array(x, dtype=dt)
2151
+ logyf = np.array(y, dtype=dt)
2152
+ logzf = np.array(z, dtype=dt)
2153
+ assert_equal(np.logaddexp(logxf, logyf), logzf)
2154
+
2155
+ def test_nan(self):
2156
+ assert_(np.isnan(np.logaddexp(np.nan, np.inf)))
2157
+ assert_(np.isnan(np.logaddexp(np.inf, np.nan)))
2158
+ assert_(np.isnan(np.logaddexp(np.nan, 0)))
2159
+ assert_(np.isnan(np.logaddexp(0, np.nan)))
2160
+ assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
2161
+
2162
+ def test_reduce(self):
2163
+ assert_equal(np.logaddexp.identity, -np.inf)
2164
+ assert_equal(np.logaddexp.reduce([]), -np.inf)
2165
+
2166
+
2167
+ class TestLog1p:
2168
+ def test_log1p(self):
2169
+ assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))
2170
+ assert_almost_equal(ncu.log1p(1e-6), ncu.log(1 + 1e-6))
2171
+
2172
+ def test_special(self):
2173
+ with np.errstate(invalid="ignore", divide="ignore"):
2174
+ assert_equal(ncu.log1p(np.nan), np.nan)
2175
+ assert_equal(ncu.log1p(np.inf), np.inf)
2176
+ assert_equal(ncu.log1p(-1.), -np.inf)
2177
+ assert_equal(ncu.log1p(-2.), np.nan)
2178
+ assert_equal(ncu.log1p(-np.inf), np.nan)
2179
+
2180
+
2181
+ class TestExpm1:
2182
+ def test_expm1(self):
2183
+ assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2) - 1)
2184
+ assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6) - 1)
2185
+
2186
+ def test_special(self):
2187
+ assert_equal(ncu.expm1(np.inf), np.inf)
2188
+ assert_equal(ncu.expm1(0.), 0.)
2189
+ assert_equal(ncu.expm1(-0.), -0.)
2190
+ assert_equal(ncu.expm1(np.inf), np.inf)
2191
+ assert_equal(ncu.expm1(-np.inf), -1.)
2192
+
2193
+ def test_complex(self):
2194
+ x = np.asarray(1e-12)
2195
+ assert_allclose(x, ncu.expm1(x))
2196
+ x = x.astype(np.complex128)
2197
+ assert_allclose(x, ncu.expm1(x))
2198
+
2199
+
2200
+ class TestHypot:
2201
+ def test_simple(self):
2202
+ assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2))
2203
+ assert_almost_equal(ncu.hypot(0, 0), 0)
2204
+
2205
+ def test_reduce(self):
2206
+ assert_almost_equal(ncu.hypot.reduce([3.0, 4.0]), 5.0)
2207
+ assert_almost_equal(ncu.hypot.reduce([3.0, 4.0, 0]), 5.0)
2208
+ assert_almost_equal(ncu.hypot.reduce([9.0, 12.0, 20.0]), 25.0)
2209
+ assert_equal(ncu.hypot.reduce([]), 0.0)
2210
+
2211
+
2212
+ def assert_hypot_isnan(x, y):
2213
+ with np.errstate(invalid='ignore'):
2214
+ assert_(np.isnan(ncu.hypot(x, y)),
2215
+ f"hypot({x}, {y}) is {ncu.hypot(x, y)}, not nan")
2216
+
2217
+
2218
+ def assert_hypot_isinf(x, y):
2219
+ with np.errstate(invalid='ignore'):
2220
+ assert_(np.isinf(ncu.hypot(x, y)),
2221
+ f"hypot({x}, {y}) is {ncu.hypot(x, y)}, not inf")
2222
+
2223
+
2224
+ class TestHypotSpecialValues:
2225
+ def test_nan_outputs(self):
2226
+ assert_hypot_isnan(np.nan, np.nan)
2227
+ assert_hypot_isnan(np.nan, 1)
2228
+
2229
+ def test_nan_outputs2(self):
2230
+ assert_hypot_isinf(np.nan, np.inf)
2231
+ assert_hypot_isinf(np.inf, np.nan)
2232
+ assert_hypot_isinf(np.inf, 0)
2233
+ assert_hypot_isinf(0, np.inf)
2234
+ assert_hypot_isinf(np.inf, np.inf)
2235
+ assert_hypot_isinf(np.inf, 23.0)
2236
+
2237
+ def test_no_fpe(self):
2238
+ assert_no_warnings(ncu.hypot, np.inf, 0)
2239
+
2240
+
2241
+ def assert_arctan2_isnan(x, y):
2242
+ assert_(np.isnan(ncu.arctan2(x, y)), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not nan")
2243
+
2244
+
2245
+ def assert_arctan2_ispinf(x, y):
2246
+ assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not +inf")
2247
+
2248
+
2249
+ def assert_arctan2_isninf(x, y):
2250
+ assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not -inf")
2251
+
2252
+
2253
+ def assert_arctan2_ispzero(x, y):
2254
+ assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not +0")
2255
+
2256
+
2257
+ def assert_arctan2_isnzero(x, y):
2258
+ assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not -0")
2259
+
2260
+
2261
+ class TestArctan2SpecialValues:
2262
+ def test_one_one(self):
2263
+ # atan2(1, 1) returns pi/4.
2264
+ assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi)
2265
+ assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi)
2266
+ assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi)
2267
+
2268
+ def test_zero_nzero(self):
2269
+ # atan2(+-0, -0) returns +-pi.
2270
+ assert_almost_equal(ncu.arctan2(ncu.PZERO, ncu.NZERO), np.pi)
2271
+ assert_almost_equal(ncu.arctan2(ncu.NZERO, ncu.NZERO), -np.pi)
2272
+
2273
+ def test_zero_pzero(self):
2274
+ # atan2(+-0, +0) returns +-0.
2275
+ assert_arctan2_ispzero(ncu.PZERO, ncu.PZERO)
2276
+ assert_arctan2_isnzero(ncu.NZERO, ncu.PZERO)
2277
+
2278
+ def test_zero_negative(self):
2279
+ # atan2(+-0, x) returns +-pi for x < 0.
2280
+ assert_almost_equal(ncu.arctan2(ncu.PZERO, -1), np.pi)
2281
+ assert_almost_equal(ncu.arctan2(ncu.NZERO, -1), -np.pi)
2282
+
2283
+ def test_zero_positive(self):
2284
+ # atan2(+-0, x) returns +-0 for x > 0.
2285
+ assert_arctan2_ispzero(ncu.PZERO, 1)
2286
+ assert_arctan2_isnzero(ncu.NZERO, 1)
2287
+
2288
+ def test_positive_zero(self):
2289
+ # atan2(y, +-0) returns +pi/2 for y > 0.
2290
+ assert_almost_equal(ncu.arctan2(1, ncu.PZERO), 0.5 * np.pi)
2291
+ assert_almost_equal(ncu.arctan2(1, ncu.NZERO), 0.5 * np.pi)
2292
+
2293
+ def test_negative_zero(self):
2294
+ # atan2(y, +-0) returns -pi/2 for y < 0.
2295
+ assert_almost_equal(ncu.arctan2(-1, ncu.PZERO), -0.5 * np.pi)
2296
+ assert_almost_equal(ncu.arctan2(-1, ncu.NZERO), -0.5 * np.pi)
2297
+
2298
+ def test_any_ninf(self):
2299
+ # atan2(+-y, -infinity) returns +-pi for finite y > 0.
2300
+ assert_almost_equal(ncu.arctan2(1, -np.inf), np.pi)
2301
+ assert_almost_equal(ncu.arctan2(-1, -np.inf), -np.pi)
2302
+
2303
+ def test_any_pinf(self):
2304
+ # atan2(+-y, +infinity) returns +-0 for finite y > 0.
2305
+ assert_arctan2_ispzero(1, np.inf)
2306
+ assert_arctan2_isnzero(-1, np.inf)
2307
+
2308
+ def test_inf_any(self):
2309
+ # atan2(+-infinity, x) returns +-pi/2 for finite x.
2310
+ assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi)
2311
+ assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi)
2312
+
2313
+ def test_inf_ninf(self):
2314
+ # atan2(+-infinity, -infinity) returns +-3*pi/4.
2315
+ assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi)
2316
+ assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi)
2317
+
2318
+ def test_inf_pinf(self):
2319
+ # atan2(+-infinity, +infinity) returns +-pi/4.
2320
+ assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi)
2321
+ assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi)
2322
+
2323
+ def test_nan_any(self):
2324
+ # atan2(nan, x) returns nan for any x, including inf
2325
+ assert_arctan2_isnan(np.nan, np.inf)
2326
+ assert_arctan2_isnan(np.inf, np.nan)
2327
+ assert_arctan2_isnan(np.nan, np.nan)
2328
+
2329
+
2330
+ class TestLdexp:
2331
+ def _check_ldexp(self, tp):
2332
+ assert_almost_equal(ncu.ldexp(np.array(2., np.float32),
2333
+ np.array(3, tp)), 16.)
2334
+ assert_almost_equal(ncu.ldexp(np.array(2., np.float64),
2335
+ np.array(3, tp)), 16.)
2336
+ assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble),
2337
+ np.array(3, tp)), 16.)
2338
+
2339
+ def test_ldexp(self):
2340
+ # The default Python int type should work
2341
+ assert_almost_equal(ncu.ldexp(2., 3), 16.)
2342
+ # The following int types should all be accepted
2343
+ self._check_ldexp(np.int8)
2344
+ self._check_ldexp(np.int16)
2345
+ self._check_ldexp(np.int32)
2346
+ self._check_ldexp('i')
2347
+ self._check_ldexp('l')
2348
+
2349
+ def test_ldexp_overflow(self):
2350
+ # silence warning emitted on overflow
2351
+ with np.errstate(over="ignore"):
2352
+ imax = np.iinfo(np.dtype('l')).max
2353
+ imin = np.iinfo(np.dtype('l')).min
2354
+ assert_equal(ncu.ldexp(2., imax), np.inf)
2355
+ assert_equal(ncu.ldexp(2., imin), 0)
2356
+
2357
+
2358
+ class TestMaximum(_FilterInvalids):
2359
+ def test_reduce(self):
2360
+ dflt = np.typecodes['AllFloat']
2361
+ dint = np.typecodes['AllInteger']
2362
+ seq1 = np.arange(11)
2363
+ seq2 = seq1[::-1]
2364
+ func = np.maximum.reduce
2365
+ for dt in dint:
2366
+ tmp1 = seq1.astype(dt)
2367
+ tmp2 = seq2.astype(dt)
2368
+ assert_equal(func(tmp1), 10)
2369
+ assert_equal(func(tmp2), 10)
2370
+ for dt in dflt:
2371
+ tmp1 = seq1.astype(dt)
2372
+ tmp2 = seq2.astype(dt)
2373
+ assert_equal(func(tmp1), 10)
2374
+ assert_equal(func(tmp2), 10)
2375
+ tmp1[::2] = np.nan
2376
+ tmp2[::2] = np.nan
2377
+ assert_equal(func(tmp1), np.nan)
2378
+ assert_equal(func(tmp2), np.nan)
2379
+
2380
+ def test_reduce_complex(self):
2381
+ assert_equal(np.maximum.reduce([1, 2j]), 1)
2382
+ assert_equal(np.maximum.reduce([1 + 3j, 2j]), 1 + 3j)
2383
+
2384
+ def test_float_nans(self):
2385
+ nan = np.nan
2386
+ arg1 = np.array([0, nan, nan])
2387
+ arg2 = np.array([nan, 0, nan])
2388
+ out = np.array([nan, nan, nan])
2389
+ assert_equal(np.maximum(arg1, arg2), out)
2390
+
2391
+ def test_object_nans(self):
2392
+ # Multiple checks to give this a chance to
2393
+ # fail if cmp is used instead of rich compare.
2394
+ # Failure cannot be guaranteed.
2395
+ for i in range(1):
2396
+ x = np.array(float('nan'), object)
2397
+ y = 1.0
2398
+ z = np.array(float('nan'), object)
2399
+ assert_(np.maximum(x, y) == 1.0)
2400
+ assert_(np.maximum(z, y) == 1.0)
2401
+
2402
+ def test_complex_nans(self):
2403
+ nan = np.nan
2404
+ for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
2405
+ arg1 = np.array([0, cnan, cnan], dtype=complex)
2406
+ arg2 = np.array([cnan, 0, cnan], dtype=complex)
2407
+ out = np.array([nan, nan, nan], dtype=complex)
2408
+ assert_equal(np.maximum(arg1, arg2), out)
2409
+
2410
+ def test_object_array(self):
2411
+ arg1 = np.arange(5, dtype=object)
2412
+ arg2 = arg1 + 1
2413
+ assert_equal(np.maximum(arg1, arg2), arg2)
2414
+
2415
+ def test_strided_array(self):
2416
+ arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
2417
+ arr2 = np.array([-2.0, -1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0]) # noqa: E221
2418
+ maxtrue = np.array([-2.0, 1.0, np.nan, 1.0, np.nan, np.nan, np.inf, -3.0])
2419
+ out = np.ones(8)
2420
+ out_maxtrue = np.array([-2.0, 1.0, 1.0, 10.0, 1.0, 1.0, np.nan, 1.0])
2421
+ assert_equal(np.maximum(arr1, arr2), maxtrue)
2422
+ assert_equal(np.maximum(arr1[::2], arr2[::2]), maxtrue[::2])
2423
+ assert_equal(np.maximum(arr1[:4:], arr2[::2]), np.array([-2.0, np.nan, 10.0, 1.0]))
2424
+ assert_equal(np.maximum(arr1[::3], arr2[:3:]), np.array([-2.0, 0.0, np.nan]))
2425
+ assert_equal(np.maximum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-2.0, 10., np.nan]))
2426
+ assert_equal(out, out_maxtrue)
2427
+
2428
+ def test_precision(self):
2429
+ dtypes = [np.float16, np.float32, np.float64, np.longdouble]
2430
+
2431
+ for dt in dtypes:
2432
+ dtmin = np.finfo(dt).min
2433
+ dtmax = np.finfo(dt).max
2434
+ d1 = dt(0.1)
2435
+ d1_next = np.nextafter(d1, np.inf)
2436
+
2437
+ test_cases = [
2438
+ # v1 v2 expected
2439
+ (dtmin, -np.inf, dtmin),
2440
+ (dtmax, -np.inf, dtmax),
2441
+ (d1, d1_next, d1_next),
2442
+ (dtmax, np.nan, np.nan),
2443
+ ]
2444
+
2445
+ for v1, v2, expected in test_cases:
2446
+ assert_equal(np.maximum([v1], [v2]), [expected])
2447
+ assert_equal(np.maximum.reduce([v1, v2]), expected)
2448
+
2449
+
2450
+ class TestMinimum(_FilterInvalids):
2451
+ def test_reduce(self):
2452
+ dflt = np.typecodes['AllFloat']
2453
+ dint = np.typecodes['AllInteger']
2454
+ seq1 = np.arange(11)
2455
+ seq2 = seq1[::-1]
2456
+ func = np.minimum.reduce
2457
+ for dt in dint:
2458
+ tmp1 = seq1.astype(dt)
2459
+ tmp2 = seq2.astype(dt)
2460
+ assert_equal(func(tmp1), 0)
2461
+ assert_equal(func(tmp2), 0)
2462
+ for dt in dflt:
2463
+ tmp1 = seq1.astype(dt)
2464
+ tmp2 = seq2.astype(dt)
2465
+ assert_equal(func(tmp1), 0)
2466
+ assert_equal(func(tmp2), 0)
2467
+ tmp1[::2] = np.nan
2468
+ tmp2[::2] = np.nan
2469
+ assert_equal(func(tmp1), np.nan)
2470
+ assert_equal(func(tmp2), np.nan)
2471
+
2472
+ def test_reduce_complex(self):
2473
+ assert_equal(np.minimum.reduce([1, 2j]), 2j)
2474
+ assert_equal(np.minimum.reduce([1 + 3j, 2j]), 2j)
2475
+
2476
+ def test_float_nans(self):
2477
+ nan = np.nan
2478
+ arg1 = np.array([0, nan, nan])
2479
+ arg2 = np.array([nan, 0, nan])
2480
+ out = np.array([nan, nan, nan])
2481
+ assert_equal(np.minimum(arg1, arg2), out)
2482
+
2483
+ def test_object_nans(self):
2484
+ # Multiple checks to give this a chance to
2485
+ # fail if cmp is used instead of rich compare.
2486
+ # Failure cannot be guaranteed.
2487
+ for i in range(1):
2488
+ x = np.array(float('nan'), object)
2489
+ y = 1.0
2490
+ z = np.array(float('nan'), object)
2491
+ assert_(np.minimum(x, y) == 1.0)
2492
+ assert_(np.minimum(z, y) == 1.0)
2493
+
2494
+ def test_complex_nans(self):
2495
+ nan = np.nan
2496
+ for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
2497
+ arg1 = np.array([0, cnan, cnan], dtype=complex)
2498
+ arg2 = np.array([cnan, 0, cnan], dtype=complex)
2499
+ out = np.array([nan, nan, nan], dtype=complex)
2500
+ assert_equal(np.minimum(arg1, arg2), out)
2501
+
2502
+ def test_object_array(self):
2503
+ arg1 = np.arange(5, dtype=object)
2504
+ arg2 = arg1 + 1
2505
+ assert_equal(np.minimum(arg1, arg2), arg1)
2506
+
2507
+ def test_strided_array(self):
2508
+ arr1 = np.array([-4.0, 1.0, 10.0, 0.0, np.nan, -np.nan, np.inf, -np.inf])
2509
+ arr2 = np.array([-2.0, -1.0, np.nan, 1.0, 0.0, np.nan, 1.0, -3.0])
2510
+ mintrue = np.array([-4.0, -1.0, np.nan, 0.0, np.nan, np.nan, 1.0, -np.inf])
2511
+ out = np.ones(8)
2512
+ out_mintrue = np.array([-4.0, 1.0, 1.0, 1.0, 1.0, 1.0, np.nan, 1.0])
2513
+ assert_equal(np.minimum(arr1, arr2), mintrue)
2514
+ assert_equal(np.minimum(arr1[::2], arr2[::2]), mintrue[::2])
2515
+ assert_equal(np.minimum(arr1[:4:], arr2[::2]), np.array([-4.0, np.nan, 0.0, 0.0]))
2516
+ assert_equal(np.minimum(arr1[::3], arr2[:3:]), np.array([-4.0, -1.0, np.nan]))
2517
+ assert_equal(np.minimum(arr1[:6:2], arr2[::3], out=out[::3]), np.array([-4.0, 1.0, np.nan]))
2518
+ assert_equal(out, out_mintrue)
2519
+
2520
+ def test_precision(self):
2521
+ dtypes = [np.float16, np.float32, np.float64, np.longdouble]
2522
+
2523
+ for dt in dtypes:
2524
+ dtmin = np.finfo(dt).min
2525
+ dtmax = np.finfo(dt).max
2526
+ d1 = dt(0.1)
2527
+ d1_next = np.nextafter(d1, np.inf)
2528
+
2529
+ test_cases = [
2530
+ # v1 v2 expected
2531
+ (dtmin, np.inf, dtmin),
2532
+ (dtmax, np.inf, dtmax),
2533
+ (d1, d1_next, d1),
2534
+ (dtmin, np.nan, np.nan),
2535
+ ]
2536
+
2537
+ for v1, v2, expected in test_cases:
2538
+ assert_equal(np.minimum([v1], [v2]), [expected])
2539
+ assert_equal(np.minimum.reduce([v1, v2]), expected)
2540
+
2541
+
2542
+ class TestFmax(_FilterInvalids):
2543
+ def test_reduce(self):
2544
+ dflt = np.typecodes['AllFloat']
2545
+ dint = np.typecodes['AllInteger']
2546
+ seq1 = np.arange(11)
2547
+ seq2 = seq1[::-1]
2548
+ func = np.fmax.reduce
2549
+ for dt in dint:
2550
+ tmp1 = seq1.astype(dt)
2551
+ tmp2 = seq2.astype(dt)
2552
+ assert_equal(func(tmp1), 10)
2553
+ assert_equal(func(tmp2), 10)
2554
+ for dt in dflt:
2555
+ tmp1 = seq1.astype(dt)
2556
+ tmp2 = seq2.astype(dt)
2557
+ assert_equal(func(tmp1), 10)
2558
+ assert_equal(func(tmp2), 10)
2559
+ tmp1[::2] = np.nan
2560
+ tmp2[::2] = np.nan
2561
+ assert_equal(func(tmp1), 9)
2562
+ assert_equal(func(tmp2), 9)
2563
+
2564
+ def test_reduce_complex(self):
2565
+ assert_equal(np.fmax.reduce([1, 2j]), 1)
2566
+ assert_equal(np.fmax.reduce([1 + 3j, 2j]), 1 + 3j)
2567
+
2568
+ def test_float_nans(self):
2569
+ nan = np.nan
2570
+ arg1 = np.array([0, nan, nan])
2571
+ arg2 = np.array([nan, 0, nan])
2572
+ out = np.array([0, 0, nan])
2573
+ assert_equal(np.fmax(arg1, arg2), out)
2574
+
2575
+ def test_complex_nans(self):
2576
+ nan = np.nan
2577
+ for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
2578
+ arg1 = np.array([0, cnan, cnan], dtype=complex)
2579
+ arg2 = np.array([cnan, 0, cnan], dtype=complex)
2580
+ out = np.array([0, 0, nan], dtype=complex)
2581
+ assert_equal(np.fmax(arg1, arg2), out)
2582
+
2583
+ def test_precision(self):
2584
+ dtypes = [np.float16, np.float32, np.float64, np.longdouble]
2585
+
2586
+ for dt in dtypes:
2587
+ dtmin = np.finfo(dt).min
2588
+ dtmax = np.finfo(dt).max
2589
+ d1 = dt(0.1)
2590
+ d1_next = np.nextafter(d1, np.inf)
2591
+
2592
+ test_cases = [
2593
+ # v1 v2 expected
2594
+ (dtmin, -np.inf, dtmin),
2595
+ (dtmax, -np.inf, dtmax),
2596
+ (d1, d1_next, d1_next),
2597
+ (dtmax, np.nan, dtmax),
2598
+ ]
2599
+
2600
+ for v1, v2, expected in test_cases:
2601
+ assert_equal(np.fmax([v1], [v2]), [expected])
2602
+ assert_equal(np.fmax.reduce([v1, v2]), expected)
2603
+
2604
+
2605
+ class TestFmin(_FilterInvalids):
2606
+ def test_reduce(self):
2607
+ dflt = np.typecodes['AllFloat']
2608
+ dint = np.typecodes['AllInteger']
2609
+ seq1 = np.arange(11)
2610
+ seq2 = seq1[::-1]
2611
+ func = np.fmin.reduce
2612
+ for dt in dint:
2613
+ tmp1 = seq1.astype(dt)
2614
+ tmp2 = seq2.astype(dt)
2615
+ assert_equal(func(tmp1), 0)
2616
+ assert_equal(func(tmp2), 0)
2617
+ for dt in dflt:
2618
+ tmp1 = seq1.astype(dt)
2619
+ tmp2 = seq2.astype(dt)
2620
+ assert_equal(func(tmp1), 0)
2621
+ assert_equal(func(tmp2), 0)
2622
+ tmp1[::2] = np.nan
2623
+ tmp2[::2] = np.nan
2624
+ assert_equal(func(tmp1), 1)
2625
+ assert_equal(func(tmp2), 1)
2626
+
2627
+ def test_reduce_complex(self):
2628
+ assert_equal(np.fmin.reduce([1, 2j]), 2j)
2629
+ assert_equal(np.fmin.reduce([1 + 3j, 2j]), 2j)
2630
+
2631
+ def test_float_nans(self):
2632
+ nan = np.nan
2633
+ arg1 = np.array([0, nan, nan])
2634
+ arg2 = np.array([nan, 0, nan])
2635
+ out = np.array([0, 0, nan])
2636
+ assert_equal(np.fmin(arg1, arg2), out)
2637
+
2638
+ def test_complex_nans(self):
2639
+ nan = np.nan
2640
+ for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]:
2641
+ arg1 = np.array([0, cnan, cnan], dtype=complex)
2642
+ arg2 = np.array([cnan, 0, cnan], dtype=complex)
2643
+ out = np.array([0, 0, nan], dtype=complex)
2644
+ assert_equal(np.fmin(arg1, arg2), out)
2645
+
2646
+ def test_precision(self):
2647
+ dtypes = [np.float16, np.float32, np.float64, np.longdouble]
2648
+
2649
+ for dt in dtypes:
2650
+ dtmin = np.finfo(dt).min
2651
+ dtmax = np.finfo(dt).max
2652
+ d1 = dt(0.1)
2653
+ d1_next = np.nextafter(d1, np.inf)
2654
+
2655
+ test_cases = [
2656
+ # v1 v2 expected
2657
+ (dtmin, np.inf, dtmin),
2658
+ (dtmax, np.inf, dtmax),
2659
+ (d1, d1_next, d1),
2660
+ (dtmin, np.nan, dtmin),
2661
+ ]
2662
+
2663
+ for v1, v2, expected in test_cases:
2664
+ assert_equal(np.fmin([v1], [v2]), [expected])
2665
+ assert_equal(np.fmin.reduce([v1, v2]), expected)
2666
+
2667
+
2668
+ class TestBool:
2669
+ def test_exceptions(self):
2670
+ a = np.ones(1, dtype=np.bool)
2671
+ assert_raises(TypeError, np.negative, a)
2672
+ assert_raises(TypeError, np.positive, a)
2673
+ assert_raises(TypeError, np.subtract, a, a)
2674
+
2675
+ def test_truth_table_logical(self):
2676
+ # 2, 3 and 4 serves as true values
2677
+ input1 = [0, 0, 3, 2]
2678
+ input2 = [0, 4, 0, 2]
2679
+
2680
+ typecodes = (np.typecodes['AllFloat']
2681
+ + np.typecodes['AllInteger']
2682
+ + '?') # boolean
2683
+ for dtype in map(np.dtype, typecodes):
2684
+ arg1 = np.asarray(input1, dtype=dtype)
2685
+ arg2 = np.asarray(input2, dtype=dtype)
2686
+
2687
+ # OR
2688
+ out = [False, True, True, True]
2689
+ for func in (np.logical_or, np.maximum):
2690
+ assert_equal(func(arg1, arg2).astype(bool), out)
2691
+ # AND
2692
+ out = [False, False, False, True]
2693
+ for func in (np.logical_and, np.minimum):
2694
+ assert_equal(func(arg1, arg2).astype(bool), out)
2695
+ # XOR
2696
+ out = [False, True, True, False]
2697
+ for func in (np.logical_xor, np.not_equal):
2698
+ assert_equal(func(arg1, arg2).astype(bool), out)
2699
+
2700
+ def test_truth_table_bitwise(self):
2701
+ arg1 = [False, False, True, True]
2702
+ arg2 = [False, True, False, True]
2703
+
2704
+ out = [False, True, True, True]
2705
+ assert_equal(np.bitwise_or(arg1, arg2), out)
2706
+
2707
+ out = [False, False, False, True]
2708
+ assert_equal(np.bitwise_and(arg1, arg2), out)
2709
+
2710
+ out = [False, True, True, False]
2711
+ assert_equal(np.bitwise_xor(arg1, arg2), out)
2712
+
2713
+ def test_reduce(self):
2714
+ none = np.array([0, 0, 0, 0], bool)
2715
+ some = np.array([1, 0, 1, 1], bool)
2716
+ every = np.array([1, 1, 1, 1], bool)
2717
+ empty = np.array([], bool)
2718
+
2719
+ arrs = [none, some, every, empty]
2720
+
2721
+ for arr in arrs:
2722
+ assert_equal(np.logical_and.reduce(arr), all(arr))
2723
+
2724
+ for arr in arrs:
2725
+ assert_equal(np.logical_or.reduce(arr), any(arr))
2726
+
2727
+ for arr in arrs:
2728
+ assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1)
2729
+
2730
+
2731
+ class TestBitwiseUFuncs:
2732
+
2733
+ _all_ints_bits = [
2734
+ np.dtype(c).itemsize * 8 for c in np.typecodes["AllInteger"]]
2735
+ bitwise_types = [
2736
+ np.dtype(c) for c in '?' + np.typecodes["AllInteger"] + 'O']
2737
+ bitwise_bits = [
2738
+ 2, # boolean type
2739
+ *_all_ints_bits, # All integers
2740
+ max(_all_ints_bits) + 1, # Object_ type
2741
+ ]
2742
+
2743
+ def test_values(self):
2744
+ for dt in self.bitwise_types:
2745
+ zeros = np.array([0], dtype=dt)
2746
+ ones = np.array([-1]).astype(dt)
2747
+ msg = f"dt = '{dt.char}'"
2748
+
2749
+ assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
2750
+ assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
2751
+
2752
+ assert_equal(np.bitwise_or(zeros, zeros), zeros, err_msg=msg)
2753
+ assert_equal(np.bitwise_or(zeros, ones), ones, err_msg=msg)
2754
+ assert_equal(np.bitwise_or(ones, zeros), ones, err_msg=msg)
2755
+ assert_equal(np.bitwise_or(ones, ones), ones, err_msg=msg)
2756
+
2757
+ assert_equal(np.bitwise_xor(zeros, zeros), zeros, err_msg=msg)
2758
+ assert_equal(np.bitwise_xor(zeros, ones), ones, err_msg=msg)
2759
+ assert_equal(np.bitwise_xor(ones, zeros), ones, err_msg=msg)
2760
+ assert_equal(np.bitwise_xor(ones, ones), zeros, err_msg=msg)
2761
+
2762
+ assert_equal(np.bitwise_and(zeros, zeros), zeros, err_msg=msg)
2763
+ assert_equal(np.bitwise_and(zeros, ones), zeros, err_msg=msg)
2764
+ assert_equal(np.bitwise_and(ones, zeros), zeros, err_msg=msg)
2765
+ assert_equal(np.bitwise_and(ones, ones), ones, err_msg=msg)
2766
+
2767
+ def test_types(self):
2768
+ for dt in self.bitwise_types:
2769
+ zeros = np.array([0], dtype=dt)
2770
+ ones = np.array([-1]).astype(dt)
2771
+ msg = f"dt = '{dt.char}'"
2772
+
2773
+ assert_(np.bitwise_not(zeros).dtype == dt, msg)
2774
+ assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
2775
+ assert_(np.bitwise_xor(zeros, zeros).dtype == dt, msg)
2776
+ assert_(np.bitwise_and(zeros, zeros).dtype == dt, msg)
2777
+
2778
+ def test_identity(self):
2779
+ assert_(np.bitwise_or.identity == 0, 'bitwise_or')
2780
+ assert_(np.bitwise_xor.identity == 0, 'bitwise_xor')
2781
+ assert_(np.bitwise_and.identity == -1, 'bitwise_and')
2782
+
2783
+ def test_reduction(self):
2784
+ binary_funcs = (np.bitwise_or, np.bitwise_xor, np.bitwise_and)
2785
+
2786
+ for dt in self.bitwise_types:
2787
+ zeros = np.array([0], dtype=dt)
2788
+ ones = np.array([-1]).astype(dt)
2789
+ for f in binary_funcs:
2790
+ msg = f"dt: '{dt}', f: '{f}'"
2791
+ assert_equal(f.reduce(zeros), zeros, err_msg=msg)
2792
+ assert_equal(f.reduce(ones), ones, err_msg=msg)
2793
+
2794
+ # Test empty reduction, no object dtype
2795
+ for dt in self.bitwise_types[:-1]:
2796
+ # No object array types
2797
+ empty = np.array([], dtype=dt)
2798
+ for f in binary_funcs:
2799
+ msg = f"dt: '{dt}', f: '{f}'"
2800
+ tgt = np.array(f.identity).astype(dt)
2801
+ res = f.reduce(empty)
2802
+ assert_equal(res, tgt, err_msg=msg)
2803
+ assert_(res.dtype == tgt.dtype, msg)
2804
+
2805
+ # Empty object arrays use the identity. Note that the types may
2806
+ # differ, the actual type used is determined by the assign_identity
2807
+ # function and is not the same as the type returned by the identity
2808
+ # method.
2809
+ for f in binary_funcs:
2810
+ msg = f"dt: '{f}'"
2811
+ empty = np.array([], dtype=object)
2812
+ tgt = f.identity
2813
+ res = f.reduce(empty)
2814
+ assert_equal(res, tgt, err_msg=msg)
2815
+
2816
+ # Non-empty object arrays do not use the identity
2817
+ for f in binary_funcs:
2818
+ msg = f"dt: '{f}'"
2819
+ btype = np.array([True], dtype=object)
2820
+ assert_(type(f.reduce(btype)) is bool, msg)
2821
+
2822
+ @pytest.mark.parametrize("input_dtype_obj, bitsize",
2823
+ zip(bitwise_types, bitwise_bits))
2824
+ def test_bitwise_count(self, input_dtype_obj, bitsize):
2825
+ input_dtype = input_dtype_obj.type
2826
+
2827
+ for i in range(1, bitsize):
2828
+ num = 2**i - 1
2829
+ msg = f"bitwise_count for {num}"
2830
+ assert i == np.bitwise_count(input_dtype(num)), msg
2831
+ if np.issubdtype(
2832
+ input_dtype, np.signedinteger) or input_dtype == np.object_:
2833
+ assert i == np.bitwise_count(input_dtype(-num)), msg
2834
+
2835
+ a = np.array([2**i - 1 for i in range(1, bitsize)], dtype=input_dtype)
2836
+ bitwise_count_a = np.bitwise_count(a)
2837
+ expected = np.arange(1, bitsize, dtype=input_dtype)
2838
+
2839
+ msg = f"array bitwise_count for {input_dtype}"
2840
+ assert all(bitwise_count_a == expected), msg
2841
+
2842
+
2843
+ class TestInt:
2844
+ def test_logical_not(self):
2845
+ x = np.ones(10, dtype=np.int16)
2846
+ o = np.ones(10 * 2, dtype=bool)
2847
+ tgt = o.copy()
2848
+ tgt[::2] = False
2849
+ os = o[::2]
2850
+ assert_array_equal(np.logical_not(x, out=os), False)
2851
+ assert_array_equal(o, tgt)
2852
+
2853
+
2854
+ class TestFloatingPoint:
2855
+ def test_floating_point(self):
2856
+ assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)
2857
+
2858
+
2859
+ class TestDegrees:
2860
+ def test_degrees(self):
2861
+ assert_almost_equal(ncu.degrees(np.pi), 180.0)
2862
+ assert_almost_equal(ncu.degrees(-0.5 * np.pi), -90.0)
2863
+
2864
+
2865
+ class TestRadians:
2866
+ def test_radians(self):
2867
+ assert_almost_equal(ncu.radians(180.0), np.pi)
2868
+ assert_almost_equal(ncu.radians(-90.0), -0.5 * np.pi)
2869
+
2870
+
2871
+ class TestHeavside:
2872
+ def test_heaviside(self):
2873
+ x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]])
2874
+ expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]])
2875
+ expected1 = expectedhalf.copy()
2876
+ expected1[0, 2] = 1
2877
+
2878
+ h = ncu.heaviside(x, 0.5)
2879
+ assert_equal(h, expectedhalf)
2880
+
2881
+ h = ncu.heaviside(x, 1.0)
2882
+ assert_equal(h, expected1)
2883
+
2884
+ x = x.astype(np.float32)
2885
+
2886
+ h = ncu.heaviside(x, np.float32(0.5))
2887
+ assert_equal(h, expectedhalf.astype(np.float32))
2888
+
2889
+ h = ncu.heaviside(x, np.float32(1.0))
2890
+ assert_equal(h, expected1.astype(np.float32))
2891
+
2892
+
2893
+ class TestSign:
2894
+ def test_sign(self):
2895
+ a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0])
2896
+ out = np.zeros(a.shape)
2897
+ tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
2898
+
2899
+ with np.errstate(invalid='ignore'):
2900
+ res = ncu.sign(a)
2901
+ assert_equal(res, tgt)
2902
+ res = ncu.sign(a, out)
2903
+ assert_equal(res, tgt)
2904
+ assert_equal(out, tgt)
2905
+
2906
+ def test_sign_complex(self):
2907
+ a = np.array([
2908
+ np.inf, -np.inf, complex(0, np.inf), complex(0, -np.inf),
2909
+ complex(np.inf, np.inf), complex(np.inf, -np.inf), # nan
2910
+ np.nan, complex(0, np.nan), complex(np.nan, np.nan), # nan
2911
+ 0.0, # 0.
2912
+ 3.0, -3.0, -2j, 3.0 + 4.0j, -8.0 + 6.0j
2913
+ ])
2914
+ out = np.zeros(a.shape, a.dtype)
2915
+ tgt = np.array([
2916
+ 1., -1., 1j, -1j,
2917
+ ] + [complex(np.nan, np.nan)] * 5 + [
2918
+ 0.0,
2919
+ 1.0, -1.0, -1j, 0.6 + 0.8j, -0.8 + 0.6j])
2920
+
2921
+ with np.errstate(invalid='ignore'):
2922
+ res = ncu.sign(a)
2923
+ assert_equal(res, tgt)
2924
+ res = ncu.sign(a, out)
2925
+ assert_(res is out)
2926
+ assert_equal(res, tgt)
2927
+
2928
+ def test_sign_dtype_object(self):
2929
+ # In reference to github issue #6229
2930
+
2931
+ foo = np.array([-.1, 0, .1])
2932
+ a = np.sign(foo.astype(object))
2933
+ b = np.sign(foo)
2934
+
2935
+ assert_array_equal(a, b)
2936
+
2937
+ def test_sign_dtype_nan_object(self):
2938
+ # In reference to github issue #6229
2939
+ def test_nan():
2940
+ foo = np.array([np.nan])
2941
+ # FIXME: a not used
2942
+ a = np.sign(foo.astype(object))
2943
+
2944
+ assert_raises(TypeError, test_nan)
2945
+
2946
+ class TestMinMax:
2947
+ def test_minmax_blocked(self):
2948
+ # simd tests on max/min, test all alignments, slow but important
2949
+ # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once)
2950
+ for dt, sz in [(np.float32, 15), (np.float64, 7)]:
2951
+ for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
2952
+ max_size=sz):
2953
+ for i in range(inp.size):
2954
+ inp[:] = np.arange(inp.size, dtype=dt)
2955
+ inp[i] = np.nan
2956
+ emsg = lambda: f'{inp!r}\n{msg}'
2957
+ with suppress_warnings() as sup:
2958
+ sup.filter(RuntimeWarning,
2959
+ "invalid value encountered in reduce")
2960
+ assert_(np.isnan(inp.max()), msg=emsg)
2961
+ assert_(np.isnan(inp.min()), msg=emsg)
2962
+
2963
+ inp[i] = 1e10
2964
+ assert_equal(inp.max(), 1e10, err_msg=msg)
2965
+ inp[i] = -1e10
2966
+ assert_equal(inp.min(), -1e10, err_msg=msg)
2967
+
2968
+ def test_lower_align(self):
2969
+ # check data that is not aligned to element size
2970
+ # i.e doubles are aligned to 4 bytes on i386
2971
+ d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
2972
+ assert_equal(d.max(), d[0])
2973
+ assert_equal(d.min(), d[0])
2974
+
2975
+ def test_reduce_reorder(self):
2976
+ # gh 10370, 11029 Some compilers reorder the call to npy_getfloatstatus
2977
+ # and put it before the call to an intrinsic function that causes
2978
+ # invalid status to be set. Also make sure warnings are not emitted
2979
+ for n in (2, 4, 8, 16, 32):
2980
+ for dt in (np.float32, np.float16, np.complex64):
2981
+ for r in np.diagflat(np.array([np.nan] * n, dtype=dt)):
2982
+ assert_equal(np.min(r), np.nan)
2983
+
2984
+ def test_minimize_no_warns(self):
2985
+ a = np.minimum(np.nan, 1)
2986
+ assert_equal(a, np.nan)
2987
+
2988
+
2989
+ class TestAbsoluteNegative:
2990
+ def test_abs_neg_blocked(self):
2991
+ # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1
2992
+ for dt, sz in [(np.float32, 11), (np.float64, 5)]:
2993
+ for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary',
2994
+ max_size=sz):
2995
+ tgt = [ncu.absolute(i) for i in inp]
2996
+ np.absolute(inp, out=out)
2997
+ assert_equal(out, tgt, err_msg=msg)
2998
+ assert_((out >= 0).all())
2999
+
3000
+ tgt = [-1 * (i) for i in inp]
3001
+ np.negative(inp, out=out)
3002
+ assert_equal(out, tgt, err_msg=msg)
3003
+
3004
+ for v in [np.nan, -np.inf, np.inf]:
3005
+ for i in range(inp.size):
3006
+ d = np.arange(inp.size, dtype=dt)
3007
+ inp[:] = -d
3008
+ inp[i] = v
3009
+ d[i] = -v if v == -np.inf else v
3010
+ assert_array_equal(np.abs(inp), d, err_msg=msg)
3011
+ np.abs(inp, out=out)
3012
+ assert_array_equal(out, d, err_msg=msg)
3013
+
3014
+ assert_array_equal(-inp, -1 * inp, err_msg=msg)
3015
+ d = -1 * inp
3016
+ np.negative(inp, out=out)
3017
+ assert_array_equal(out, d, err_msg=msg)
3018
+
3019
+ def test_lower_align(self):
3020
+ # check data that is not aligned to element size
3021
+ # i.e doubles are aligned to 4 bytes on i386
3022
+ d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64)
3023
+ assert_equal(np.abs(d), d)
3024
+ assert_equal(np.negative(d), -d)
3025
+ np.negative(d, out=d)
3026
+ np.negative(np.ones_like(d), out=d)
3027
+ np.abs(d, out=d)
3028
+ np.abs(np.ones_like(d), out=d)
3029
+
3030
+ @pytest.mark.parametrize("dtype", ['d', 'f', 'int32', 'int64'])
3031
+ @pytest.mark.parametrize("big", [True, False])
3032
+ def test_noncontiguous(self, dtype, big):
3033
+ data = np.array([-1.0, 1.0, -0.0, 0.0, 2.2251e-308, -2.5, 2.5, -6,
3034
+ 6, -2.2251e-308, -8, 10], dtype=dtype)
3035
+ expect = np.array([1.0, -1.0, 0.0, -0.0, -2.2251e-308, 2.5, -2.5, 6,
3036
+ -6, 2.2251e-308, 8, -10], dtype=dtype)
3037
+ if big:
3038
+ data = np.repeat(data, 10)
3039
+ expect = np.repeat(expect, 10)
3040
+ out = np.ndarray(data.shape, dtype=dtype)
3041
+ ncontig_in = data[1::2]
3042
+ ncontig_out = out[1::2]
3043
+ contig_in = np.array(ncontig_in)
3044
+ # contig in, contig out
3045
+ assert_array_equal(np.negative(contig_in), expect[1::2])
3046
+ # contig in, ncontig out
3047
+ assert_array_equal(np.negative(contig_in, out=ncontig_out),
3048
+ expect[1::2])
3049
+ # ncontig in, contig out
3050
+ assert_array_equal(np.negative(ncontig_in), expect[1::2])
3051
+ # ncontig in, ncontig out
3052
+ assert_array_equal(np.negative(ncontig_in, out=ncontig_out),
3053
+ expect[1::2])
3054
+ # contig in, contig out, nd stride
3055
+ data_split = np.array(np.array_split(data, 2))
3056
+ expect_split = np.array(np.array_split(expect, 2))
3057
+ assert_equal(np.negative(data_split), expect_split)
3058
+
3059
+
3060
+ class TestPositive:
3061
+ def test_valid(self):
3062
+ valid_dtypes = [int, float, complex, object]
3063
+ for dtype in valid_dtypes:
3064
+ x = np.arange(5, dtype=dtype)
3065
+ result = np.positive(x)
3066
+ assert_equal(x, result, err_msg=str(dtype))
3067
+
3068
+ def test_invalid(self):
3069
+ with assert_raises(TypeError):
3070
+ np.positive(True)
3071
+ with assert_raises(TypeError):
3072
+ np.positive(np.datetime64('2000-01-01'))
3073
+ with assert_raises(TypeError):
3074
+ np.positive(np.array(['foo'], dtype=str))
3075
+ with assert_raises(TypeError):
3076
+ np.positive(np.array(['bar'], dtype=object))
3077
+
3078
+
3079
+ class TestSpecialMethods:
3080
+ def test_wrap(self):
3081
+
3082
+ class with_wrap:
3083
+ def __array__(self, dtype=None, copy=None):
3084
+ return np.zeros(1)
3085
+
3086
+ def __array_wrap__(self, arr, context, return_scalar):
3087
+ r = with_wrap()
3088
+ r.arr = arr
3089
+ r.context = context
3090
+ return r
3091
+
3092
+ a = with_wrap()
3093
+ x = ncu.minimum(a, a)
3094
+ assert_equal(x.arr, np.zeros(1))
3095
+ func, args, i = x.context
3096
+ assert_(func is ncu.minimum)
3097
+ assert_equal(len(args), 2)
3098
+ assert_equal(args[0], a)
3099
+ assert_equal(args[1], a)
3100
+ assert_equal(i, 0)
3101
+
3102
+ def test_wrap_out(self):
3103
+ # Calling convention for out should not affect how special methods are
3104
+ # called
3105
+
3106
+ class StoreArrayPrepareWrap(np.ndarray):
3107
+ _wrap_args = None
3108
+ _prepare_args = None
3109
+
3110
+ def __new__(cls):
3111
+ return np.zeros(()).view(cls)
3112
+
3113
+ def __array_wrap__(self, obj, context, return_scalar):
3114
+ self._wrap_args = context[1]
3115
+ return obj
3116
+
3117
+ @property
3118
+ def args(self):
3119
+ # We need to ensure these are fetched at the same time, before
3120
+ # any other ufuncs are called by the assertions
3121
+ return self._wrap_args
3122
+
3123
+ def __repr__(self):
3124
+ return "a" # for short test output
3125
+
3126
+ def do_test(f_call, f_expected):
3127
+ a = StoreArrayPrepareWrap()
3128
+
3129
+ f_call(a)
3130
+
3131
+ w = a.args
3132
+ expected = f_expected(a)
3133
+ try:
3134
+ assert w == expected
3135
+ except AssertionError as e:
3136
+ # assert_equal produces truly useless error messages
3137
+ raise AssertionError("\n".join([
3138
+ "Bad arguments passed in ufunc call",
3139
+ f" expected: {expected}",
3140
+ f" __array_wrap__ got: {w}"
3141
+ ]))
3142
+
3143
+ # method not on the out argument
3144
+ do_test(lambda a: np.add(a, 0), lambda a: (a, 0))
3145
+ do_test(lambda a: np.add(a, 0, None), lambda a: (a, 0))
3146
+ do_test(lambda a: np.add(a, 0, out=None), lambda a: (a, 0))
3147
+ do_test(lambda a: np.add(a, 0, out=(None,)), lambda a: (a, 0))
3148
+
3149
+ # method on the out argument
3150
+ do_test(lambda a: np.add(0, 0, a), lambda a: (0, 0, a))
3151
+ do_test(lambda a: np.add(0, 0, out=a), lambda a: (0, 0, a))
3152
+ do_test(lambda a: np.add(0, 0, out=(a,)), lambda a: (0, 0, a))
3153
+
3154
+ # Also check the where mask handling:
3155
+ do_test(lambda a: np.add(a, 0, where=False), lambda a: (a, 0))
3156
+ do_test(lambda a: np.add(0, 0, a, where=False), lambda a: (0, 0, a))
3157
+
3158
+ def test_wrap_with_iterable(self):
3159
+ # test fix for bug #1026:
3160
+
3161
+ class with_wrap(np.ndarray):
3162
+ __array_priority__ = 10
3163
+
3164
+ def __new__(cls):
3165
+ return np.asarray(1).view(cls).copy()
3166
+
3167
+ def __array_wrap__(self, arr, context, return_scalar):
3168
+ return arr.view(type(self))
3169
+
3170
+ a = with_wrap()
3171
+ x = ncu.multiply(a, (1, 2, 3))
3172
+ assert_(isinstance(x, with_wrap))
3173
+ assert_array_equal(x, np.array((1, 2, 3)))
3174
+
3175
+ def test_priority_with_scalar(self):
3176
+ # test fix for bug #826:
3177
+
3178
+ class A(np.ndarray):
3179
+ __array_priority__ = 10
3180
+
3181
+ def __new__(cls):
3182
+ return np.asarray(1.0, 'float64').view(cls).copy()
3183
+
3184
+ a = A()
3185
+ x = np.float64(1) * a
3186
+ assert_(isinstance(x, A))
3187
+ assert_array_equal(x, np.array(1))
3188
+
3189
+ def test_priority(self):
3190
+
3191
+ class A:
3192
+ def __array__(self, dtype=None, copy=None):
3193
+ return np.zeros(1)
3194
+
3195
+ def __array_wrap__(self, arr, context, return_scalar):
3196
+ r = type(self)()
3197
+ r.arr = arr
3198
+ r.context = context
3199
+ return r
3200
+
3201
+ class B(A):
3202
+ __array_priority__ = 20.
3203
+
3204
+ class C(A):
3205
+ __array_priority__ = 40.
3206
+
3207
+ x = np.zeros(1)
3208
+ a = A()
3209
+ b = B()
3210
+ c = C()
3211
+ f = ncu.minimum
3212
+ assert_(type(f(x, x)) is np.ndarray)
3213
+ assert_(type(f(x, a)) is A)
3214
+ assert_(type(f(x, b)) is B)
3215
+ assert_(type(f(x, c)) is C)
3216
+ assert_(type(f(a, x)) is A)
3217
+ assert_(type(f(b, x)) is B)
3218
+ assert_(type(f(c, x)) is C)
3219
+
3220
+ assert_(type(f(a, a)) is A)
3221
+ assert_(type(f(a, b)) is B)
3222
+ assert_(type(f(b, a)) is B)
3223
+ assert_(type(f(b, b)) is B)
3224
+ assert_(type(f(b, c)) is C)
3225
+ assert_(type(f(c, b)) is C)
3226
+ assert_(type(f(c, c)) is C)
3227
+
3228
+ assert_(type(ncu.exp(a) is A))
3229
+ assert_(type(ncu.exp(b) is B))
3230
+ assert_(type(ncu.exp(c) is C))
3231
+
3232
+ def test_failing_wrap(self):
3233
+
3234
+ class A:
3235
+ def __array__(self, dtype=None, copy=None):
3236
+ return np.zeros(2)
3237
+
3238
+ def __array_wrap__(self, arr, context, return_scalar):
3239
+ raise RuntimeError
3240
+
3241
+ a = A()
3242
+ assert_raises(RuntimeError, ncu.maximum, a, a)
3243
+ assert_raises(RuntimeError, ncu.maximum.reduce, a)
3244
+
3245
+ def test_failing_out_wrap(self):
3246
+
3247
+ singleton = np.array([1.0])
3248
+
3249
+ class Ok(np.ndarray):
3250
+ def __array_wrap__(self, obj, context, return_scalar):
3251
+ return singleton
3252
+
3253
+ class Bad(np.ndarray):
3254
+ def __array_wrap__(self, obj, context, return_scalar):
3255
+ raise RuntimeError
3256
+
3257
+ ok = np.empty(1).view(Ok)
3258
+ bad = np.empty(1).view(Bad)
3259
+ # double-free (segfault) of "ok" if "bad" raises an exception
3260
+ for i in range(10):
3261
+ assert_raises(RuntimeError, ncu.frexp, 1, ok, bad)
3262
+
3263
+ def test_none_wrap(self):
3264
+ # Tests that issue #8507 is resolved. Previously, this would segfault
3265
+
3266
+ class A:
3267
+ def __array__(self, dtype=None, copy=None):
3268
+ return np.zeros(1)
3269
+
3270
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
3271
+ return None
3272
+
3273
+ a = A()
3274
+ assert_equal(ncu.maximum(a, a), None)
3275
+
3276
+ def test_default_prepare(self):
3277
+
3278
+ class with_wrap:
3279
+ __array_priority__ = 10
3280
+
3281
+ def __array__(self, dtype=None, copy=None):
3282
+ return np.zeros(1)
3283
+
3284
+ def __array_wrap__(self, arr, context, return_scalar):
3285
+ return arr
3286
+
3287
+ a = with_wrap()
3288
+ x = ncu.minimum(a, a)
3289
+ assert_equal(x, np.zeros(1))
3290
+ assert_equal(type(x), np.ndarray)
3291
+
3292
+ def test_array_too_many_args(self):
3293
+
3294
+ class A:
3295
+ def __array__(self, dtype, context, copy=None):
3296
+ return np.zeros(1)
3297
+
3298
+ a = A()
3299
+ assert_raises_regex(TypeError, '2 required positional', np.sum, a)
3300
+
3301
+ def test_ufunc_override(self):
3302
+ # check override works even with instance with high priority.
3303
+ class A:
3304
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3305
+ return self, func, method, inputs, kwargs
3306
+
3307
+ class MyNDArray(np.ndarray):
3308
+ __array_priority__ = 100
3309
+
3310
+ a = A()
3311
+ b = np.array([1]).view(MyNDArray)
3312
+ res0 = np.multiply(a, b)
3313
+ res1 = np.multiply(b, b, out=a)
3314
+
3315
+ # self
3316
+ assert_equal(res0[0], a)
3317
+ assert_equal(res1[0], a)
3318
+ assert_equal(res0[1], np.multiply)
3319
+ assert_equal(res1[1], np.multiply)
3320
+ assert_equal(res0[2], '__call__')
3321
+ assert_equal(res1[2], '__call__')
3322
+ assert_equal(res0[3], (a, b))
3323
+ assert_equal(res1[3], (b, b))
3324
+ assert_equal(res0[4], {})
3325
+ assert_equal(res1[4], {'out': (a,)})
3326
+
3327
+ def test_ufunc_override_mro(self):
3328
+
3329
+ # Some multi arg functions for testing.
3330
+ def tres_mul(a, b, c):
3331
+ return a * b * c
3332
+
3333
+ def quatro_mul(a, b, c, d):
3334
+ return a * b * c * d
3335
+
3336
+ # Make these into ufuncs.
3337
+ three_mul_ufunc = np.frompyfunc(tres_mul, 3, 1)
3338
+ four_mul_ufunc = np.frompyfunc(quatro_mul, 4, 1)
3339
+
3340
+ class A:
3341
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3342
+ return "A"
3343
+
3344
+ class ASub(A):
3345
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3346
+ return "ASub"
3347
+
3348
+ class B:
3349
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3350
+ return "B"
3351
+
3352
+ class C:
3353
+ def __init__(self):
3354
+ self.count = 0
3355
+
3356
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3357
+ self.count += 1
3358
+ return NotImplemented
3359
+
3360
+ class CSub(C):
3361
+ def __array_ufunc__(self, func, method, *inputs, **kwargs):
3362
+ self.count += 1
3363
+ return NotImplemented
3364
+
3365
+ a = A()
3366
+ a_sub = ASub()
3367
+ b = B()
3368
+ c = C()
3369
+
3370
+ # Standard
3371
+ res = np.multiply(a, a_sub)
3372
+ assert_equal(res, "ASub")
3373
+ res = np.multiply(a_sub, b)
3374
+ assert_equal(res, "ASub")
3375
+
3376
+ # With 1 NotImplemented
3377
+ res = np.multiply(c, a)
3378
+ assert_equal(res, "A")
3379
+ assert_equal(c.count, 1)
3380
+ # Check our counter works, so we can trust tests below.
3381
+ res = np.multiply(c, a)
3382
+ assert_equal(c.count, 2)
3383
+
3384
+ # Both NotImplemented.
3385
+ c = C()
3386
+ c_sub = CSub()
3387
+ assert_raises(TypeError, np.multiply, c, c_sub)
3388
+ assert_equal(c.count, 1)
3389
+ assert_equal(c_sub.count, 1)
3390
+ c.count = c_sub.count = 0
3391
+ assert_raises(TypeError, np.multiply, c_sub, c)
3392
+ assert_equal(c.count, 1)
3393
+ assert_equal(c_sub.count, 1)
3394
+ c.count = 0
3395
+ assert_raises(TypeError, np.multiply, c, c)
3396
+ assert_equal(c.count, 1)
3397
+ c.count = 0
3398
+ assert_raises(TypeError, np.multiply, 2, c)
3399
+ assert_equal(c.count, 1)
3400
+
3401
+ # Ternary testing.
3402
+ assert_equal(three_mul_ufunc(a, 1, 2), "A")
3403
+ assert_equal(three_mul_ufunc(1, a, 2), "A")
3404
+ assert_equal(three_mul_ufunc(1, 2, a), "A")
3405
+
3406
+ assert_equal(three_mul_ufunc(a, a, 6), "A")
3407
+ assert_equal(three_mul_ufunc(a, 2, a), "A")
3408
+ assert_equal(three_mul_ufunc(a, 2, b), "A")
3409
+ assert_equal(three_mul_ufunc(a, 2, a_sub), "ASub")
3410
+ assert_equal(three_mul_ufunc(a, a_sub, 3), "ASub")
3411
+ c.count = 0
3412
+ assert_equal(three_mul_ufunc(c, a_sub, 3), "ASub")
3413
+ assert_equal(c.count, 1)
3414
+ c.count = 0
3415
+ assert_equal(three_mul_ufunc(1, a_sub, c), "ASub")
3416
+ assert_equal(c.count, 0)
3417
+
3418
+ c.count = 0
3419
+ assert_equal(three_mul_ufunc(a, b, c), "A")
3420
+ assert_equal(c.count, 0)
3421
+ c_sub.count = 0
3422
+ assert_equal(three_mul_ufunc(a, b, c_sub), "A")
3423
+ assert_equal(c_sub.count, 0)
3424
+ assert_equal(three_mul_ufunc(1, 2, b), "B")
3425
+
3426
+ assert_raises(TypeError, three_mul_ufunc, 1, 2, c)
3427
+ assert_raises(TypeError, three_mul_ufunc, c_sub, 2, c)
3428
+ assert_raises(TypeError, three_mul_ufunc, c_sub, 2, 3)
3429
+
3430
+ # Quaternary testing.
3431
+ assert_equal(four_mul_ufunc(a, 1, 2, 3), "A")
3432
+ assert_equal(four_mul_ufunc(1, a, 2, 3), "A")
3433
+ assert_equal(four_mul_ufunc(1, 1, a, 3), "A")
3434
+ assert_equal(four_mul_ufunc(1, 1, 2, a), "A")
3435
+
3436
+ assert_equal(four_mul_ufunc(a, b, 2, 3), "A")
3437
+ assert_equal(four_mul_ufunc(1, a, 2, b), "A")
3438
+ assert_equal(four_mul_ufunc(b, 1, a, 3), "B")
3439
+ assert_equal(four_mul_ufunc(a_sub, 1, 2, a), "ASub")
3440
+ assert_equal(four_mul_ufunc(a, 1, 2, a_sub), "ASub")
3441
+
3442
+ c = C()
3443
+ c_sub = CSub()
3444
+ assert_raises(TypeError, four_mul_ufunc, 1, 2, 3, c)
3445
+ assert_equal(c.count, 1)
3446
+ c.count = 0
3447
+ assert_raises(TypeError, four_mul_ufunc, 1, 2, c_sub, c)
3448
+ assert_equal(c_sub.count, 1)
3449
+ assert_equal(c.count, 1)
3450
+ c2 = C()
3451
+ c.count = c_sub.count = 0
3452
+ assert_raises(TypeError, four_mul_ufunc, 1, c, c_sub, c2)
3453
+ assert_equal(c_sub.count, 1)
3454
+ assert_equal(c.count, 1)
3455
+ assert_equal(c2.count, 0)
3456
+ c.count = c2.count = c_sub.count = 0
3457
+ assert_raises(TypeError, four_mul_ufunc, c2, c, c_sub, c)
3458
+ assert_equal(c_sub.count, 1)
3459
+ assert_equal(c.count, 0)
3460
+ assert_equal(c2.count, 1)
3461
+
3462
+ def test_ufunc_override_methods(self):
3463
+
3464
+ class A:
3465
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3466
+ return self, ufunc, method, inputs, kwargs
3467
+
3468
+ # __call__
3469
+ a = A()
3470
+ with assert_raises(TypeError):
3471
+ np.multiply.__call__(1, a, foo='bar', answer=42)
3472
+ res = np.multiply.__call__(1, a, subok='bar', where=42)
3473
+ assert_equal(res[0], a)
3474
+ assert_equal(res[1], np.multiply)
3475
+ assert_equal(res[2], '__call__')
3476
+ assert_equal(res[3], (1, a))
3477
+ assert_equal(res[4], {'subok': 'bar', 'where': 42})
3478
+
3479
+ # __call__, wrong args
3480
+ assert_raises(TypeError, np.multiply, a)
3481
+ assert_raises(TypeError, np.multiply, a, a, a, a)
3482
+ assert_raises(TypeError, np.multiply, a, a, sig='a', signature='a')
3483
+ assert_raises(TypeError, ncu_tests.inner1d, a, a, axis=0, axes=[0, 0])
3484
+
3485
+ # reduce, positional args
3486
+ res = np.multiply.reduce(a, 'axis0', 'dtype0', 'out0', 'keep0')
3487
+ assert_equal(res[0], a)
3488
+ assert_equal(res[1], np.multiply)
3489
+ assert_equal(res[2], 'reduce')
3490
+ assert_equal(res[3], (a,))
3491
+ assert_equal(res[4], {'dtype': 'dtype0',
3492
+ 'out': ('out0',),
3493
+ 'keepdims': 'keep0',
3494
+ 'axis': 'axis0'})
3495
+
3496
+ # reduce, kwargs
3497
+ res = np.multiply.reduce(a, axis='axis0', dtype='dtype0', out='out0',
3498
+ keepdims='keep0', initial='init0',
3499
+ where='where0')
3500
+ assert_equal(res[0], a)
3501
+ assert_equal(res[1], np.multiply)
3502
+ assert_equal(res[2], 'reduce')
3503
+ assert_equal(res[3], (a,))
3504
+ assert_equal(res[4], {'dtype': 'dtype0',
3505
+ 'out': ('out0',),
3506
+ 'keepdims': 'keep0',
3507
+ 'axis': 'axis0',
3508
+ 'initial': 'init0',
3509
+ 'where': 'where0'})
3510
+
3511
+ # reduce, output equal to None removed, but not other explicit ones,
3512
+ # even if they are at their default value.
3513
+ res = np.multiply.reduce(a, 0, None, None, False)
3514
+ assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False})
3515
+ res = np.multiply.reduce(a, out=None, axis=0, keepdims=True)
3516
+ assert_equal(res[4], {'axis': 0, 'keepdims': True})
3517
+ res = np.multiply.reduce(a, None, out=(None,), dtype=None)
3518
+ assert_equal(res[4], {'axis': None, 'dtype': None})
3519
+ res = np.multiply.reduce(a, 0, None, None, False, 2, True)
3520
+ assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
3521
+ 'initial': 2, 'where': True})
3522
+ # np._NoValue ignored for initial
3523
+ res = np.multiply.reduce(a, 0, None, None, False,
3524
+ np._NoValue, True)
3525
+ assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
3526
+ 'where': True})
3527
+ # None kept for initial, True for where.
3528
+ res = np.multiply.reduce(a, 0, None, None, False, None, True)
3529
+ assert_equal(res[4], {'axis': 0, 'dtype': None, 'keepdims': False,
3530
+ 'initial': None, 'where': True})
3531
+
3532
+ # reduce, wrong args
3533
+ assert_raises(ValueError, np.multiply.reduce, a, out=())
3534
+ assert_raises(ValueError, np.multiply.reduce, a, out=('out0', 'out1'))
3535
+ assert_raises(TypeError, np.multiply.reduce, a, 'axis0', axis='axis0')
3536
+
3537
+ # accumulate, pos args
3538
+ res = np.multiply.accumulate(a, 'axis0', 'dtype0', 'out0')
3539
+ assert_equal(res[0], a)
3540
+ assert_equal(res[1], np.multiply)
3541
+ assert_equal(res[2], 'accumulate')
3542
+ assert_equal(res[3], (a,))
3543
+ assert_equal(res[4], {'dtype': 'dtype0',
3544
+ 'out': ('out0',),
3545
+ 'axis': 'axis0'})
3546
+
3547
+ # accumulate, kwargs
3548
+ res = np.multiply.accumulate(a, axis='axis0', dtype='dtype0',
3549
+ out='out0')
3550
+ assert_equal(res[0], a)
3551
+ assert_equal(res[1], np.multiply)
3552
+ assert_equal(res[2], 'accumulate')
3553
+ assert_equal(res[3], (a,))
3554
+ assert_equal(res[4], {'dtype': 'dtype0',
3555
+ 'out': ('out0',),
3556
+ 'axis': 'axis0'})
3557
+
3558
+ # accumulate, output equal to None removed.
3559
+ res = np.multiply.accumulate(a, 0, None, None)
3560
+ assert_equal(res[4], {'axis': 0, 'dtype': None})
3561
+ res = np.multiply.accumulate(a, out=None, axis=0, dtype='dtype1')
3562
+ assert_equal(res[4], {'axis': 0, 'dtype': 'dtype1'})
3563
+ res = np.multiply.accumulate(a, None, out=(None,), dtype=None)
3564
+ assert_equal(res[4], {'axis': None, 'dtype': None})
3565
+
3566
+ # accumulate, wrong args
3567
+ assert_raises(ValueError, np.multiply.accumulate, a, out=())
3568
+ assert_raises(ValueError, np.multiply.accumulate, a,
3569
+ out=('out0', 'out1'))
3570
+ assert_raises(TypeError, np.multiply.accumulate, a,
3571
+ 'axis0', axis='axis0')
3572
+
3573
+ # reduceat, pos args
3574
+ res = np.multiply.reduceat(a, [4, 2], 'axis0', 'dtype0', 'out0')
3575
+ assert_equal(res[0], a)
3576
+ assert_equal(res[1], np.multiply)
3577
+ assert_equal(res[2], 'reduceat')
3578
+ assert_equal(res[3], (a, [4, 2]))
3579
+ assert_equal(res[4], {'dtype': 'dtype0',
3580
+ 'out': ('out0',),
3581
+ 'axis': 'axis0'})
3582
+
3583
+ # reduceat, kwargs
3584
+ res = np.multiply.reduceat(a, [4, 2], axis='axis0', dtype='dtype0',
3585
+ out='out0')
3586
+ assert_equal(res[0], a)
3587
+ assert_equal(res[1], np.multiply)
3588
+ assert_equal(res[2], 'reduceat')
3589
+ assert_equal(res[3], (a, [4, 2]))
3590
+ assert_equal(res[4], {'dtype': 'dtype0',
3591
+ 'out': ('out0',),
3592
+ 'axis': 'axis0'})
3593
+
3594
+ # reduceat, output equal to None removed.
3595
+ res = np.multiply.reduceat(a, [4, 2], 0, None, None)
3596
+ assert_equal(res[4], {'axis': 0, 'dtype': None})
3597
+ res = np.multiply.reduceat(a, [4, 2], axis=None, out=None, dtype='dt')
3598
+ assert_equal(res[4], {'axis': None, 'dtype': 'dt'})
3599
+ res = np.multiply.reduceat(a, [4, 2], None, None, out=(None,))
3600
+ assert_equal(res[4], {'axis': None, 'dtype': None})
3601
+
3602
+ # reduceat, wrong args
3603
+ assert_raises(ValueError, np.multiply.reduce, a, [4, 2], out=())
3604
+ assert_raises(ValueError, np.multiply.reduce, a, [4, 2],
3605
+ out=('out0', 'out1'))
3606
+ assert_raises(TypeError, np.multiply.reduce, a, [4, 2],
3607
+ 'axis0', axis='axis0')
3608
+
3609
+ # outer
3610
+ res = np.multiply.outer(a, 42)
3611
+ assert_equal(res[0], a)
3612
+ assert_equal(res[1], np.multiply)
3613
+ assert_equal(res[2], 'outer')
3614
+ assert_equal(res[3], (a, 42))
3615
+ assert_equal(res[4], {})
3616
+
3617
+ # outer, wrong args
3618
+ assert_raises(TypeError, np.multiply.outer, a)
3619
+ assert_raises(TypeError, np.multiply.outer, a, a, a, a)
3620
+ assert_raises(TypeError, np.multiply.outer, a, a, sig='a', signature='a')
3621
+
3622
+ # at
3623
+ res = np.multiply.at(a, [4, 2], 'b0')
3624
+ assert_equal(res[0], a)
3625
+ assert_equal(res[1], np.multiply)
3626
+ assert_equal(res[2], 'at')
3627
+ assert_equal(res[3], (a, [4, 2], 'b0'))
3628
+
3629
+ # at, wrong args
3630
+ assert_raises(TypeError, np.multiply.at, a)
3631
+ assert_raises(TypeError, np.multiply.at, a, a, a, a)
3632
+
3633
+ def test_ufunc_override_out(self):
3634
+
3635
+ class A:
3636
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3637
+ return kwargs
3638
+
3639
+ class B:
3640
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3641
+ return kwargs
3642
+
3643
+ a = A()
3644
+ b = B()
3645
+ res0 = np.multiply(a, b, 'out_arg')
3646
+ res1 = np.multiply(a, b, out='out_arg')
3647
+ res2 = np.multiply(2, b, 'out_arg')
3648
+ res3 = np.multiply(3, b, out='out_arg')
3649
+ res4 = np.multiply(a, 4, 'out_arg')
3650
+ res5 = np.multiply(a, 5, out='out_arg')
3651
+
3652
+ assert_equal(res0['out'][0], 'out_arg')
3653
+ assert_equal(res1['out'][0], 'out_arg')
3654
+ assert_equal(res2['out'][0], 'out_arg')
3655
+ assert_equal(res3['out'][0], 'out_arg')
3656
+ assert_equal(res4['out'][0], 'out_arg')
3657
+ assert_equal(res5['out'][0], 'out_arg')
3658
+
3659
+ # ufuncs with multiple output modf and frexp.
3660
+ res6 = np.modf(a, 'out0', 'out1')
3661
+ res7 = np.frexp(a, 'out0', 'out1')
3662
+ assert_equal(res6['out'][0], 'out0')
3663
+ assert_equal(res6['out'][1], 'out1')
3664
+ assert_equal(res7['out'][0], 'out0')
3665
+ assert_equal(res7['out'][1], 'out1')
3666
+
3667
+ # While we're at it, check that default output is never passed on.
3668
+ assert_(np.sin(a, None) == {})
3669
+ assert_(np.sin(a, out=None) == {})
3670
+ assert_(np.sin(a, out=(None,)) == {})
3671
+ assert_(np.modf(a, None) == {})
3672
+ assert_(np.modf(a, None, None) == {})
3673
+ assert_(np.modf(a, out=(None, None)) == {})
3674
+ with assert_raises(TypeError):
3675
+ # Out argument must be tuple, since there are multiple outputs.
3676
+ np.modf(a, out=None)
3677
+
3678
+ # don't give positional and output argument, or too many arguments.
3679
+ # wrong number of arguments in the tuple is an error too.
3680
+ assert_raises(TypeError, np.multiply, a, b, 'one', out='two')
3681
+ assert_raises(TypeError, np.multiply, a, b, 'one', 'two')
3682
+ assert_raises(ValueError, np.multiply, a, b, out=('one', 'two'))
3683
+ assert_raises(TypeError, np.multiply, a, out=())
3684
+ assert_raises(TypeError, np.modf, a, 'one', out=('two', 'three'))
3685
+ assert_raises(TypeError, np.modf, a, 'one', 'two', 'three')
3686
+ assert_raises(ValueError, np.modf, a, out=('one', 'two', 'three'))
3687
+ assert_raises(ValueError, np.modf, a, out=('one',))
3688
+
3689
+ def test_ufunc_override_where(self):
3690
+
3691
+ class OverriddenArrayOld(np.ndarray):
3692
+
3693
+ def _unwrap(self, objs):
3694
+ cls = type(self)
3695
+ result = []
3696
+ for obj in objs:
3697
+ if isinstance(obj, cls):
3698
+ obj = np.array(obj)
3699
+ elif type(obj) != np.ndarray:
3700
+ return NotImplemented
3701
+ result.append(obj)
3702
+ return result
3703
+
3704
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3705
+
3706
+ inputs = self._unwrap(inputs)
3707
+ if inputs is NotImplemented:
3708
+ return NotImplemented
3709
+
3710
+ kwargs = kwargs.copy()
3711
+ if "out" in kwargs:
3712
+ kwargs["out"] = self._unwrap(kwargs["out"])
3713
+ if kwargs["out"] is NotImplemented:
3714
+ return NotImplemented
3715
+
3716
+ r = super().__array_ufunc__(ufunc, method, *inputs, **kwargs)
3717
+ if r is not NotImplemented:
3718
+ r = r.view(type(self))
3719
+
3720
+ return r
3721
+
3722
+ class OverriddenArrayNew(OverriddenArrayOld):
3723
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3724
+
3725
+ kwargs = kwargs.copy()
3726
+ if "where" in kwargs:
3727
+ kwargs["where"] = self._unwrap((kwargs["where"], ))
3728
+ if kwargs["where"] is NotImplemented:
3729
+ return NotImplemented
3730
+ else:
3731
+ kwargs["where"] = kwargs["where"][0]
3732
+
3733
+ r = super().__array_ufunc__(ufunc, method, *inputs, **kwargs)
3734
+ if r is not NotImplemented:
3735
+ r = r.view(type(self))
3736
+
3737
+ return r
3738
+
3739
+ ufunc = np.negative
3740
+
3741
+ array = np.array([1, 2, 3])
3742
+ where = np.array([True, False, True])
3743
+ expected = ufunc(array, where=where)
3744
+
3745
+ with pytest.raises(TypeError):
3746
+ ufunc(array, where=where.view(OverriddenArrayOld))
3747
+
3748
+ result_1 = ufunc(
3749
+ array,
3750
+ where=where.view(OverriddenArrayNew)
3751
+ )
3752
+ assert isinstance(result_1, OverriddenArrayNew)
3753
+ assert np.all(np.array(result_1) == expected, where=where)
3754
+
3755
+ result_2 = ufunc(
3756
+ array.view(OverriddenArrayNew),
3757
+ where=where.view(OverriddenArrayNew)
3758
+ )
3759
+ assert isinstance(result_2, OverriddenArrayNew)
3760
+ assert np.all(np.array(result_2) == expected, where=where)
3761
+
3762
+ def test_ufunc_override_exception(self):
3763
+
3764
+ class A:
3765
+ def __array_ufunc__(self, *a, **kwargs):
3766
+ raise ValueError("oops")
3767
+
3768
+ a = A()
3769
+ assert_raises(ValueError, np.negative, 1, out=a)
3770
+ assert_raises(ValueError, np.negative, a)
3771
+ assert_raises(ValueError, np.divide, 1., a)
3772
+
3773
+ def test_ufunc_override_not_implemented(self):
3774
+
3775
+ class A:
3776
+ def __array_ufunc__(self, *args, **kwargs):
3777
+ return NotImplemented
3778
+
3779
+ msg = ("operand type(s) all returned NotImplemented from "
3780
+ "__array_ufunc__(<ufunc 'negative'>, '__call__', <*>): 'A'")
3781
+ with assert_raises_regex(TypeError, fnmatch.translate(msg)):
3782
+ np.negative(A())
3783
+
3784
+ msg = ("operand type(s) all returned NotImplemented from "
3785
+ "__array_ufunc__(<ufunc 'add'>, '__call__', <*>, <object *>, "
3786
+ "out=(1,)): 'A', 'object', 'int'")
3787
+ with assert_raises_regex(TypeError, fnmatch.translate(msg)):
3788
+ np.add(A(), object(), out=1)
3789
+
3790
+ def test_ufunc_override_disabled(self):
3791
+
3792
+ class OptOut:
3793
+ __array_ufunc__ = None
3794
+
3795
+ opt_out = OptOut()
3796
+
3797
+ # ufuncs always raise
3798
+ msg = "operand 'OptOut' does not support ufuncs"
3799
+ with assert_raises_regex(TypeError, msg):
3800
+ np.add(opt_out, 1)
3801
+ with assert_raises_regex(TypeError, msg):
3802
+ np.add(1, opt_out)
3803
+ with assert_raises_regex(TypeError, msg):
3804
+ np.negative(opt_out)
3805
+
3806
+ # opt-outs still hold even when other arguments have pathological
3807
+ # __array_ufunc__ implementations
3808
+
3809
+ class GreedyArray:
3810
+ def __array_ufunc__(self, *args, **kwargs):
3811
+ return self
3812
+
3813
+ greedy = GreedyArray()
3814
+ assert_(np.negative(greedy) is greedy)
3815
+ with assert_raises_regex(TypeError, msg):
3816
+ np.add(greedy, opt_out)
3817
+ with assert_raises_regex(TypeError, msg):
3818
+ np.add(greedy, 1, out=opt_out)
3819
+
3820
+ def test_gufunc_override(self):
3821
+ # gufunc are just ufunc instances, but follow a different path,
3822
+ # so check __array_ufunc__ overrides them properly.
3823
+ class A:
3824
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3825
+ return self, ufunc, method, inputs, kwargs
3826
+
3827
+ inner1d = ncu_tests.inner1d
3828
+ a = A()
3829
+ res = inner1d(a, a)
3830
+ assert_equal(res[0], a)
3831
+ assert_equal(res[1], inner1d)
3832
+ assert_equal(res[2], '__call__')
3833
+ assert_equal(res[3], (a, a))
3834
+ assert_equal(res[4], {})
3835
+
3836
+ res = inner1d(1, 1, out=a)
3837
+ assert_equal(res[0], a)
3838
+ assert_equal(res[1], inner1d)
3839
+ assert_equal(res[2], '__call__')
3840
+ assert_equal(res[3], (1, 1))
3841
+ assert_equal(res[4], {'out': (a,)})
3842
+
3843
+ # wrong number of arguments in the tuple is an error too.
3844
+ assert_raises(TypeError, inner1d, a, out='two')
3845
+ assert_raises(TypeError, inner1d, a, a, 'one', out='two')
3846
+ assert_raises(TypeError, inner1d, a, a, 'one', 'two')
3847
+ assert_raises(ValueError, inner1d, a, a, out=('one', 'two'))
3848
+ assert_raises(ValueError, inner1d, a, a, out=())
3849
+
3850
+ def test_ufunc_override_with_super(self):
3851
+ # NOTE: this class is used in doc/source/user/basics.subclassing.rst
3852
+ # if you make any changes here, do update it there too.
3853
+ class A(np.ndarray):
3854
+ def __array_ufunc__(self, ufunc, method, *inputs, out=None, **kwargs):
3855
+ args = []
3856
+ in_no = []
3857
+ for i, input_ in enumerate(inputs):
3858
+ if isinstance(input_, A):
3859
+ in_no.append(i)
3860
+ args.append(input_.view(np.ndarray))
3861
+ else:
3862
+ args.append(input_)
3863
+
3864
+ outputs = out
3865
+ out_no = []
3866
+ if outputs:
3867
+ out_args = []
3868
+ for j, output in enumerate(outputs):
3869
+ if isinstance(output, A):
3870
+ out_no.append(j)
3871
+ out_args.append(output.view(np.ndarray))
3872
+ else:
3873
+ out_args.append(output)
3874
+ kwargs['out'] = tuple(out_args)
3875
+ else:
3876
+ outputs = (None,) * ufunc.nout
3877
+
3878
+ info = {}
3879
+ if in_no:
3880
+ info['inputs'] = in_no
3881
+ if out_no:
3882
+ info['outputs'] = out_no
3883
+
3884
+ results = super().__array_ufunc__(ufunc, method,
3885
+ *args, **kwargs)
3886
+ if results is NotImplemented:
3887
+ return NotImplemented
3888
+
3889
+ if method == 'at':
3890
+ if isinstance(inputs[0], A):
3891
+ inputs[0].info = info
3892
+ return
3893
+
3894
+ if ufunc.nout == 1:
3895
+ results = (results,)
3896
+
3897
+ results = tuple((np.asarray(result).view(A)
3898
+ if output is None else output)
3899
+ for result, output in zip(results, outputs))
3900
+ if results and isinstance(results[0], A):
3901
+ results[0].info = info
3902
+
3903
+ return results[0] if len(results) == 1 else results
3904
+
3905
+ class B:
3906
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
3907
+ if any(isinstance(input_, A) for input_ in inputs):
3908
+ return "A!"
3909
+ else:
3910
+ return NotImplemented
3911
+
3912
+ d = np.arange(5.)
3913
+ # 1 input, 1 output
3914
+ a = np.arange(5.).view(A)
3915
+ b = np.sin(a)
3916
+ check = np.sin(d)
3917
+ assert_(np.all(check == b))
3918
+ assert_equal(b.info, {'inputs': [0]})
3919
+ b = np.sin(d, out=(a,))
3920
+ assert_(np.all(check == b))
3921
+ assert_equal(b.info, {'outputs': [0]})
3922
+ assert_(b is a)
3923
+ a = np.arange(5.).view(A)
3924
+ b = np.sin(a, out=a)
3925
+ assert_(np.all(check == b))
3926
+ assert_equal(b.info, {'inputs': [0], 'outputs': [0]})
3927
+
3928
+ # 1 input, 2 outputs
3929
+ a = np.arange(5.).view(A)
3930
+ b1, b2 = np.modf(a)
3931
+ assert_equal(b1.info, {'inputs': [0]})
3932
+ b1, b2 = np.modf(d, out=(None, a))
3933
+ assert_(b2 is a)
3934
+ assert_equal(b1.info, {'outputs': [1]})
3935
+ a = np.arange(5.).view(A)
3936
+ b = np.arange(5.).view(A)
3937
+ c1, c2 = np.modf(a, out=(a, b))
3938
+ assert_(c1 is a)
3939
+ assert_(c2 is b)
3940
+ assert_equal(c1.info, {'inputs': [0], 'outputs': [0, 1]})
3941
+
3942
+ # 2 input, 1 output
3943
+ a = np.arange(5.).view(A)
3944
+ b = np.arange(5.).view(A)
3945
+ c = np.add(a, b, out=a)
3946
+ assert_(c is a)
3947
+ assert_equal(c.info, {'inputs': [0, 1], 'outputs': [0]})
3948
+ # some tests with a non-ndarray subclass
3949
+ a = np.arange(5.)
3950
+ b = B()
3951
+ assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
3952
+ assert_(b.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
3953
+ assert_raises(TypeError, np.add, a, b)
3954
+ a = a.view(A)
3955
+ assert_(a.__array_ufunc__(np.add, '__call__', a, b) is NotImplemented)
3956
+ assert_(b.__array_ufunc__(np.add, '__call__', a, b) == "A!")
3957
+ assert_(np.add(a, b) == "A!")
3958
+ # regression check for gh-9102 -- tests ufunc.reduce implicitly.
3959
+ d = np.array([[1, 2, 3], [1, 2, 3]])
3960
+ a = d.view(A)
3961
+ c = a.any()
3962
+ check = d.any()
3963
+ assert_equal(c, check)
3964
+ assert_(c.info, {'inputs': [0]})
3965
+ c = a.max()
3966
+ check = d.max()
3967
+ assert_equal(c, check)
3968
+ assert_(c.info, {'inputs': [0]})
3969
+ b = np.array(0).view(A)
3970
+ c = a.max(out=b)
3971
+ assert_equal(c, check)
3972
+ assert_(c is b)
3973
+ assert_(c.info, {'inputs': [0], 'outputs': [0]})
3974
+ check = a.max(axis=0)
3975
+ b = np.zeros_like(check).view(A)
3976
+ c = a.max(axis=0, out=b)
3977
+ assert_equal(c, check)
3978
+ assert_(c is b)
3979
+ assert_(c.info, {'inputs': [0], 'outputs': [0]})
3980
+ # simple explicit tests of reduce, accumulate, reduceat
3981
+ check = np.add.reduce(d, axis=1)
3982
+ c = np.add.reduce(a, axis=1)
3983
+ assert_equal(c, check)
3984
+ assert_(c.info, {'inputs': [0]})
3985
+ b = np.zeros_like(c)
3986
+ c = np.add.reduce(a, 1, None, b)
3987
+ assert_equal(c, check)
3988
+ assert_(c is b)
3989
+ assert_(c.info, {'inputs': [0], 'outputs': [0]})
3990
+ check = np.add.accumulate(d, axis=0)
3991
+ c = np.add.accumulate(a, axis=0)
3992
+ assert_equal(c, check)
3993
+ assert_(c.info, {'inputs': [0]})
3994
+ b = np.zeros_like(c)
3995
+ c = np.add.accumulate(a, 0, None, b)
3996
+ assert_equal(c, check)
3997
+ assert_(c is b)
3998
+ assert_(c.info, {'inputs': [0], 'outputs': [0]})
3999
+ indices = [0, 2, 1]
4000
+ check = np.add.reduceat(d, indices, axis=1)
4001
+ c = np.add.reduceat(a, indices, axis=1)
4002
+ assert_equal(c, check)
4003
+ assert_(c.info, {'inputs': [0]})
4004
+ b = np.zeros_like(c)
4005
+ c = np.add.reduceat(a, indices, 1, None, b)
4006
+ assert_equal(c, check)
4007
+ assert_(c is b)
4008
+ assert_(c.info, {'inputs': [0], 'outputs': [0]})
4009
+ # and a few tests for at
4010
+ d = np.array([[1, 2, 3], [1, 2, 3]])
4011
+ check = d.copy()
4012
+ a = d.copy().view(A)
4013
+ np.add.at(check, ([0, 1], [0, 2]), 1.)
4014
+ np.add.at(a, ([0, 1], [0, 2]), 1.)
4015
+ assert_equal(a, check)
4016
+ assert_(a.info, {'inputs': [0]})
4017
+ b = np.array(1.).view(A)
4018
+ a = d.copy().view(A)
4019
+ np.add.at(a, ([0, 1], [0, 2]), b)
4020
+ assert_equal(a, check)
4021
+ assert_(a.info, {'inputs': [0, 2]})
4022
+
4023
+ def test_array_ufunc_direct_call(self):
4024
+ # This is mainly a regression test for gh-24023 (shouldn't segfault)
4025
+ a = np.array(1)
4026
+ with pytest.raises(TypeError):
4027
+ a.__array_ufunc__()
4028
+
4029
+ # No kwargs means kwargs may be NULL on the C-level
4030
+ with pytest.raises(TypeError):
4031
+ a.__array_ufunc__(1, 2)
4032
+
4033
+ # And the same with a valid call:
4034
+ res = a.__array_ufunc__(np.add, "__call__", a, a)
4035
+ assert_array_equal(res, a + a)
4036
+
4037
+ def test_ufunc_docstring(self):
4038
+ original_doc = np.add.__doc__
4039
+ new_doc = "new docs"
4040
+ expected_dict = (
4041
+ {} if IS_PYPY else {"__module__": "numpy", "__qualname__": "add"}
4042
+ )
4043
+
4044
+ np.add.__doc__ = new_doc
4045
+ assert np.add.__doc__ == new_doc
4046
+ assert np.add.__dict__["__doc__"] == new_doc
4047
+
4048
+ del np.add.__doc__
4049
+ assert np.add.__doc__ == original_doc
4050
+ assert np.add.__dict__ == expected_dict
4051
+
4052
+ np.add.__dict__["other"] = 1
4053
+ np.add.__dict__["__doc__"] = new_doc
4054
+ assert np.add.__doc__ == new_doc
4055
+
4056
+ del np.add.__dict__["__doc__"]
4057
+ assert np.add.__doc__ == original_doc
4058
+ del np.add.__dict__["other"]
4059
+ assert np.add.__dict__ == expected_dict
4060
+
4061
+
4062
+ class TestChoose:
4063
+ def test_mixed(self):
4064
+ c = np.array([True, True])
4065
+ a = np.array([True, True])
4066
+ assert_equal(np.choose(c, (a, 1)), np.array([1, 1]))
4067
+
4068
+
4069
+ class TestRationalFunctions:
4070
+ def test_lcm(self):
4071
+ self._test_lcm_inner(np.int16)
4072
+ self._test_lcm_inner(np.uint16)
4073
+
4074
+ def test_lcm_object(self):
4075
+ self._test_lcm_inner(np.object_)
4076
+
4077
+ def test_gcd(self):
4078
+ self._test_gcd_inner(np.int16)
4079
+ self._test_lcm_inner(np.uint16)
4080
+
4081
+ def test_gcd_object(self):
4082
+ self._test_gcd_inner(np.object_)
4083
+
4084
+ def _test_lcm_inner(self, dtype):
4085
+ # basic use
4086
+ a = np.array([12, 120], dtype=dtype)
4087
+ b = np.array([20, 200], dtype=dtype)
4088
+ assert_equal(np.lcm(a, b), [60, 600])
4089
+
4090
+ if not issubclass(dtype, np.unsignedinteger):
4091
+ # negatives are ignored
4092
+ a = np.array([12, -12, 12, -12], dtype=dtype)
4093
+ b = np.array([20, 20, -20, -20], dtype=dtype)
4094
+ assert_equal(np.lcm(a, b), [60] * 4)
4095
+
4096
+ # reduce
4097
+ a = np.array([3, 12, 20], dtype=dtype)
4098
+ assert_equal(np.lcm.reduce([3, 12, 20]), 60)
4099
+
4100
+ # broadcasting, and a test including 0
4101
+ a = np.arange(6).astype(dtype)
4102
+ b = 20
4103
+ assert_equal(np.lcm(a, b), [0, 20, 20, 60, 20, 20])
4104
+
4105
+ def _test_gcd_inner(self, dtype):
4106
+ # basic use
4107
+ a = np.array([12, 120], dtype=dtype)
4108
+ b = np.array([20, 200], dtype=dtype)
4109
+ assert_equal(np.gcd(a, b), [4, 40])
4110
+
4111
+ if not issubclass(dtype, np.unsignedinteger):
4112
+ # negatives are ignored
4113
+ a = np.array([12, -12, 12, -12], dtype=dtype)
4114
+ b = np.array([20, 20, -20, -20], dtype=dtype)
4115
+ assert_equal(np.gcd(a, b), [4] * 4)
4116
+
4117
+ # reduce
4118
+ a = np.array([15, 25, 35], dtype=dtype)
4119
+ assert_equal(np.gcd.reduce(a), 5)
4120
+
4121
+ # broadcasting, and a test including 0
4122
+ a = np.arange(6).astype(dtype)
4123
+ b = 20
4124
+ assert_equal(np.gcd(a, b), [20, 1, 2, 1, 4, 5])
4125
+
4126
+ def test_lcm_overflow(self):
4127
+ # verify that we don't overflow when a*b does overflow
4128
+ big = np.int32(np.iinfo(np.int32).max // 11)
4129
+ a = 2 * big
4130
+ b = 5 * big
4131
+ assert_equal(np.lcm(a, b), 10 * big)
4132
+
4133
+ def test_gcd_overflow(self):
4134
+ for dtype in (np.int32, np.int64):
4135
+ # verify that we don't overflow when taking abs(x)
4136
+ # not relevant for lcm, where the result is unrepresentable anyway
4137
+ a = dtype(np.iinfo(dtype).min) # negative power of two
4138
+ q = -(a // 4)
4139
+ assert_equal(np.gcd(a, q * 3), q)
4140
+ assert_equal(np.gcd(a, -q * 3), q)
4141
+
4142
+ def test_decimal(self):
4143
+ from decimal import Decimal
4144
+ a = np.array([1, 1, -1, -1]) * Decimal('0.20')
4145
+ b = np.array([1, -1, 1, -1]) * Decimal('0.12')
4146
+
4147
+ assert_equal(np.gcd(a, b), 4 * [Decimal('0.04')])
4148
+ assert_equal(np.lcm(a, b), 4 * [Decimal('0.60')])
4149
+
4150
+ def test_float(self):
4151
+ # not well-defined on float due to rounding errors
4152
+ assert_raises(TypeError, np.gcd, 0.3, 0.4)
4153
+ assert_raises(TypeError, np.lcm, 0.3, 0.4)
4154
+
4155
+ def test_huge_integers(self):
4156
+ # Converting to an array first is a bit different as it means we
4157
+ # have an explicit object dtype:
4158
+ assert_equal(np.array(2**200), 2**200)
4159
+ # Special promotion rules should ensure that this also works for
4160
+ # two Python integers (even if slow).
4161
+ # (We do this for comparisons, as the result is always bool and
4162
+ # we also special case array comparisons with Python integers)
4163
+ np.equal(2**200, 2**200)
4164
+
4165
+ # But, we cannot do this when it would affect the result dtype:
4166
+ with pytest.raises(OverflowError):
4167
+ np.gcd(2**100, 3**100)
4168
+
4169
+ # Asking for `object` explicitly is fine, though:
4170
+ assert np.gcd(2**100, 3**100, dtype=object) == 1
4171
+
4172
+ # As of now, the below work, because it is using arrays (which
4173
+ # will be object arrays)
4174
+ a = np.array(2**100 * 3**5)
4175
+ b = np.array([2**100 * 5**7, 2**50 * 3**10])
4176
+ assert_equal(np.gcd(a, b), [2**100, 2**50 * 3**5])
4177
+ assert_equal(np.lcm(a, b), [2**100 * 3**5 * 5**7, 2**100 * 3**10])
4178
+
4179
+ def test_inf_and_nan(self):
4180
+ inf = np.array([np.inf], dtype=np.object_)
4181
+ assert_raises(ValueError, np.gcd, inf, 1)
4182
+ assert_raises(ValueError, np.gcd, 1, inf)
4183
+ assert_raises(ValueError, np.gcd, np.nan, inf)
4184
+ assert_raises(TypeError, np.gcd, 4, float(np.inf))
4185
+
4186
+
4187
+ class TestRoundingFunctions:
4188
+
4189
+ def test_object_direct(self):
4190
+ """ test direct implementation of these magic methods """
4191
+ class C:
4192
+ def __floor__(self):
4193
+ return 1
4194
+
4195
+ def __ceil__(self):
4196
+ return 2
4197
+
4198
+ def __trunc__(self):
4199
+ return 3
4200
+
4201
+ arr = np.array([C(), C()])
4202
+ assert_equal(np.floor(arr), [1, 1])
4203
+ assert_equal(np.ceil(arr), [2, 2])
4204
+ assert_equal(np.trunc(arr), [3, 3])
4205
+
4206
+ def test_object_indirect(self):
4207
+ """ test implementations via __float__ """
4208
+ class C:
4209
+ def __float__(self):
4210
+ return -2.5
4211
+
4212
+ arr = np.array([C(), C()])
4213
+ assert_equal(np.floor(arr), [-3, -3])
4214
+ assert_equal(np.ceil(arr), [-2, -2])
4215
+ with pytest.raises(TypeError):
4216
+ np.trunc(arr) # consistent with math.trunc
4217
+
4218
+ def test_fraction(self):
4219
+ f = Fraction(-4, 3)
4220
+ assert_equal(np.floor(f), -2)
4221
+ assert_equal(np.ceil(f), -1)
4222
+ assert_equal(np.trunc(f), -1)
4223
+
4224
+ @pytest.mark.parametrize('func', [np.floor, np.ceil, np.trunc])
4225
+ @pytest.mark.parametrize('dtype', [np.bool, np.float64, np.float32,
4226
+ np.int64, np.uint32])
4227
+ def test_output_dtype(self, func, dtype):
4228
+ arr = np.array([-2, 0, 4, 8]).astype(dtype)
4229
+ result = func(arr)
4230
+ assert_equal(arr, result)
4231
+ assert result.dtype == dtype
4232
+
4233
+
4234
+ class TestComplexFunctions:
4235
+ funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh,
4236
+ np.arctanh, np.sin, np.cos, np.tan, np.exp,
4237
+ np.exp2, np.log, np.sqrt, np.log10, np.log2,
4238
+ np.log1p]
4239
+
4240
+ def test_it(self):
4241
+ for f in self.funcs:
4242
+ if f is np.arccosh:
4243
+ x = 1.5
4244
+ else:
4245
+ x = .5
4246
+ fr = f(x)
4247
+ fz = f(complex(x))
4248
+ assert_almost_equal(fz.real, fr, err_msg=f'real part {f}')
4249
+ assert_almost_equal(fz.imag, 0., err_msg=f'imag part {f}')
4250
+
4251
+ @pytest.mark.xfail(IS_WASM, reason="doesn't work")
4252
+ def test_precisions_consistent(self):
4253
+ z = 1 + 1j
4254
+ for f in self.funcs:
4255
+ fcf = f(np.csingle(z))
4256
+ fcd = f(np.cdouble(z))
4257
+ fcl = f(np.clongdouble(z))
4258
+ assert_almost_equal(fcf, fcd, decimal=6, err_msg=f'fch-fcd {f}')
4259
+ assert_almost_equal(fcl, fcd, decimal=15, err_msg=f'fch-fcl {f}')
4260
+
4261
+ @pytest.mark.xfail(IS_WASM, reason="doesn't work")
4262
+ def test_branch_cuts(self):
4263
+ # check branch cuts and continuity on them
4264
+ _check_branch_cut(np.log, -0.5, 1j, 1, -1, True) # noqa: E221
4265
+ _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True) # noqa: E221
4266
+ _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True)
4267
+ _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True)
4268
+ _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True) # noqa: E221
4269
+
4270
+ _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True)
4271
+ _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True)
4272
+ _check_branch_cut(np.arctan, [0 - 2j, 2j], [1, 1], -1, 1, True)
4273
+
4274
+ _check_branch_cut(np.arcsinh, [0 - 2j, 2j], [1, 1], -1, 1, True)
4275
+ _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True)
4276
+ _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True)
4277
+
4278
+ # check against bogus branch cuts: assert continuity between quadrants
4279
+ _check_branch_cut(np.arcsin, [0 - 2j, 2j], [ 1, 1], 1, 1)
4280
+ _check_branch_cut(np.arccos, [0 - 2j, 2j], [ 1, 1], 1, 1)
4281
+ _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1)
4282
+
4283
+ _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1)
4284
+ _check_branch_cut(np.arccosh, [0 - 2j, 2j, 2], [1, 1, 1j], 1, 1)
4285
+ _check_branch_cut(np.arctanh, [0 - 2j, 2j, 0], [1, 1, 1j], 1, 1)
4286
+
4287
+ @pytest.mark.xfail(IS_WASM, reason="doesn't work")
4288
+ def test_branch_cuts_complex64(self):
4289
+ # check branch cuts and continuity on them
4290
+ _check_branch_cut(np.log, -0.5, 1j, 1, -1, True, np.complex64) # noqa: E221
4291
+ _check_branch_cut(np.log2, -0.5, 1j, 1, -1, True, np.complex64) # noqa: E221
4292
+ _check_branch_cut(np.log10, -0.5, 1j, 1, -1, True, np.complex64)
4293
+ _check_branch_cut(np.log1p, -1.5, 1j, 1, -1, True, np.complex64)
4294
+ _check_branch_cut(np.sqrt, -0.5, 1j, 1, -1, True, np.complex64) # noqa: E221
4295
+
4296
+ _check_branch_cut(np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
4297
+ _check_branch_cut(np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
4298
+ _check_branch_cut(np.arctan, [0 - 2j, 2j], [1, 1], -1, 1, True, np.complex64)
4299
+
4300
+ _check_branch_cut(np.arcsinh, [0 - 2j, 2j], [1, 1], -1, 1, True, np.complex64)
4301
+ _check_branch_cut(np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64)
4302
+ _check_branch_cut(np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64)
4303
+
4304
+ # check against bogus branch cuts: assert continuity between quadrants
4305
+ _check_branch_cut(np.arcsin, [0 - 2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
4306
+ _check_branch_cut(np.arccos, [0 - 2j, 2j], [ 1, 1], 1, 1, False, np.complex64)
4307
+ _check_branch_cut(np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64)
4308
+
4309
+ _check_branch_cut(np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64)
4310
+ _check_branch_cut(np.arccosh, [0 - 2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64)
4311
+ _check_branch_cut(np.arctanh, [0 - 2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64)
4312
+
4313
+ def test_against_cmath(self):
4314
+ import cmath
4315
+
4316
+ points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
4317
+ name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
4318
+ 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
4319
+ atol = 4 * np.finfo(complex).eps
4320
+ for func in self.funcs:
4321
+ fname = func.__name__.split('.')[-1]
4322
+ cname = name_map.get(fname, fname)
4323
+ try:
4324
+ cfunc = getattr(cmath, cname)
4325
+ except AttributeError:
4326
+ continue
4327
+ for p in points:
4328
+ a = complex(func(np.complex128(p)))
4329
+ b = cfunc(p)
4330
+ assert_(
4331
+ abs(a - b) < atol,
4332
+ f"{fname} {p}: {a}; cmath: {b}"
4333
+ )
4334
+
4335
+ @pytest.mark.xfail(
4336
+ # manylinux2014 uses glibc2.17
4337
+ _glibc_older_than("2.18"),
4338
+ reason="Older glibc versions are imprecise (maybe passes with SIMD?)"
4339
+ )
4340
+ @pytest.mark.xfail(IS_WASM, reason="doesn't work")
4341
+ @pytest.mark.parametrize('dtype', [
4342
+ np.complex64, np.complex128, np.clongdouble
4343
+ ])
4344
+ def test_loss_of_precision(self, dtype):
4345
+ """Check loss of precision in complex arc* functions"""
4346
+ if dtype is np.clongdouble and platform.machine() != 'x86_64':
4347
+ # Failures on musllinux, aarch64, s390x, ppc64le (see gh-17554)
4348
+ pytest.skip('Only works reliably for x86-64 and recent glibc')
4349
+
4350
+ # Check against known-good functions
4351
+
4352
+ info = np.finfo(dtype)
4353
+ real_dtype = dtype(0.).real.dtype
4354
+ eps = info.eps
4355
+
4356
+ def check(x, rtol):
4357
+ x = x.astype(real_dtype)
4358
+
4359
+ z = x.astype(dtype)
4360
+ d = np.absolute(np.arcsinh(x) / np.arcsinh(z).real - 1)
4361
+ assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
4362
+ 'arcsinh'))
4363
+
4364
+ z = (1j * x).astype(dtype)
4365
+ d = np.absolute(np.arcsinh(x) / np.arcsin(z).imag - 1)
4366
+ assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
4367
+ 'arcsin'))
4368
+
4369
+ z = x.astype(dtype)
4370
+ d = np.absolute(np.arctanh(x) / np.arctanh(z).real - 1)
4371
+ assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
4372
+ 'arctanh'))
4373
+
4374
+ z = (1j * x).astype(dtype)
4375
+ d = np.absolute(np.arctanh(x) / np.arctan(z).imag - 1)
4376
+ assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),
4377
+ 'arctan'))
4378
+
4379
+ # The switchover was chosen as 1e-3; hence there can be up to
4380
+ # ~eps/1e-3 of relative cancellation error before it
4381
+
4382
+ x_series = np.logspace(-20, -3.001, 200)
4383
+ x_basic = np.logspace(-2.999, 0, 10, endpoint=False)
4384
+
4385
+ if dtype is np.clongdouble:
4386
+ if bad_arcsinh():
4387
+ pytest.skip("Trig functions of np.clongdouble values known "
4388
+ "to be inaccurate on aarch64 and PPC for some "
4389
+ "compilation configurations.")
4390
+ # It's not guaranteed that the system-provided arc functions
4391
+ # are accurate down to a few epsilons. (Eg. on Linux 64-bit)
4392
+ # So, give more leeway for long complex tests here:
4393
+ check(x_series, 50.0 * eps)
4394
+ else:
4395
+ check(x_series, 2.1 * eps)
4396
+ check(x_basic, 2.0 * eps / 1e-3)
4397
+
4398
+ # Check a few points
4399
+
4400
+ z = np.array([1e-5 * (1 + 1j)], dtype=dtype)
4401
+ p = 9.999999999333333333e-6 + 1.000000000066666666e-5j
4402
+ d = np.absolute(1 - np.arctanh(z) / p)
4403
+ assert_(np.all(d < 1e-15))
4404
+
4405
+ p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j
4406
+ d = np.absolute(1 - np.arcsinh(z) / p)
4407
+ assert_(np.all(d < 1e-15))
4408
+
4409
+ p = 9.999999999333333333e-6j + 1.000000000066666666e-5
4410
+ d = np.absolute(1 - np.arctan(z) / p)
4411
+ assert_(np.all(d < 1e-15))
4412
+
4413
+ p = 1.0000000000333333333e-5j + 9.999999999666666667e-6
4414
+ d = np.absolute(1 - np.arcsin(z) / p)
4415
+ assert_(np.all(d < 1e-15))
4416
+
4417
+ # Check continuity across switchover points
4418
+
4419
+ def check(func, z0, d=1):
4420
+ z0 = np.asarray(z0, dtype=dtype)
4421
+ zp = z0 + abs(z0) * d * eps * 2
4422
+ zm = z0 - abs(z0) * d * eps * 2
4423
+ assert_(np.all(zp != zm), (zp, zm))
4424
+
4425
+ # NB: the cancellation error at the switchover is at least eps
4426
+ good = (abs(func(zp) - func(zm)) < 2 * eps)
4427
+ assert_(np.all(good), (func, z0[~good]))
4428
+
4429
+ for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan):
4430
+ pts = [rp + 1j * ip for rp in (-1e-3, 0, 1e-3) for ip in (-1e-3, 0, 1e-3)
4431
+ if rp != 0 or ip != 0]
4432
+ check(func, pts, 1)
4433
+ check(func, pts, 1j)
4434
+ check(func, pts, 1 + 1j)
4435
+
4436
+ @np.errstate(all="ignore")
4437
+ def test_promotion_corner_cases(self):
4438
+ for func in self.funcs:
4439
+ assert func(np.float16(1)).dtype == np.float16
4440
+ # Integer to low precision float promotion is a dubious choice:
4441
+ assert func(np.uint8(1)).dtype == np.float16
4442
+ assert func(np.int16(1)).dtype == np.float32
4443
+
4444
+
4445
+ class TestAttributes:
4446
+ def test_attributes(self):
4447
+ add = ncu.add
4448
+ assert_equal(add.__name__, 'add')
4449
+ assert_(add.ntypes >= 18) # don't fail if types added
4450
+ assert_('ii->i' in add.types)
4451
+ assert_equal(add.nin, 2)
4452
+ assert_equal(add.nout, 1)
4453
+ assert_equal(add.identity, 0)
4454
+
4455
+ def test_doc(self):
4456
+ # don't bother checking the long list of kwargs, which are likely to
4457
+ # change
4458
+ assert_(ncu.add.__doc__.startswith(
4459
+ "add(x1, x2, /, out=None, *, where=True"))
4460
+ assert_(ncu.frexp.__doc__.startswith(
4461
+ "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True"))
4462
+
4463
+
4464
+ class TestSubclass:
4465
+
4466
+ def test_subclass_op(self):
4467
+
4468
+ class simple(np.ndarray):
4469
+ def __new__(subtype, shape):
4470
+ self = np.ndarray.__new__(subtype, shape, dtype=object)
4471
+ self.fill(0)
4472
+ return self
4473
+
4474
+ a = simple((3, 4))
4475
+ assert_equal(a + a, a)
4476
+
4477
+
4478
+ class TestFrompyfunc:
4479
+
4480
+ def test_identity(self):
4481
+ def mul(a, b):
4482
+ return a * b
4483
+
4484
+ # with identity=value
4485
+ mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=1)
4486
+ assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
4487
+ assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
4488
+ assert_equal(mul_ufunc.reduce([]), 1)
4489
+
4490
+ # with identity=None (reorderable)
4491
+ mul_ufunc = np.frompyfunc(mul, nin=2, nout=1, identity=None)
4492
+ assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
4493
+ assert_equal(mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)), 1)
4494
+ assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
4495
+
4496
+ # with no identity (not reorderable)
4497
+ mul_ufunc = np.frompyfunc(mul, nin=2, nout=1)
4498
+ assert_equal(mul_ufunc.reduce([2, 3, 4]), 24)
4499
+ assert_raises(ValueError, lambda: mul_ufunc.reduce(np.ones((2, 2)), axis=(0, 1)))
4500
+ assert_raises(ValueError, lambda: mul_ufunc.reduce([]))
4501
+
4502
+
4503
+ def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False,
4504
+ dtype=complex):
4505
+ """
4506
+ Check for a branch cut in a function.
4507
+
4508
+ Assert that `x0` lies on a branch cut of function `f` and `f` is
4509
+ continuous from the direction `dx`.
4510
+
4511
+ Parameters
4512
+ ----------
4513
+ f : func
4514
+ Function to check
4515
+ x0 : array-like
4516
+ Point on branch cut
4517
+ dx : array-like
4518
+ Direction to check continuity in
4519
+ re_sign, im_sign : {1, -1}
4520
+ Change of sign of the real or imaginary part expected
4521
+ sig_zero_ok : bool
4522
+ Whether to check if the branch cut respects signed zero (if applicable)
4523
+ dtype : dtype
4524
+ Dtype to check (should be complex)
4525
+
4526
+ """
4527
+ x0 = np.atleast_1d(x0).astype(dtype)
4528
+ dx = np.atleast_1d(dx).astype(dtype)
4529
+
4530
+ if np.dtype(dtype).char == 'F':
4531
+ scale = np.finfo(dtype).eps * 1e2
4532
+ atol = np.float32(1e-2)
4533
+ else:
4534
+ scale = np.finfo(dtype).eps * 1e3
4535
+ atol = 1e-4
4536
+
4537
+ y0 = f(x0)
4538
+ yp = f(x0 + dx * scale * np.absolute(x0) / np.absolute(dx))
4539
+ ym = f(x0 - dx * scale * np.absolute(x0) / np.absolute(dx))
4540
+
4541
+ assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp))
4542
+ assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp))
4543
+ assert_(np.all(np.absolute(y0.real - ym.real * re_sign) < atol), (y0, ym))
4544
+ assert_(np.all(np.absolute(y0.imag - ym.imag * im_sign) < atol), (y0, ym))
4545
+
4546
+ if sig_zero_ok:
4547
+ # check that signed zeros also work as a displacement
4548
+ jr = (x0.real == 0) & (dx.real != 0)
4549
+ ji = (x0.imag == 0) & (dx.imag != 0)
4550
+ if np.any(jr):
4551
+ x = x0[jr]
4552
+ x.real = ncu.NZERO
4553
+ ym = f(x)
4554
+ assert_(np.all(np.absolute(y0[jr].real - ym.real * re_sign) < atol), (y0[jr], ym))
4555
+ assert_(np.all(np.absolute(y0[jr].imag - ym.imag * im_sign) < atol), (y0[jr], ym))
4556
+
4557
+ if np.any(ji):
4558
+ x = x0[ji]
4559
+ x.imag = ncu.NZERO
4560
+ ym = f(x)
4561
+ assert_(np.all(np.absolute(y0[ji].real - ym.real * re_sign) < atol), (y0[ji], ym))
4562
+ assert_(np.all(np.absolute(y0[ji].imag - ym.imag * im_sign) < atol), (y0[ji], ym))
4563
+
4564
+ def test_copysign():
4565
+ assert_(np.copysign(1, -1) == -1)
4566
+ with np.errstate(divide="ignore"):
4567
+ assert_(1 / np.copysign(0, -1) < 0)
4568
+ assert_(1 / np.copysign(0, 1) > 0)
4569
+ assert_(np.signbit(np.copysign(np.nan, -1)))
4570
+ assert_(not np.signbit(np.copysign(np.nan, 1)))
4571
+
4572
+ def _test_nextafter(t):
4573
+ one = t(1)
4574
+ two = t(2)
4575
+ zero = t(0)
4576
+ eps = np.finfo(t).eps
4577
+ assert_(np.nextafter(one, two) - one == eps)
4578
+ assert_(np.nextafter(one, zero) - one < 0)
4579
+ assert_(np.isnan(np.nextafter(np.nan, one)))
4580
+ assert_(np.isnan(np.nextafter(one, np.nan)))
4581
+ assert_(np.nextafter(one, one) == one)
4582
+
4583
+ def test_nextafter():
4584
+ return _test_nextafter(np.float64)
4585
+
4586
+
4587
+ def test_nextafterf():
4588
+ return _test_nextafter(np.float32)
4589
+
4590
+
4591
+ @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
4592
+ reason="long double is same as double")
4593
+ @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
4594
+ reason="IBM double double")
4595
+ def test_nextafterl():
4596
+ return _test_nextafter(np.longdouble)
4597
+
4598
+
4599
+ def test_nextafter_0():
4600
+ for t, direction in itertools.product(np._core.sctypes['float'], (1, -1)):
4601
+ # The value of tiny for double double is NaN, so we need to pass the
4602
+ # assert
4603
+ with suppress_warnings() as sup:
4604
+ sup.filter(UserWarning)
4605
+ if not np.isnan(np.finfo(t).tiny):
4606
+ tiny = np.finfo(t).tiny
4607
+ assert_(
4608
+ 0. < direction * np.nextafter(t(0), t(direction)) < tiny)
4609
+ assert_equal(np.nextafter(t(0), t(direction)) / t(2.1), direction * 0.0)
4610
+
4611
+ def _test_spacing(t):
4612
+ one = t(1)
4613
+ eps = np.finfo(t).eps
4614
+ nan = t(np.nan)
4615
+ inf = t(np.inf)
4616
+ with np.errstate(invalid='ignore'):
4617
+ assert_equal(np.spacing(one), eps)
4618
+ assert_(np.isnan(np.spacing(nan)))
4619
+ assert_(np.isnan(np.spacing(inf)))
4620
+ assert_(np.isnan(np.spacing(-inf)))
4621
+ assert_(np.spacing(t(1e30)) != 0)
4622
+
4623
+ def test_spacing():
4624
+ return _test_spacing(np.float64)
4625
+
4626
+ def test_spacingf():
4627
+ return _test_spacing(np.float32)
4628
+
4629
+
4630
+ @pytest.mark.skipif(np.finfo(np.double) == np.finfo(np.longdouble),
4631
+ reason="long double is same as double")
4632
+ @pytest.mark.xfail(condition=platform.machine().startswith("ppc64"),
4633
+ reason="IBM double double")
4634
+ def test_spacingl():
4635
+ return _test_spacing(np.longdouble)
4636
+
4637
+ def test_spacing_gfortran():
4638
+ # Reference from this fortran file, built with gfortran 4.3.3 on linux
4639
+ # 32bits:
4640
+ # PROGRAM test_spacing
4641
+ # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37)
4642
+ # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200)
4643
+ #
4644
+ # WRITE(*,*) spacing(0.00001_DBL)
4645
+ # WRITE(*,*) spacing(1.0_DBL)
4646
+ # WRITE(*,*) spacing(1000._DBL)
4647
+ # WRITE(*,*) spacing(10500._DBL)
4648
+ #
4649
+ # WRITE(*,*) spacing(0.00001_SGL)
4650
+ # WRITE(*,*) spacing(1.0_SGL)
4651
+ # WRITE(*,*) spacing(1000._SGL)
4652
+ # WRITE(*,*) spacing(10500._SGL)
4653
+ # END PROGRAM
4654
+ ref = {np.float64: [1.69406589450860068E-021,
4655
+ 2.22044604925031308E-016,
4656
+ 1.13686837721616030E-013,
4657
+ 1.81898940354585648E-012],
4658
+ np.float32: [9.09494702E-13,
4659
+ 1.19209290E-07,
4660
+ 6.10351563E-05,
4661
+ 9.76562500E-04]}
4662
+
4663
+ for dt, dec_ in zip([np.float32, np.float64], (10, 20)):
4664
+ x = np.array([1e-5, 1, 1000, 10500], dtype=dt)
4665
+ assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec_)
4666
+
4667
+ def test_nextafter_vs_spacing():
4668
+ # XXX: spacing does not handle long double yet
4669
+ for t in [np.float32, np.float64]:
4670
+ for _f in [1, 1e-5, 1000]:
4671
+ f = t(_f)
4672
+ f1 = t(_f + 1)
4673
+ assert_(np.nextafter(f, f1) - f == np.spacing(f))
4674
+
4675
+ def test_pos_nan():
4676
+ """Check np.nan is a positive nan."""
4677
+ assert_(np.signbit(np.nan) == 0)
4678
+
4679
+ def test_reduceat():
4680
+ """Test bug in reduceat when structured arrays are not copied."""
4681
+ db = np.dtype([('name', 'S11'), ('time', np.int64), ('value', np.float32)])
4682
+ a = np.empty([100], dtype=db)
4683
+ a['name'] = 'Simple'
4684
+ a['time'] = 10
4685
+ a['value'] = 100
4686
+ indx = [0, 7, 15, 25]
4687
+
4688
+ h2 = []
4689
+ val1 = indx[0]
4690
+ for val2 in indx[1:]:
4691
+ h2.append(np.add.reduce(a['value'][val1:val2]))
4692
+ val1 = val2
4693
+ h2.append(np.add.reduce(a['value'][val1:]))
4694
+ h2 = np.array(h2)
4695
+
4696
+ # test buffered -- this should work
4697
+ h1 = np.add.reduceat(a['value'], indx)
4698
+ assert_array_almost_equal(h1, h2)
4699
+
4700
+ # This is when the error occurs.
4701
+ # test no buffer
4702
+ np.setbufsize(32)
4703
+ h1 = np.add.reduceat(a['value'], indx)
4704
+ np.setbufsize(ncu.UFUNC_BUFSIZE_DEFAULT)
4705
+ assert_array_almost_equal(h1, h2)
4706
+
4707
+ def test_negative_value_raises():
4708
+ with pytest.raises(ValueError, match="buffer size must be non-negative"):
4709
+ np.setbufsize(-5)
4710
+
4711
+ old = np.getbufsize()
4712
+ try:
4713
+ prev = np.setbufsize(4096)
4714
+ assert prev == old
4715
+ assert np.getbufsize() == 4096
4716
+ finally:
4717
+ np.setbufsize(old)
4718
+
4719
+ def test_reduceat_empty():
4720
+ """Reduceat should work with empty arrays"""
4721
+ indices = np.array([], 'i4')
4722
+ x = np.array([], 'f8')
4723
+ result = np.add.reduceat(x, indices)
4724
+ assert_equal(result.dtype, x.dtype)
4725
+ assert_equal(result.shape, (0,))
4726
+ # Another case with a slightly different zero-sized shape
4727
+ x = np.ones((5, 2))
4728
+ result = np.add.reduceat(x, [], axis=0)
4729
+ assert_equal(result.dtype, x.dtype)
4730
+ assert_equal(result.shape, (0, 2))
4731
+ result = np.add.reduceat(x, [], axis=1)
4732
+ assert_equal(result.dtype, x.dtype)
4733
+ assert_equal(result.shape, (5, 0))
4734
+
4735
+ def test_complex_nan_comparisons():
4736
+ nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
4737
+ fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
4738
+ complex(1, 1), complex(-1, -1), complex(0, 0)]
4739
+
4740
+ with np.errstate(invalid='ignore'):
4741
+ for x in nans + fins:
4742
+ x = np.array([x])
4743
+ for y in nans + fins:
4744
+ y = np.array([y])
4745
+
4746
+ if np.isfinite(x) and np.isfinite(y):
4747
+ continue
4748
+
4749
+ assert_equal(x < y, False, err_msg=f"{x!r} < {y!r}")
4750
+ assert_equal(x > y, False, err_msg=f"{x!r} > {y!r}")
4751
+ assert_equal(x <= y, False, err_msg=f"{x!r} <= {y!r}")
4752
+ assert_equal(x >= y, False, err_msg=f"{x!r} >= {y!r}")
4753
+ assert_equal(x == y, False, err_msg=f"{x!r} == {y!r}")
4754
+
4755
+
4756
+ def test_rint_big_int():
4757
+ # np.rint bug for large integer values on Windows 32-bit and MKL
4758
+ # https://github.com/numpy/numpy/issues/6685
4759
+ val = 4607998452777363968
4760
+ # This is exactly representable in floating point
4761
+ assert_equal(val, int(float(val)))
4762
+ # Rint should not change the value
4763
+ assert_equal(val, np.rint(val))
4764
+
4765
+
4766
+ @pytest.mark.parametrize('ftype', [np.float32, np.float64])
4767
+ def test_memoverlap_accumulate(ftype):
4768
+ # Reproduces bug https://github.com/numpy/numpy/issues/15597
4769
+ arr = np.array([0.61, 0.60, 0.77, 0.41, 0.19], dtype=ftype)
4770
+ out_max = np.array([0.61, 0.61, 0.77, 0.77, 0.77], dtype=ftype)
4771
+ out_min = np.array([0.61, 0.60, 0.60, 0.41, 0.19], dtype=ftype)
4772
+ assert_equal(np.maximum.accumulate(arr), out_max)
4773
+ assert_equal(np.minimum.accumulate(arr), out_min)
4774
+
4775
+ @pytest.mark.parametrize("ufunc, dtype", [
4776
+ (ufunc, t[0])
4777
+ for ufunc in UFUNCS_BINARY_ACC
4778
+ for t in ufunc.types
4779
+ if t[-1] == '?' and t[0] not in 'DFGMmO'
4780
+ ])
4781
+ def test_memoverlap_accumulate_cmp(ufunc, dtype):
4782
+ if ufunc.signature:
4783
+ pytest.skip('For generic signatures only')
4784
+ for size in (2, 8, 32, 64, 128, 256):
4785
+ arr = np.array([0, 1, 1] * size, dtype=dtype)
4786
+ acc = ufunc.accumulate(arr, dtype='?')
4787
+ acc_u8 = acc.view(np.uint8)
4788
+ exp = np.array(list(itertools.accumulate(arr, ufunc)), dtype=np.uint8)
4789
+ assert_equal(exp, acc_u8)
4790
+
4791
+ @pytest.mark.parametrize("ufunc, dtype", [
4792
+ (ufunc, t[0])
4793
+ for ufunc in UFUNCS_BINARY_ACC
4794
+ for t in ufunc.types
4795
+ if t[0] == t[1] and t[0] == t[-1] and t[0] not in 'DFGMmO?'
4796
+ ])
4797
+ def test_memoverlap_accumulate_symmetric(ufunc, dtype):
4798
+ if ufunc.signature:
4799
+ pytest.skip('For generic signatures only')
4800
+ with np.errstate(all='ignore'):
4801
+ for size in (2, 8, 32, 64, 128, 256):
4802
+ arr = np.array([0, 1, 2] * size).astype(dtype)
4803
+ acc = ufunc.accumulate(arr, dtype=dtype)
4804
+ exp = np.array(list(itertools.accumulate(arr, ufunc)), dtype=dtype)
4805
+ assert_equal(exp, acc)
4806
+
4807
+ def test_signaling_nan_exceptions():
4808
+ with assert_no_warnings():
4809
+ a = np.ndarray(shape=(), dtype='float32', buffer=b'\x00\xe0\xbf\xff')
4810
+ np.isnan(a)
4811
+
4812
+ @pytest.mark.parametrize("arr", [
4813
+ np.arange(2),
4814
+ np.matrix([0, 1]),
4815
+ np.matrix([[0, 1], [2, 5]]),
4816
+ ])
4817
+ def test_outer_subclass_preserve(arr):
4818
+ # for gh-8661
4819
+ class foo(np.ndarray):
4820
+ pass
4821
+ actual = np.multiply.outer(arr.view(foo), arr.view(foo))
4822
+ assert actual.__class__.__name__ == 'foo'
4823
+
4824
+ def test_outer_bad_subclass():
4825
+ class BadArr1(np.ndarray):
4826
+ def __array_finalize__(self, obj):
4827
+ # The outer call reshapes to 3 dims, try to do a bad reshape.
4828
+ if self.ndim == 3:
4829
+ self.shape = self.shape + (1,)
4830
+
4831
+ class BadArr2(np.ndarray):
4832
+ def __array_finalize__(self, obj):
4833
+ if isinstance(obj, BadArr2):
4834
+ # outer inserts 1-sized dims. In that case disturb them.
4835
+ if self.shape[-1] == 1:
4836
+ self.shape = self.shape[::-1]
4837
+
4838
+ for cls in [BadArr1, BadArr2]:
4839
+ arr = np.ones((2, 3)).view(cls)
4840
+ with assert_raises(TypeError) as a:
4841
+ # The first array gets reshaped (not the second one)
4842
+ np.add.outer(arr, [1, 2])
4843
+
4844
+ # This actually works, since we only see the reshaping error:
4845
+ arr = np.ones((2, 3)).view(cls)
4846
+ assert type(np.add.outer([1, 2], arr)) is cls
4847
+
4848
+ def test_outer_exceeds_maxdims():
4849
+ deep = np.ones((1,) * 33)
4850
+ with assert_raises(ValueError):
4851
+ np.add.outer(deep, deep)
4852
+
4853
+ def test_bad_legacy_ufunc_silent_errors():
4854
+ # legacy ufuncs can't report errors and NumPy can't check if the GIL
4855
+ # is released. So NumPy has to check after the GIL is released just to
4856
+ # cover all bases. `np.power` uses/used to use this.
4857
+ arr = np.arange(3).astype(np.float64)
4858
+
4859
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4860
+ ncu_tests.always_error(arr, arr)
4861
+
4862
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4863
+ # not contiguous means the fast-path cannot be taken
4864
+ non_contig = arr.repeat(20).reshape(-1, 6)[:, ::2]
4865
+ ncu_tests.always_error(non_contig, arr)
4866
+
4867
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4868
+ ncu_tests.always_error.outer(arr, arr)
4869
+
4870
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4871
+ ncu_tests.always_error.reduce(arr)
4872
+
4873
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4874
+ ncu_tests.always_error.reduceat(arr, [0, 1])
4875
+
4876
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4877
+ ncu_tests.always_error.accumulate(arr)
4878
+
4879
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4880
+ ncu_tests.always_error.at(arr, [0, 1, 2], arr)
4881
+
4882
+
4883
+ @pytest.mark.parametrize('x1', [np.arange(3.0), [0.0, 1.0, 2.0]])
4884
+ def test_bad_legacy_gufunc_silent_errors(x1):
4885
+ # Verify that an exception raised in a gufunc loop propagates correctly.
4886
+ # The signature of always_error_gufunc is '(i),()->()'.
4887
+ with pytest.raises(RuntimeError, match=r"How unexpected :\)!"):
4888
+ ncu_tests.always_error_gufunc(x1, 0.0)
4889
+
4890
+
4891
+ class TestAddDocstring:
4892
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
4893
+ @pytest.mark.skipif(IS_PYPY, reason="PyPy does not modify tp_doc")
4894
+ def test_add_same_docstring(self):
4895
+ # test for attributes (which are C-level defined)
4896
+ ncu.add_docstring(np.ndarray.flat, np.ndarray.flat.__doc__)
4897
+
4898
+ # And typical functions:
4899
+ def func():
4900
+ """docstring"""
4901
+ return
4902
+
4903
+ ncu.add_docstring(func, func.__doc__)
4904
+
4905
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
4906
+ def test_different_docstring_fails(self):
4907
+ # test for attributes (which are C-level defined)
4908
+ with assert_raises(RuntimeError):
4909
+ ncu.add_docstring(np.ndarray.flat, "different docstring")
4910
+
4911
+ # And typical functions:
4912
+ def func():
4913
+ """docstring"""
4914
+ return
4915
+
4916
+ with assert_raises(RuntimeError):
4917
+ ncu.add_docstring(func, "different docstring")
4918
+
4919
+
4920
+ class TestAdd_newdoc_ufunc:
4921
+ @pytest.mark.filterwarnings("ignore:_add_newdoc_ufunc:DeprecationWarning")
4922
+ def test_ufunc_arg(self):
4923
+ assert_raises(TypeError, ncu._add_newdoc_ufunc, 2, "blah")
4924
+ assert_raises(ValueError, ncu._add_newdoc_ufunc, np.add, "blah")
4925
+
4926
+ @pytest.mark.filterwarnings("ignore:_add_newdoc_ufunc:DeprecationWarning")
4927
+ def test_string_arg(self):
4928
+ assert_raises(TypeError, ncu._add_newdoc_ufunc, np.add, 3)