numpy 2.4.1__pp311-pypy311_pp73-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.
Files changed (1039) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +108 -0
  3. numpy/__init__.cython-30.pxd +1242 -0
  4. numpy/__init__.pxd +1155 -0
  5. numpy/__init__.py +942 -0
  6. numpy/__init__.pyi +6202 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +206 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +201 -0
  12. numpy/_core/__init__.pyi +666 -0
  13. numpy/_core/_add_newdocs.py +7151 -0
  14. numpy/_core/_add_newdocs.pyi +2 -0
  15. numpy/_core/_add_newdocs_scalars.py +381 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +130 -0
  18. numpy/_core/_asarray.pyi +43 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +56 -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 +54 -0
  25. numpy/_core/_internal.py +968 -0
  26. numpy/_core/_internal.pyi +61 -0
  27. numpy/_core/_methods.py +252 -0
  28. numpy/_core/_methods.pyi +22 -0
  29. numpy/_core/_multiarray_tests.pypy311-pp73-darwin.so +0 -0
  30. numpy/_core/_multiarray_umath.pypy311-pp73-darwin.so +0 -0
  31. numpy/_core/_operand_flag_tests.pypy311-pp73-darwin.so +0 -0
  32. numpy/_core/_rational_tests.pypy311-pp73-darwin.so +0 -0
  33. numpy/_core/_simd.pyi +35 -0
  34. numpy/_core/_simd.pypy311-pp73-darwin.so +0 -0
  35. numpy/_core/_string_helpers.py +100 -0
  36. numpy/_core/_string_helpers.pyi +12 -0
  37. numpy/_core/_struct_ufunc_tests.pypy311-pp73-darwin.so +0 -0
  38. numpy/_core/_type_aliases.py +131 -0
  39. numpy/_core/_type_aliases.pyi +86 -0
  40. numpy/_core/_ufunc_config.py +515 -0
  41. numpy/_core/_ufunc_config.pyi +69 -0
  42. numpy/_core/_umath_tests.pyi +47 -0
  43. numpy/_core/_umath_tests.pypy311-pp73-darwin.so +0 -0
  44. numpy/_core/arrayprint.py +1779 -0
  45. numpy/_core/arrayprint.pyi +158 -0
  46. numpy/_core/cversions.py +13 -0
  47. numpy/_core/defchararray.py +1414 -0
  48. numpy/_core/defchararray.pyi +1150 -0
  49. numpy/_core/einsumfunc.py +1650 -0
  50. numpy/_core/einsumfunc.pyi +184 -0
  51. numpy/_core/fromnumeric.py +4233 -0
  52. numpy/_core/fromnumeric.pyi +1735 -0
  53. numpy/_core/function_base.py +547 -0
  54. numpy/_core/function_base.pyi +276 -0
  55. numpy/_core/getlimits.py +462 -0
  56. numpy/_core/getlimits.pyi +124 -0
  57. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  58. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  59. numpy/_core/include/numpy/__ufunc_api.c +55 -0
  60. numpy/_core/include/numpy/__ufunc_api.h +349 -0
  61. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  62. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  63. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  64. numpy/_core/include/numpy/arrayobject.h +7 -0
  65. numpy/_core/include/numpy/arrayscalars.h +198 -0
  66. numpy/_core/include/numpy/dtype_api.h +547 -0
  67. numpy/_core/include/numpy/halffloat.h +70 -0
  68. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  69. numpy/_core/include/numpy/ndarraytypes.h +1982 -0
  70. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  71. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  72. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  73. numpy/_core/include/numpy/npy_common.h +989 -0
  74. numpy/_core/include/numpy/npy_cpu.h +126 -0
  75. numpy/_core/include/numpy/npy_endian.h +79 -0
  76. numpy/_core/include/numpy/npy_math.h +602 -0
  77. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  78. numpy/_core/include/numpy/npy_os.h +42 -0
  79. numpy/_core/include/numpy/numpyconfig.h +185 -0
  80. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  81. numpy/_core/include/numpy/random/bitgen.h +20 -0
  82. numpy/_core/include/numpy/random/distributions.h +209 -0
  83. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  84. numpy/_core/include/numpy/ufuncobject.h +343 -0
  85. numpy/_core/include/numpy/utils.h +37 -0
  86. numpy/_core/lib/libnpymath.a +0 -0
  87. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  88. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  89. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  90. numpy/_core/memmap.py +363 -0
  91. numpy/_core/memmap.pyi +3 -0
  92. numpy/_core/multiarray.py +1740 -0
  93. numpy/_core/multiarray.pyi +1316 -0
  94. numpy/_core/numeric.py +2758 -0
  95. numpy/_core/numeric.pyi +1276 -0
  96. numpy/_core/numerictypes.py +633 -0
  97. numpy/_core/numerictypes.pyi +196 -0
  98. numpy/_core/overrides.py +188 -0
  99. numpy/_core/overrides.pyi +47 -0
  100. numpy/_core/printoptions.py +32 -0
  101. numpy/_core/printoptions.pyi +28 -0
  102. numpy/_core/records.py +1088 -0
  103. numpy/_core/records.pyi +340 -0
  104. numpy/_core/shape_base.py +996 -0
  105. numpy/_core/shape_base.pyi +182 -0
  106. numpy/_core/strings.py +1813 -0
  107. numpy/_core/strings.pyi +536 -0
  108. numpy/_core/tests/_locales.py +72 -0
  109. numpy/_core/tests/_natype.py +144 -0
  110. numpy/_core/tests/data/astype_copy.pkl +0 -0
  111. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  112. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  113. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  114. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  115. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  122. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  123. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  124. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  125. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  127. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  128. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  129. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  130. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  131. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  132. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  134. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  135. numpy/_core/tests/examples/cython/meson.build +43 -0
  136. numpy/_core/tests/examples/cython/setup.py +39 -0
  137. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  138. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  139. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  140. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  141. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  142. numpy/_core/tests/test__exceptions.py +90 -0
  143. numpy/_core/tests/test_abc.py +54 -0
  144. numpy/_core/tests/test_api.py +655 -0
  145. numpy/_core/tests/test_argparse.py +90 -0
  146. numpy/_core/tests/test_array_api_info.py +113 -0
  147. numpy/_core/tests/test_array_coercion.py +928 -0
  148. numpy/_core/tests/test_array_interface.py +222 -0
  149. numpy/_core/tests/test_arraymethod.py +84 -0
  150. numpy/_core/tests/test_arrayobject.py +75 -0
  151. numpy/_core/tests/test_arrayprint.py +1324 -0
  152. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  153. numpy/_core/tests/test_casting_unittests.py +955 -0
  154. numpy/_core/tests/test_conversion_utils.py +209 -0
  155. numpy/_core/tests/test_cpu_dispatcher.py +48 -0
  156. numpy/_core/tests/test_cpu_features.py +450 -0
  157. numpy/_core/tests/test_custom_dtypes.py +393 -0
  158. numpy/_core/tests/test_cython.py +352 -0
  159. numpy/_core/tests/test_datetime.py +2792 -0
  160. numpy/_core/tests/test_defchararray.py +858 -0
  161. numpy/_core/tests/test_deprecations.py +460 -0
  162. numpy/_core/tests/test_dlpack.py +190 -0
  163. numpy/_core/tests/test_dtype.py +2110 -0
  164. numpy/_core/tests/test_einsum.py +1351 -0
  165. numpy/_core/tests/test_errstate.py +131 -0
  166. numpy/_core/tests/test_extint128.py +217 -0
  167. numpy/_core/tests/test_finfo.py +86 -0
  168. numpy/_core/tests/test_function_base.py +504 -0
  169. numpy/_core/tests/test_getlimits.py +171 -0
  170. numpy/_core/tests/test_half.py +593 -0
  171. numpy/_core/tests/test_hashtable.py +36 -0
  172. numpy/_core/tests/test_indexerrors.py +122 -0
  173. numpy/_core/tests/test_indexing.py +1692 -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 +370 -0
  177. numpy/_core/tests/test_mem_overlap.py +933 -0
  178. numpy/_core/tests/test_mem_policy.py +453 -0
  179. numpy/_core/tests/test_memmap.py +248 -0
  180. numpy/_core/tests/test_multiarray.py +11008 -0
  181. numpy/_core/tests/test_multiprocessing.py +55 -0
  182. numpy/_core/tests/test_multithreading.py +377 -0
  183. numpy/_core/tests/test_nditer.py +3533 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4295 -0
  186. numpy/_core/tests/test_numerictypes.py +650 -0
  187. numpy/_core/tests/test_overrides.py +800 -0
  188. numpy/_core/tests/test_print.py +202 -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 +2677 -0
  192. numpy/_core/tests/test_scalar_ctors.py +203 -0
  193. numpy/_core/tests/test_scalar_methods.py +328 -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 +1168 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +904 -0
  199. numpy/_core/tests/test_simd.py +1345 -0
  200. numpy/_core/tests/test_simd_module.py +105 -0
  201. numpy/_core/tests/test_stringdtype.py +1855 -0
  202. numpy/_core/tests/test_strings.py +1523 -0
  203. numpy/_core/tests/test_ufunc.py +3405 -0
  204. numpy/_core/tests/test_umath.py +4962 -0
  205. numpy/_core/tests/test_umath_accuracy.py +132 -0
  206. numpy/_core/tests/test_umath_complex.py +631 -0
  207. numpy/_core/tests/test_unicode.py +369 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +232 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +78 -0
  213. numpy/_expired_attrs_2_0.pyi +61 -0
  214. numpy/_globals.py +121 -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 +6 -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 +173 -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 +39 -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 +975 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +28 -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 +70 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +118 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +248 -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 +15 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +236 -0
  277. numpy/distutils/__init__.py +64 -0
  278. numpy/distutils/__init__.pyi +4 -0
  279. numpy/distutils/__pycache__/conv_template.pypy311.pyc +0 -0
  280. numpy/distutils/_shell_utils.py +87 -0
  281. numpy/distutils/armccompiler.py +26 -0
  282. numpy/distutils/ccompiler.py +826 -0
  283. numpy/distutils/ccompiler_opt.py +2668 -0
  284. numpy/distutils/checks/cpu_asimd.c +27 -0
  285. numpy/distutils/checks/cpu_asimddp.c +16 -0
  286. numpy/distutils/checks/cpu_asimdfhm.c +19 -0
  287. numpy/distutils/checks/cpu_asimdhp.c +15 -0
  288. numpy/distutils/checks/cpu_avx.c +20 -0
  289. numpy/distutils/checks/cpu_avx2.c +20 -0
  290. numpy/distutils/checks/cpu_avx512_clx.c +22 -0
  291. numpy/distutils/checks/cpu_avx512_cnl.c +24 -0
  292. numpy/distutils/checks/cpu_avx512_icl.c +26 -0
  293. numpy/distutils/checks/cpu_avx512_knl.c +25 -0
  294. numpy/distutils/checks/cpu_avx512_knm.c +30 -0
  295. numpy/distutils/checks/cpu_avx512_skx.c +26 -0
  296. numpy/distutils/checks/cpu_avx512_spr.c +26 -0
  297. numpy/distutils/checks/cpu_avx512cd.c +20 -0
  298. numpy/distutils/checks/cpu_avx512f.c +20 -0
  299. numpy/distutils/checks/cpu_f16c.c +22 -0
  300. numpy/distutils/checks/cpu_fma3.c +22 -0
  301. numpy/distutils/checks/cpu_fma4.c +13 -0
  302. numpy/distutils/checks/cpu_lsx.c +11 -0
  303. numpy/distutils/checks/cpu_neon.c +19 -0
  304. numpy/distutils/checks/cpu_neon_fp16.c +11 -0
  305. numpy/distutils/checks/cpu_neon_vfpv4.c +21 -0
  306. numpy/distutils/checks/cpu_popcnt.c +32 -0
  307. numpy/distutils/checks/cpu_rvv.c +13 -0
  308. numpy/distutils/checks/cpu_sse.c +20 -0
  309. numpy/distutils/checks/cpu_sse2.c +20 -0
  310. numpy/distutils/checks/cpu_sse3.c +20 -0
  311. numpy/distutils/checks/cpu_sse41.c +20 -0
  312. numpy/distutils/checks/cpu_sse42.c +20 -0
  313. numpy/distutils/checks/cpu_ssse3.c +20 -0
  314. numpy/distutils/checks/cpu_sve.c +14 -0
  315. numpy/distutils/checks/cpu_vsx.c +21 -0
  316. numpy/distutils/checks/cpu_vsx2.c +13 -0
  317. numpy/distutils/checks/cpu_vsx3.c +13 -0
  318. numpy/distutils/checks/cpu_vsx4.c +14 -0
  319. numpy/distutils/checks/cpu_vx.c +16 -0
  320. numpy/distutils/checks/cpu_vxe.c +25 -0
  321. numpy/distutils/checks/cpu_vxe2.c +21 -0
  322. numpy/distutils/checks/cpu_xop.c +12 -0
  323. numpy/distutils/checks/extra_avx512bw_mask.c +18 -0
  324. numpy/distutils/checks/extra_avx512dq_mask.c +16 -0
  325. numpy/distutils/checks/extra_avx512f_reduce.c +41 -0
  326. numpy/distutils/checks/extra_vsx3_half_double.c +12 -0
  327. numpy/distutils/checks/extra_vsx4_mma.c +21 -0
  328. numpy/distutils/checks/extra_vsx_asm.c +36 -0
  329. numpy/distutils/checks/test_flags.c +1 -0
  330. numpy/distutils/command/__init__.py +41 -0
  331. numpy/distutils/command/autodist.py +148 -0
  332. numpy/distutils/command/bdist_rpm.py +22 -0
  333. numpy/distutils/command/build.py +62 -0
  334. numpy/distutils/command/build_clib.py +469 -0
  335. numpy/distutils/command/build_ext.py +752 -0
  336. numpy/distutils/command/build_py.py +31 -0
  337. numpy/distutils/command/build_scripts.py +49 -0
  338. numpy/distutils/command/build_src.py +773 -0
  339. numpy/distutils/command/config.py +516 -0
  340. numpy/distutils/command/config_compiler.py +126 -0
  341. numpy/distutils/command/develop.py +15 -0
  342. numpy/distutils/command/egg_info.py +25 -0
  343. numpy/distutils/command/install.py +79 -0
  344. numpy/distutils/command/install_clib.py +40 -0
  345. numpy/distutils/command/install_data.py +24 -0
  346. numpy/distutils/command/install_headers.py +25 -0
  347. numpy/distutils/command/sdist.py +27 -0
  348. numpy/distutils/conv_template.py +329 -0
  349. numpy/distutils/core.py +215 -0
  350. numpy/distutils/cpuinfo.py +683 -0
  351. numpy/distutils/exec_command.py +315 -0
  352. numpy/distutils/extension.py +101 -0
  353. numpy/distutils/fcompiler/__init__.py +1035 -0
  354. numpy/distutils/fcompiler/absoft.py +158 -0
  355. numpy/distutils/fcompiler/arm.py +71 -0
  356. numpy/distutils/fcompiler/compaq.py +120 -0
  357. numpy/distutils/fcompiler/environment.py +88 -0
  358. numpy/distutils/fcompiler/fujitsu.py +46 -0
  359. numpy/distutils/fcompiler/g95.py +42 -0
  360. numpy/distutils/fcompiler/gnu.py +555 -0
  361. numpy/distutils/fcompiler/hpux.py +41 -0
  362. numpy/distutils/fcompiler/ibm.py +97 -0
  363. numpy/distutils/fcompiler/intel.py +211 -0
  364. numpy/distutils/fcompiler/lahey.py +45 -0
  365. numpy/distutils/fcompiler/mips.py +54 -0
  366. numpy/distutils/fcompiler/nag.py +87 -0
  367. numpy/distutils/fcompiler/none.py +28 -0
  368. numpy/distutils/fcompiler/nv.py +53 -0
  369. numpy/distutils/fcompiler/pathf95.py +33 -0
  370. numpy/distutils/fcompiler/pg.py +128 -0
  371. numpy/distutils/fcompiler/sun.py +51 -0
  372. numpy/distutils/fcompiler/vast.py +52 -0
  373. numpy/distutils/from_template.py +261 -0
  374. numpy/distutils/fujitsuccompiler.py +28 -0
  375. numpy/distutils/intelccompiler.py +106 -0
  376. numpy/distutils/lib2def.py +116 -0
  377. numpy/distutils/line_endings.py +77 -0
  378. numpy/distutils/log.py +111 -0
  379. numpy/distutils/mingw/gfortran_vs2003_hack.c +6 -0
  380. numpy/distutils/mingw32ccompiler.py +620 -0
  381. numpy/distutils/misc_util.py +2484 -0
  382. numpy/distutils/msvc9compiler.py +63 -0
  383. numpy/distutils/msvccompiler.py +76 -0
  384. numpy/distutils/npy_pkg_config.py +441 -0
  385. numpy/distutils/numpy_distribution.py +17 -0
  386. numpy/distutils/pathccompiler.py +21 -0
  387. numpy/distutils/system_info.py +3267 -0
  388. numpy/distutils/tests/__init__.py +0 -0
  389. numpy/distutils/tests/test_build_ext.py +74 -0
  390. numpy/distutils/tests/test_ccompiler_opt.py +808 -0
  391. numpy/distutils/tests/test_ccompiler_opt_conf.py +176 -0
  392. numpy/distutils/tests/test_exec_command.py +217 -0
  393. numpy/distutils/tests/test_fcompiler.py +43 -0
  394. numpy/distutils/tests/test_fcompiler_gnu.py +55 -0
  395. numpy/distutils/tests/test_fcompiler_intel.py +30 -0
  396. numpy/distutils/tests/test_fcompiler_nagfor.py +22 -0
  397. numpy/distutils/tests/test_from_template.py +44 -0
  398. numpy/distutils/tests/test_log.py +34 -0
  399. numpy/distutils/tests/test_mingw32ccompiler.py +47 -0
  400. numpy/distutils/tests/test_misc_util.py +88 -0
  401. numpy/distutils/tests/test_npy_pkg_config.py +84 -0
  402. numpy/distutils/tests/test_shell_utils.py +79 -0
  403. numpy/distutils/tests/test_system_info.py +334 -0
  404. numpy/distutils/tests/utilities.py +90 -0
  405. numpy/distutils/unixccompiler.py +141 -0
  406. numpy/doc/ufuncs.py +138 -0
  407. numpy/dtypes.py +41 -0
  408. numpy/dtypes.pyi +630 -0
  409. numpy/exceptions.py +246 -0
  410. numpy/exceptions.pyi +27 -0
  411. numpy/f2py/__init__.py +86 -0
  412. numpy/f2py/__init__.pyi +5 -0
  413. numpy/f2py/__main__.py +5 -0
  414. numpy/f2py/__version__.py +1 -0
  415. numpy/f2py/__version__.pyi +1 -0
  416. numpy/f2py/_backends/__init__.py +9 -0
  417. numpy/f2py/_backends/__init__.pyi +5 -0
  418. numpy/f2py/_backends/_backend.py +44 -0
  419. numpy/f2py/_backends/_backend.pyi +46 -0
  420. numpy/f2py/_backends/_distutils.py +76 -0
  421. numpy/f2py/_backends/_distutils.pyi +13 -0
  422. numpy/f2py/_backends/_meson.py +244 -0
  423. numpy/f2py/_backends/_meson.pyi +62 -0
  424. numpy/f2py/_backends/meson.build.template +58 -0
  425. numpy/f2py/_isocbind.py +62 -0
  426. numpy/f2py/_isocbind.pyi +13 -0
  427. numpy/f2py/_src_pyf.py +247 -0
  428. numpy/f2py/_src_pyf.pyi +28 -0
  429. numpy/f2py/auxfuncs.py +1004 -0
  430. numpy/f2py/auxfuncs.pyi +262 -0
  431. numpy/f2py/capi_maps.py +811 -0
  432. numpy/f2py/capi_maps.pyi +33 -0
  433. numpy/f2py/cb_rules.py +665 -0
  434. numpy/f2py/cb_rules.pyi +17 -0
  435. numpy/f2py/cfuncs.py +1563 -0
  436. numpy/f2py/cfuncs.pyi +31 -0
  437. numpy/f2py/common_rules.py +143 -0
  438. numpy/f2py/common_rules.pyi +9 -0
  439. numpy/f2py/crackfortran.py +3725 -0
  440. numpy/f2py/crackfortran.pyi +266 -0
  441. numpy/f2py/diagnose.py +149 -0
  442. numpy/f2py/diagnose.pyi +1 -0
  443. numpy/f2py/f2py2e.py +788 -0
  444. numpy/f2py/f2py2e.pyi +74 -0
  445. numpy/f2py/f90mod_rules.py +269 -0
  446. numpy/f2py/f90mod_rules.pyi +16 -0
  447. numpy/f2py/func2subr.py +329 -0
  448. numpy/f2py/func2subr.pyi +7 -0
  449. numpy/f2py/rules.py +1629 -0
  450. numpy/f2py/rules.pyi +41 -0
  451. numpy/f2py/setup.cfg +3 -0
  452. numpy/f2py/src/fortranobject.c +1436 -0
  453. numpy/f2py/src/fortranobject.h +173 -0
  454. numpy/f2py/symbolic.py +1518 -0
  455. numpy/f2py/symbolic.pyi +219 -0
  456. numpy/f2py/tests/__init__.py +16 -0
  457. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  458. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  459. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  460. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  461. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  462. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  463. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  464. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  465. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  466. numpy/f2py/tests/src/callback/foo.f +62 -0
  467. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  468. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  469. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  470. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  471. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  472. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  473. numpy/f2py/tests/src/cli/hi77.f +3 -0
  474. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  475. numpy/f2py/tests/src/common/block.f +11 -0
  476. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  477. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  478. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  479. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  480. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  481. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  482. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  483. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  484. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  485. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  486. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  487. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  488. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  489. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  490. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  491. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  492. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  493. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  494. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  495. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  496. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  497. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  498. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  499. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  500. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  501. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  502. numpy/f2py/tests/src/mixed/foo.f +5 -0
  503. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  504. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  505. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  506. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  507. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  508. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  509. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  510. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  511. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  512. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  513. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  514. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  515. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  516. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  517. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  518. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  519. numpy/f2py/tests/src/regression/AB.inc +1 -0
  520. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  521. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  522. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  523. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  524. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  525. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  526. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  527. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  528. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  529. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  530. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  531. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  532. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  533. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  534. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  535. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  536. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  537. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  538. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  539. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  540. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  541. numpy/f2py/tests/src/routines/subrout.f +4 -0
  542. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  543. numpy/f2py/tests/src/size/foo.f90 +44 -0
  544. numpy/f2py/tests/src/string/char.f90 +29 -0
  545. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  546. numpy/f2py/tests/src/string/gh24008.f +8 -0
  547. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  548. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  549. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  550. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  551. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  552. numpy/f2py/tests/src/string/string.f +12 -0
  553. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  554. numpy/f2py/tests/test_abstract_interface.py +26 -0
  555. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  556. numpy/f2py/tests/test_assumed_shape.py +50 -0
  557. numpy/f2py/tests/test_block_docstring.py +20 -0
  558. numpy/f2py/tests/test_callback.py +263 -0
  559. numpy/f2py/tests/test_character.py +641 -0
  560. numpy/f2py/tests/test_common.py +23 -0
  561. numpy/f2py/tests/test_crackfortran.py +421 -0
  562. numpy/f2py/tests/test_data.py +71 -0
  563. numpy/f2py/tests/test_docs.py +66 -0
  564. numpy/f2py/tests/test_f2cmap.py +17 -0
  565. numpy/f2py/tests/test_f2py2e.py +983 -0
  566. numpy/f2py/tests/test_isoc.py +56 -0
  567. numpy/f2py/tests/test_kind.py +52 -0
  568. numpy/f2py/tests/test_mixed.py +35 -0
  569. numpy/f2py/tests/test_modules.py +83 -0
  570. numpy/f2py/tests/test_parameter.py +129 -0
  571. numpy/f2py/tests/test_pyf_src.py +43 -0
  572. numpy/f2py/tests/test_quoted_character.py +18 -0
  573. numpy/f2py/tests/test_regression.py +187 -0
  574. numpy/f2py/tests/test_return_character.py +48 -0
  575. numpy/f2py/tests/test_return_complex.py +67 -0
  576. numpy/f2py/tests/test_return_integer.py +55 -0
  577. numpy/f2py/tests/test_return_logical.py +65 -0
  578. numpy/f2py/tests/test_return_real.py +109 -0
  579. numpy/f2py/tests/test_routines.py +29 -0
  580. numpy/f2py/tests/test_semicolon_split.py +75 -0
  581. numpy/f2py/tests/test_size.py +45 -0
  582. numpy/f2py/tests/test_string.py +100 -0
  583. numpy/f2py/tests/test_symbolic.py +500 -0
  584. numpy/f2py/tests/test_value_attrspec.py +15 -0
  585. numpy/f2py/tests/util.py +442 -0
  586. numpy/f2py/use_rules.py +99 -0
  587. numpy/f2py/use_rules.pyi +9 -0
  588. numpy/fft/__init__.py +213 -0
  589. numpy/fft/__init__.pyi +38 -0
  590. numpy/fft/_helper.py +235 -0
  591. numpy/fft/_helper.pyi +44 -0
  592. numpy/fft/_pocketfft.py +1693 -0
  593. numpy/fft/_pocketfft.pyi +137 -0
  594. numpy/fft/_pocketfft_umath.pypy311-pp73-darwin.so +0 -0
  595. numpy/fft/tests/__init__.py +0 -0
  596. numpy/fft/tests/test_helper.py +167 -0
  597. numpy/fft/tests/test_pocketfft.py +589 -0
  598. numpy/lib/__init__.py +97 -0
  599. numpy/lib/__init__.pyi +52 -0
  600. numpy/lib/_array_utils_impl.py +62 -0
  601. numpy/lib/_array_utils_impl.pyi +10 -0
  602. numpy/lib/_arraypad_impl.py +926 -0
  603. numpy/lib/_arraypad_impl.pyi +88 -0
  604. numpy/lib/_arraysetops_impl.py +1158 -0
  605. numpy/lib/_arraysetops_impl.pyi +462 -0
  606. numpy/lib/_arrayterator_impl.py +224 -0
  607. numpy/lib/_arrayterator_impl.pyi +45 -0
  608. numpy/lib/_datasource.py +700 -0
  609. numpy/lib/_datasource.pyi +30 -0
  610. numpy/lib/_format_impl.py +1036 -0
  611. numpy/lib/_format_impl.pyi +56 -0
  612. numpy/lib/_function_base_impl.py +5760 -0
  613. numpy/lib/_function_base_impl.pyi +2324 -0
  614. numpy/lib/_histograms_impl.py +1085 -0
  615. numpy/lib/_histograms_impl.pyi +40 -0
  616. numpy/lib/_index_tricks_impl.py +1048 -0
  617. numpy/lib/_index_tricks_impl.pyi +267 -0
  618. numpy/lib/_iotools.py +900 -0
  619. numpy/lib/_iotools.pyi +116 -0
  620. numpy/lib/_nanfunctions_impl.py +2006 -0
  621. numpy/lib/_nanfunctions_impl.pyi +48 -0
  622. numpy/lib/_npyio_impl.py +2583 -0
  623. numpy/lib/_npyio_impl.pyi +299 -0
  624. numpy/lib/_polynomial_impl.py +1465 -0
  625. numpy/lib/_polynomial_impl.pyi +338 -0
  626. numpy/lib/_scimath_impl.py +642 -0
  627. numpy/lib/_scimath_impl.pyi +93 -0
  628. numpy/lib/_shape_base_impl.py +1289 -0
  629. numpy/lib/_shape_base_impl.pyi +236 -0
  630. numpy/lib/_stride_tricks_impl.py +582 -0
  631. numpy/lib/_stride_tricks_impl.pyi +73 -0
  632. numpy/lib/_twodim_base_impl.py +1201 -0
  633. numpy/lib/_twodim_base_impl.pyi +408 -0
  634. numpy/lib/_type_check_impl.py +710 -0
  635. numpy/lib/_type_check_impl.pyi +348 -0
  636. numpy/lib/_ufunclike_impl.py +199 -0
  637. numpy/lib/_ufunclike_impl.pyi +60 -0
  638. numpy/lib/_user_array_impl.py +310 -0
  639. numpy/lib/_user_array_impl.pyi +226 -0
  640. numpy/lib/_utils_impl.py +784 -0
  641. numpy/lib/_utils_impl.pyi +22 -0
  642. numpy/lib/_version.py +153 -0
  643. numpy/lib/_version.pyi +17 -0
  644. numpy/lib/array_utils.py +7 -0
  645. numpy/lib/array_utils.pyi +6 -0
  646. numpy/lib/format.py +24 -0
  647. numpy/lib/format.pyi +24 -0
  648. numpy/lib/introspect.py +94 -0
  649. numpy/lib/introspect.pyi +3 -0
  650. numpy/lib/mixins.py +180 -0
  651. numpy/lib/mixins.pyi +78 -0
  652. numpy/lib/npyio.py +1 -0
  653. numpy/lib/npyio.pyi +5 -0
  654. numpy/lib/recfunctions.py +1681 -0
  655. numpy/lib/recfunctions.pyi +444 -0
  656. numpy/lib/scimath.py +13 -0
  657. numpy/lib/scimath.pyi +12 -0
  658. numpy/lib/stride_tricks.py +1 -0
  659. numpy/lib/stride_tricks.pyi +4 -0
  660. numpy/lib/tests/__init__.py +0 -0
  661. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  662. numpy/lib/tests/data/py2-objarr.npy +0 -0
  663. numpy/lib/tests/data/py2-objarr.npz +0 -0
  664. numpy/lib/tests/data/py3-objarr.npy +0 -0
  665. numpy/lib/tests/data/py3-objarr.npz +0 -0
  666. numpy/lib/tests/data/python3.npy +0 -0
  667. numpy/lib/tests/data/win64python2.npy +0 -0
  668. numpy/lib/tests/test__datasource.py +328 -0
  669. numpy/lib/tests/test__iotools.py +358 -0
  670. numpy/lib/tests/test__version.py +64 -0
  671. numpy/lib/tests/test_array_utils.py +32 -0
  672. numpy/lib/tests/test_arraypad.py +1427 -0
  673. numpy/lib/tests/test_arraysetops.py +1302 -0
  674. numpy/lib/tests/test_arrayterator.py +45 -0
  675. numpy/lib/tests/test_format.py +1054 -0
  676. numpy/lib/tests/test_function_base.py +4750 -0
  677. numpy/lib/tests/test_histograms.py +855 -0
  678. numpy/lib/tests/test_index_tricks.py +693 -0
  679. numpy/lib/tests/test_io.py +2857 -0
  680. numpy/lib/tests/test_loadtxt.py +1099 -0
  681. numpy/lib/tests/test_mixins.py +215 -0
  682. numpy/lib/tests/test_nanfunctions.py +1438 -0
  683. numpy/lib/tests/test_packbits.py +376 -0
  684. numpy/lib/tests/test_polynomial.py +325 -0
  685. numpy/lib/tests/test_recfunctions.py +1042 -0
  686. numpy/lib/tests/test_regression.py +231 -0
  687. numpy/lib/tests/test_shape_base.py +813 -0
  688. numpy/lib/tests/test_stride_tricks.py +655 -0
  689. numpy/lib/tests/test_twodim_base.py +559 -0
  690. numpy/lib/tests/test_type_check.py +473 -0
  691. numpy/lib/tests/test_ufunclike.py +97 -0
  692. numpy/lib/tests/test_utils.py +80 -0
  693. numpy/lib/user_array.py +1 -0
  694. numpy/lib/user_array.pyi +1 -0
  695. numpy/linalg/__init__.py +95 -0
  696. numpy/linalg/__init__.pyi +71 -0
  697. numpy/linalg/_linalg.py +3657 -0
  698. numpy/linalg/_linalg.pyi +548 -0
  699. numpy/linalg/_umath_linalg.pyi +60 -0
  700. numpy/linalg/_umath_linalg.pypy311-pp73-darwin.so +0 -0
  701. numpy/linalg/lapack_lite.pyi +143 -0
  702. numpy/linalg/lapack_lite.pypy311-pp73-darwin.so +0 -0
  703. numpy/linalg/tests/__init__.py +0 -0
  704. numpy/linalg/tests/test_deprecations.py +21 -0
  705. numpy/linalg/tests/test_linalg.py +2442 -0
  706. numpy/linalg/tests/test_regression.py +182 -0
  707. numpy/ma/API_CHANGES.txt +135 -0
  708. numpy/ma/LICENSE +24 -0
  709. numpy/ma/README.rst +236 -0
  710. numpy/ma/__init__.py +53 -0
  711. numpy/ma/__init__.pyi +458 -0
  712. numpy/ma/core.py +8929 -0
  713. numpy/ma/core.pyi +3720 -0
  714. numpy/ma/extras.py +2266 -0
  715. numpy/ma/extras.pyi +297 -0
  716. numpy/ma/mrecords.py +762 -0
  717. numpy/ma/mrecords.pyi +96 -0
  718. numpy/ma/tests/__init__.py +0 -0
  719. numpy/ma/tests/test_arrayobject.py +40 -0
  720. numpy/ma/tests/test_core.py +6008 -0
  721. numpy/ma/tests/test_deprecations.py +65 -0
  722. numpy/ma/tests/test_extras.py +1945 -0
  723. numpy/ma/tests/test_mrecords.py +495 -0
  724. numpy/ma/tests/test_old_ma.py +939 -0
  725. numpy/ma/tests/test_regression.py +83 -0
  726. numpy/ma/tests/test_subclassing.py +469 -0
  727. numpy/ma/testutils.py +294 -0
  728. numpy/ma/testutils.pyi +69 -0
  729. numpy/matlib.py +380 -0
  730. numpy/matlib.pyi +580 -0
  731. numpy/matrixlib/__init__.py +12 -0
  732. numpy/matrixlib/__init__.pyi +3 -0
  733. numpy/matrixlib/defmatrix.py +1119 -0
  734. numpy/matrixlib/defmatrix.pyi +218 -0
  735. numpy/matrixlib/tests/__init__.py +0 -0
  736. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  737. numpy/matrixlib/tests/test_interaction.py +360 -0
  738. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  739. numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
  740. numpy/matrixlib/tests/test_multiarray.py +17 -0
  741. numpy/matrixlib/tests/test_numeric.py +18 -0
  742. numpy/matrixlib/tests/test_regression.py +31 -0
  743. numpy/polynomial/__init__.py +187 -0
  744. numpy/polynomial/__init__.pyi +31 -0
  745. numpy/polynomial/_polybase.py +1191 -0
  746. numpy/polynomial/_polybase.pyi +262 -0
  747. numpy/polynomial/_polytypes.pyi +501 -0
  748. numpy/polynomial/chebyshev.py +2001 -0
  749. numpy/polynomial/chebyshev.pyi +180 -0
  750. numpy/polynomial/hermite.py +1738 -0
  751. numpy/polynomial/hermite.pyi +106 -0
  752. numpy/polynomial/hermite_e.py +1640 -0
  753. numpy/polynomial/hermite_e.pyi +106 -0
  754. numpy/polynomial/laguerre.py +1673 -0
  755. numpy/polynomial/laguerre.pyi +100 -0
  756. numpy/polynomial/legendre.py +1603 -0
  757. numpy/polynomial/legendre.pyi +100 -0
  758. numpy/polynomial/polynomial.py +1625 -0
  759. numpy/polynomial/polynomial.pyi +109 -0
  760. numpy/polynomial/polyutils.py +759 -0
  761. numpy/polynomial/polyutils.pyi +307 -0
  762. numpy/polynomial/tests/__init__.py +0 -0
  763. numpy/polynomial/tests/test_chebyshev.py +618 -0
  764. numpy/polynomial/tests/test_classes.py +613 -0
  765. numpy/polynomial/tests/test_hermite.py +553 -0
  766. numpy/polynomial/tests/test_hermite_e.py +554 -0
  767. numpy/polynomial/tests/test_laguerre.py +535 -0
  768. numpy/polynomial/tests/test_legendre.py +566 -0
  769. numpy/polynomial/tests/test_polynomial.py +691 -0
  770. numpy/polynomial/tests/test_polyutils.py +123 -0
  771. numpy/polynomial/tests/test_printing.py +557 -0
  772. numpy/polynomial/tests/test_symbol.py +217 -0
  773. numpy/py.typed +0 -0
  774. numpy/random/LICENSE.md +71 -0
  775. numpy/random/__init__.pxd +14 -0
  776. numpy/random/__init__.py +213 -0
  777. numpy/random/__init__.pyi +124 -0
  778. numpy/random/_bounded_integers.pxd +29 -0
  779. numpy/random/_bounded_integers.pyi +1 -0
  780. numpy/random/_bounded_integers.pypy311-pp73-darwin.so +0 -0
  781. numpy/random/_common.pxd +110 -0
  782. numpy/random/_common.pyi +16 -0
  783. numpy/random/_common.pypy311-pp73-darwin.so +0 -0
  784. numpy/random/_examples/cffi/extending.py +44 -0
  785. numpy/random/_examples/cffi/parse.py +53 -0
  786. numpy/random/_examples/cython/extending.pyx +77 -0
  787. numpy/random/_examples/cython/extending_distributions.pyx +117 -0
  788. numpy/random/_examples/cython/meson.build +53 -0
  789. numpy/random/_examples/numba/extending.py +86 -0
  790. numpy/random/_examples/numba/extending_distributions.py +67 -0
  791. numpy/random/_generator.pyi +862 -0
  792. numpy/random/_generator.pypy311-pp73-darwin.so +0 -0
  793. numpy/random/_mt19937.pyi +27 -0
  794. numpy/random/_mt19937.pypy311-pp73-darwin.so +0 -0
  795. numpy/random/_pcg64.pyi +41 -0
  796. numpy/random/_pcg64.pypy311-pp73-darwin.so +0 -0
  797. numpy/random/_philox.pyi +36 -0
  798. numpy/random/_philox.pypy311-pp73-darwin.so +0 -0
  799. numpy/random/_pickle.py +88 -0
  800. numpy/random/_pickle.pyi +43 -0
  801. numpy/random/_sfc64.pyi +25 -0
  802. numpy/random/_sfc64.pypy311-pp73-darwin.so +0 -0
  803. numpy/random/bit_generator.pxd +40 -0
  804. numpy/random/bit_generator.pyi +123 -0
  805. numpy/random/bit_generator.pypy311-pp73-darwin.so +0 -0
  806. numpy/random/c_distributions.pxd +119 -0
  807. numpy/random/lib/libnpyrandom.a +0 -0
  808. numpy/random/mtrand.pyi +759 -0
  809. numpy/random/mtrand.pypy311-pp73-darwin.so +0 -0
  810. numpy/random/tests/__init__.py +0 -0
  811. numpy/random/tests/data/__init__.py +0 -0
  812. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  813. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  814. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  815. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  816. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  817. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  818. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  819. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  820. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  821. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  822. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  823. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  824. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  825. numpy/random/tests/test_direct.py +595 -0
  826. numpy/random/tests/test_extending.py +131 -0
  827. numpy/random/tests/test_generator_mt19937.py +2825 -0
  828. numpy/random/tests/test_generator_mt19937_regressions.py +221 -0
  829. numpy/random/tests/test_random.py +1724 -0
  830. numpy/random/tests/test_randomstate.py +2099 -0
  831. numpy/random/tests/test_randomstate_regression.py +213 -0
  832. numpy/random/tests/test_regression.py +175 -0
  833. numpy/random/tests/test_seed_sequence.py +79 -0
  834. numpy/random/tests/test_smoke.py +882 -0
  835. numpy/rec/__init__.py +2 -0
  836. numpy/rec/__init__.pyi +23 -0
  837. numpy/strings/__init__.py +2 -0
  838. numpy/strings/__init__.pyi +97 -0
  839. numpy/testing/__init__.py +22 -0
  840. numpy/testing/__init__.pyi +107 -0
  841. numpy/testing/_private/__init__.py +0 -0
  842. numpy/testing/_private/__init__.pyi +0 -0
  843. numpy/testing/_private/extbuild.py +250 -0
  844. numpy/testing/_private/extbuild.pyi +25 -0
  845. numpy/testing/_private/utils.py +2830 -0
  846. numpy/testing/_private/utils.pyi +505 -0
  847. numpy/testing/overrides.py +84 -0
  848. numpy/testing/overrides.pyi +10 -0
  849. numpy/testing/print_coercion_tables.py +207 -0
  850. numpy/testing/print_coercion_tables.pyi +26 -0
  851. numpy/testing/tests/__init__.py +0 -0
  852. numpy/testing/tests/test_utils.py +2123 -0
  853. numpy/tests/__init__.py +0 -0
  854. numpy/tests/test__all__.py +10 -0
  855. numpy/tests/test_configtool.py +51 -0
  856. numpy/tests/test_ctypeslib.py +383 -0
  857. numpy/tests/test_lazyloading.py +42 -0
  858. numpy/tests/test_matlib.py +59 -0
  859. numpy/tests/test_numpy_config.py +47 -0
  860. numpy/tests/test_numpy_version.py +54 -0
  861. numpy/tests/test_public_api.py +807 -0
  862. numpy/tests/test_reloading.py +76 -0
  863. numpy/tests/test_scripts.py +48 -0
  864. numpy/tests/test_warnings.py +79 -0
  865. numpy/typing/__init__.py +233 -0
  866. numpy/typing/__init__.pyi +3 -0
  867. numpy/typing/mypy_plugin.py +200 -0
  868. numpy/typing/tests/__init__.py +0 -0
  869. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  870. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  871. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  872. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  873. numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
  874. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  875. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  876. numpy/typing/tests/data/fail/char.pyi +63 -0
  877. numpy/typing/tests/data/fail/chararray.pyi +61 -0
  878. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  879. numpy/typing/tests/data/fail/constants.pyi +3 -0
  880. numpy/typing/tests/data/fail/datasource.pyi +16 -0
  881. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  882. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  883. numpy/typing/tests/data/fail/flatiter.pyi +38 -0
  884. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  885. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  886. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  887. numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
  888. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  889. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  890. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  891. numpy/typing/tests/data/fail/linalg.pyi +52 -0
  892. numpy/typing/tests/data/fail/ma.pyi +155 -0
  893. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  894. numpy/typing/tests/data/fail/modules.pyi +17 -0
  895. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  896. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  897. numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
  898. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  899. numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
  900. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  901. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  902. numpy/typing/tests/data/fail/random.pyi +62 -0
  903. numpy/typing/tests/data/fail/rec.pyi +17 -0
  904. numpy/typing/tests/data/fail/scalars.pyi +86 -0
  905. numpy/typing/tests/data/fail/shape.pyi +7 -0
  906. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  907. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  908. numpy/typing/tests/data/fail/strings.pyi +52 -0
  909. numpy/typing/tests/data/fail/testing.pyi +28 -0
  910. numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
  911. numpy/typing/tests/data/fail/type_check.pyi +12 -0
  912. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  913. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  914. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  915. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  916. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  917. numpy/typing/tests/data/mypy.ini +8 -0
  918. numpy/typing/tests/data/pass/arithmetic.py +614 -0
  919. numpy/typing/tests/data/pass/array_constructors.py +138 -0
  920. numpy/typing/tests/data/pass/array_like.py +43 -0
  921. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  922. numpy/typing/tests/data/pass/arrayterator.py +28 -0
  923. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  924. numpy/typing/tests/data/pass/comparisons.py +316 -0
  925. numpy/typing/tests/data/pass/dtype.py +57 -0
  926. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  927. numpy/typing/tests/data/pass/flatiter.py +26 -0
  928. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  929. numpy/typing/tests/data/pass/index_tricks.py +62 -0
  930. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  931. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  932. numpy/typing/tests/data/pass/lib_version.py +18 -0
  933. numpy/typing/tests/data/pass/literal.py +52 -0
  934. numpy/typing/tests/data/pass/ma.py +199 -0
  935. numpy/typing/tests/data/pass/mod.py +149 -0
  936. numpy/typing/tests/data/pass/modules.py +45 -0
  937. numpy/typing/tests/data/pass/multiarray.py +77 -0
  938. numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
  939. numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
  940. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  941. numpy/typing/tests/data/pass/nditer.py +4 -0
  942. numpy/typing/tests/data/pass/numeric.py +90 -0
  943. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  944. numpy/typing/tests/data/pass/random.py +1498 -0
  945. numpy/typing/tests/data/pass/recfunctions.py +164 -0
  946. numpy/typing/tests/data/pass/scalars.py +249 -0
  947. numpy/typing/tests/data/pass/shape.py +19 -0
  948. numpy/typing/tests/data/pass/simple.py +170 -0
  949. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  950. numpy/typing/tests/data/pass/ufunclike.py +52 -0
  951. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  952. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  953. numpy/typing/tests/data/reveal/arithmetic.pyi +719 -0
  954. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  955. numpy/typing/tests/data/reveal/array_constructors.pyi +277 -0
  956. numpy/typing/tests/data/reveal/arraypad.pyi +27 -0
  957. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  958. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  959. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  960. numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
  961. numpy/typing/tests/data/reveal/char.pyi +225 -0
  962. numpy/typing/tests/data/reveal/chararray.pyi +138 -0
  963. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  964. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  965. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  966. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  967. numpy/typing/tests/data/reveal/dtype.pyi +132 -0
  968. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  969. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  970. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  971. numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
  972. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  973. numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
  974. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  975. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  976. numpy/typing/tests/data/reveal/lib_function_base.pyi +409 -0
  977. numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
  978. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  979. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  980. numpy/typing/tests/data/reveal/linalg.pyi +154 -0
  981. numpy/typing/tests/data/reveal/ma.pyi +1098 -0
  982. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  983. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  984. numpy/typing/tests/data/reveal/mod.pyi +178 -0
  985. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  986. numpy/typing/tests/data/reveal/multiarray.pyi +197 -0
  987. numpy/typing/tests/data/reveal/nbit_base_example.pyi +20 -0
  988. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +82 -0
  989. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
  990. numpy/typing/tests/data/reveal/ndarray_misc.pyi +246 -0
  991. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
  992. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  993. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  994. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  995. numpy/typing/tests/data/reveal/numeric.pyi +170 -0
  996. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  997. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +217 -0
  998. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
  999. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  1000. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  1001. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  1002. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  1003. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  1004. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  1005. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  1006. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  1007. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  1008. numpy/typing/tests/data/reveal/twodim_base.pyi +225 -0
  1009. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  1010. numpy/typing/tests/data/reveal/ufunc_config.pyi +29 -0
  1011. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  1012. numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
  1013. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  1014. numpy/typing/tests/test_isfile.py +38 -0
  1015. numpy/typing/tests/test_runtime.py +110 -0
  1016. numpy/typing/tests/test_typing.py +205 -0
  1017. numpy/version.py +11 -0
  1018. numpy/version.pyi +9 -0
  1019. numpy-2.4.1.dist-info/METADATA +139 -0
  1020. numpy-2.4.1.dist-info/RECORD +1039 -0
  1021. numpy-2.4.1.dist-info/WHEEL +6 -0
  1022. numpy-2.4.1.dist-info/entry_points.txt +13 -0
  1023. numpy-2.4.1.dist-info/licenses/LICENSE.txt +935 -0
  1024. numpy-2.4.1.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
  1025. numpy-2.4.1.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
  1026. numpy-2.4.1.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
  1027. numpy-2.4.1.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
  1028. numpy-2.4.1.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
  1029. numpy-2.4.1.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
  1030. numpy-2.4.1.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
  1031. numpy-2.4.1.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
  1032. numpy-2.4.1.dist-info/licenses/numpy/ma/LICENSE +24 -0
  1033. numpy-2.4.1.dist-info/licenses/numpy/random/LICENSE.md +71 -0
  1034. numpy-2.4.1.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
  1035. numpy-2.4.1.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
  1036. numpy-2.4.1.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
  1037. numpy-2.4.1.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
  1038. numpy-2.4.1.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
  1039. numpy-2.4.1.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
@@ -0,0 +1,3405 @@
1
+ import ctypes as ct
2
+ import inspect
3
+ import itertools
4
+ import pickle
5
+ import sys
6
+ import warnings
7
+
8
+ import pytest
9
+ from pytest import param
10
+
11
+ import numpy as np
12
+ import numpy._core._operand_flag_tests as opflag_tests
13
+ import numpy._core._rational_tests as _rational_tests
14
+ import numpy._core._umath_tests as umt
15
+ import numpy._core.umath as ncu
16
+ import numpy.linalg._umath_linalg as uml
17
+ from numpy.exceptions import AxisError
18
+ from numpy.testing import (
19
+ HAS_REFCOUNT,
20
+ IS_PYPY,
21
+ IS_WASM,
22
+ assert_,
23
+ assert_allclose,
24
+ assert_almost_equal,
25
+ assert_array_almost_equal,
26
+ assert_array_equal,
27
+ assert_equal,
28
+ assert_no_warnings,
29
+ assert_raises,
30
+ )
31
+ from numpy.testing._private.utils import requires_memory
32
+
33
+ UNARY_UFUNCS = [obj for obj in np._core.umath.__dict__.values()
34
+ if isinstance(obj, np.ufunc)]
35
+ UNARY_OBJECT_UFUNCS = [uf for uf in UNARY_UFUNCS if "O->O" in uf.types]
36
+
37
+ # Remove functions that do not support `floats`
38
+ UNARY_OBJECT_UFUNCS.remove(np.bitwise_count)
39
+
40
+
41
+ class TestUfuncKwargs:
42
+ def test_kwarg_exact(self):
43
+ assert_raises(TypeError, np.add, 1, 2, castingx='safe')
44
+ assert_raises(TypeError, np.add, 1, 2, dtypex=int)
45
+ assert_raises(TypeError, np.add, 1, 2, extobjx=[4096])
46
+ assert_raises(TypeError, np.add, 1, 2, outx=None)
47
+ assert_raises(TypeError, np.add, 1, 2, sigx='ii->i')
48
+ assert_raises(TypeError, np.add, 1, 2, signaturex='ii->i')
49
+ assert_raises(TypeError, np.add, 1, 2, subokx=False)
50
+ assert_raises(TypeError, np.add, 1, 2, wherex=[True])
51
+
52
+ def test_sig_signature(self):
53
+ assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
54
+ signature='ii->i')
55
+
56
+ def test_sig_dtype(self):
57
+ assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
58
+ dtype=int)
59
+ assert_raises(TypeError, np.add, 1, 2, signature='ii->i',
60
+ dtype=int)
61
+
62
+ def test_extobj_removed(self):
63
+ assert_raises(TypeError, np.add, 1, 2, extobj=[4096])
64
+
65
+
66
+ class TestUfuncGenericLoops:
67
+ """Test generic loops.
68
+
69
+ The loops to be tested are:
70
+
71
+ PyUFunc_ff_f_As_dd_d
72
+ PyUFunc_ff_f
73
+ PyUFunc_dd_d
74
+ PyUFunc_gg_g
75
+ PyUFunc_FF_F_As_DD_D
76
+ PyUFunc_DD_D
77
+ PyUFunc_FF_F
78
+ PyUFunc_GG_G
79
+ PyUFunc_OO_O
80
+ PyUFunc_OO_O_method
81
+ PyUFunc_f_f_As_d_d
82
+ PyUFunc_d_d
83
+ PyUFunc_f_f
84
+ PyUFunc_g_g
85
+ PyUFunc_F_F_As_D_D
86
+ PyUFunc_F_F
87
+ PyUFunc_D_D
88
+ PyUFunc_G_G
89
+ PyUFunc_O_O
90
+ PyUFunc_O_O_method
91
+ PyUFunc_On_Om
92
+
93
+ Where:
94
+
95
+ f -- float
96
+ d -- double
97
+ g -- long double
98
+ F -- complex float
99
+ D -- complex double
100
+ G -- complex long double
101
+ O -- python object
102
+
103
+ It is difficult to assure that each of these loops is entered from the
104
+ Python level as the special cased loops are a moving target and the
105
+ corresponding types are architecture dependent. We probably need to
106
+ define C level testing ufuncs to get at them. For the time being, I've
107
+ just looked at the signatures registered in the build directory to find
108
+ relevant functions.
109
+
110
+ """
111
+ np_dtypes = [
112
+ (np.single, np.single), (np.single, np.double),
113
+ (np.csingle, np.csingle), (np.csingle, np.cdouble),
114
+ (np.double, np.double), (np.longdouble, np.longdouble),
115
+ (np.cdouble, np.cdouble), (np.clongdouble, np.clongdouble)]
116
+
117
+ @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
118
+ def test_unary_PyUFunc(self, input_dtype, output_dtype, f=np.exp, x=0, y=1):
119
+ xs = np.full(10, input_dtype(x), dtype=output_dtype)
120
+ ys = f(xs)[::2]
121
+ assert_allclose(ys, y)
122
+ assert_equal(ys.dtype, output_dtype)
123
+
124
+ def f2(x, y):
125
+ return x**y
126
+
127
+ @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
128
+ def test_binary_PyUFunc(self, input_dtype, output_dtype, f=f2, x=0, y=1):
129
+ xs = np.full(10, input_dtype(x), dtype=output_dtype)
130
+ ys = f(xs, xs)[::2]
131
+ assert_allclose(ys, y)
132
+ assert_equal(ys.dtype, output_dtype)
133
+
134
+ # class to use in testing object method loops
135
+ class foo:
136
+ def conjugate(self):
137
+ return np.bool(1)
138
+
139
+ def logical_xor(self, obj):
140
+ return np.bool(1)
141
+
142
+ def test_unary_PyUFunc_O_O(self):
143
+ x = np.ones(10, dtype=object)
144
+ assert_(np.all(np.abs(x) == 1))
145
+
146
+ def test_unary_PyUFunc_O_O_method_simple(self, foo=foo):
147
+ x = np.full(10, foo(), dtype=object)
148
+ assert_(np.all(np.conjugate(x) == True))
149
+
150
+ def test_binary_PyUFunc_OO_O(self):
151
+ x = np.ones(10, dtype=object)
152
+ assert_(np.all(np.add(x, x) == 2))
153
+
154
+ def test_binary_PyUFunc_OO_O_method(self, foo=foo):
155
+ x = np.full(10, foo(), dtype=object)
156
+ assert_(np.all(np.logical_xor(x, x)))
157
+
158
+ def test_binary_PyUFunc_On_Om_method(self, foo=foo):
159
+ x = np.full((10, 2, 3), foo(), dtype=object)
160
+ assert_(np.all(np.logical_xor(x, x)))
161
+
162
+ def test_python_complex_conjugate(self):
163
+ # The conjugate ufunc should fall back to calling the method:
164
+ arr = np.array([1 + 2j, 3 - 4j], dtype="O")
165
+ assert isinstance(arr[0], complex)
166
+ res = np.conjugate(arr)
167
+ assert res.dtype == np.dtype("O")
168
+ assert_array_equal(res, np.array([1 - 2j, 3 + 4j], dtype="O"))
169
+
170
+ @pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS)
171
+ def test_unary_PyUFunc_O_O_method_full(self, ufunc):
172
+ """Compare the result of the object loop with non-object one"""
173
+ val = np.float64(np.pi / 4)
174
+
175
+ class MyFloat(np.float64):
176
+ def __getattr__(self, attr):
177
+ try:
178
+ return super().__getattr__(attr)
179
+ except AttributeError:
180
+ return lambda: getattr(np._core.umath, attr)(val)
181
+
182
+ # Use 0-D arrays, to ensure the same element call
183
+ num_arr = np.array(val, dtype=np.float64)
184
+ obj_arr = np.array(MyFloat(val), dtype="O")
185
+
186
+ with np.errstate(all="raise"):
187
+ try:
188
+ res_num = ufunc(num_arr)
189
+ except Exception as exc:
190
+ with assert_raises(type(exc)):
191
+ ufunc(obj_arr)
192
+ else:
193
+ res_obj = ufunc(obj_arr)
194
+ assert_array_almost_equal(res_num.astype("O"), res_obj)
195
+
196
+
197
+ def _pickleable_module_global():
198
+ pass
199
+
200
+
201
+ class TestUfunc:
202
+ def test_pickle(self):
203
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
204
+ assert_(pickle.loads(pickle.dumps(np.sin,
205
+ protocol=proto)) is np.sin)
206
+
207
+ # Check that ufunc not defined in the top level numpy namespace
208
+ # such as numpy._core._rational_tests.test_add can also be pickled
209
+ res = pickle.loads(pickle.dumps(_rational_tests.test_add,
210
+ protocol=proto))
211
+ assert_(res is _rational_tests.test_add)
212
+
213
+ def test_pickle_withstring(self):
214
+ astring = (b"cnumpy.core\n_ufunc_reconstruct\np0\n"
215
+ b"(S'numpy._core.umath'\np1\nS'cos'\np2\ntp3\nRp4\n.")
216
+ assert_(pickle.loads(astring) is np.cos)
217
+
218
+ @pytest.mark.skipif(IS_PYPY, reason="'is' check does not work on PyPy")
219
+ def test_pickle_name_is_qualname(self):
220
+ # This tests that a simplification of our ufunc pickle code will
221
+ # lead to allowing qualnames as names. Future ufuncs should
222
+ # possible add a specific qualname, or a hook into pickling instead
223
+ # (dask+numba may benefit).
224
+ _pickleable_module_global.ufunc = umt._pickleable_module_global_ufunc
225
+
226
+ obj = pickle.loads(pickle.dumps(_pickleable_module_global.ufunc))
227
+ assert obj is umt._pickleable_module_global_ufunc
228
+
229
+ def test_reduceat_shifting_sum(self):
230
+ L = 6
231
+ x = np.arange(L)
232
+ idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel()
233
+ assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7])
234
+
235
+ def test_all_ufunc(self):
236
+ """Try to check presence and results of all ufuncs.
237
+
238
+ The list of ufuncs comes from generate_umath.py and is as follows:
239
+
240
+ ===== ==== ============= =============== ========================
241
+ done args function types notes
242
+ ===== ==== ============= =============== ========================
243
+ n 1 conjugate nums + O
244
+ n 1 absolute nums + O complex -> real
245
+ n 1 negative nums + O
246
+ n 1 sign nums + O -> int
247
+ n 1 invert bool + ints + O flts raise an error
248
+ n 1 degrees real + M cmplx raise an error
249
+ n 1 radians real + M cmplx raise an error
250
+ n 1 arccos flts + M
251
+ n 1 arccosh flts + M
252
+ n 1 arcsin flts + M
253
+ n 1 arcsinh flts + M
254
+ n 1 arctan flts + M
255
+ n 1 arctanh flts + M
256
+ n 1 cos flts + M
257
+ n 1 sin flts + M
258
+ n 1 tan flts + M
259
+ n 1 cosh flts + M
260
+ n 1 sinh flts + M
261
+ n 1 tanh flts + M
262
+ n 1 exp flts + M
263
+ n 1 expm1 flts + M
264
+ n 1 log flts + M
265
+ n 1 log10 flts + M
266
+ n 1 log1p flts + M
267
+ n 1 sqrt flts + M real x < 0 raises error
268
+ n 1 ceil real + M
269
+ n 1 trunc real + M
270
+ n 1 floor real + M
271
+ n 1 fabs real + M
272
+ n 1 rint flts + M
273
+ n 1 isnan flts -> bool
274
+ n 1 isinf flts -> bool
275
+ n 1 isfinite flts -> bool
276
+ n 1 signbit real -> bool
277
+ n 1 modf real -> (frac, int)
278
+ n 1 logical_not bool + nums + M -> bool
279
+ n 2 left_shift ints + O flts raise an error
280
+ n 2 right_shift ints + O flts raise an error
281
+ n 2 add bool + nums + O boolean + is ||
282
+ n 2 subtract bool + nums + O boolean - is ^
283
+ n 2 multiply bool + nums + O boolean * is &
284
+ n 2 divide nums + O
285
+ n 2 floor_divide nums + O
286
+ n 2 true_divide nums + O bBhH -> f, iIlLqQ -> d
287
+ n 2 fmod nums + M
288
+ n 2 power nums + O
289
+ n 2 greater bool + nums + O -> bool
290
+ n 2 greater_equal bool + nums + O -> bool
291
+ n 2 less bool + nums + O -> bool
292
+ n 2 less_equal bool + nums + O -> bool
293
+ n 2 equal bool + nums + O -> bool
294
+ n 2 not_equal bool + nums + O -> bool
295
+ n 2 logical_and bool + nums + M -> bool
296
+ n 2 logical_or bool + nums + M -> bool
297
+ n 2 logical_xor bool + nums + M -> bool
298
+ n 2 maximum bool + nums + O
299
+ n 2 minimum bool + nums + O
300
+ n 2 bitwise_and bool + ints + O flts raise an error
301
+ n 2 bitwise_or bool + ints + O flts raise an error
302
+ n 2 bitwise_xor bool + ints + O flts raise an error
303
+ n 2 arctan2 real + M
304
+ n 2 remainder ints + real + O
305
+ n 2 hypot real + M
306
+ ===== ==== ============= =============== ========================
307
+
308
+ Types other than those listed will be accepted, but they are cast to
309
+ the smallest compatible type for which the function is defined. The
310
+ casting rules are:
311
+
312
+ bool -> int8 -> float32
313
+ ints -> double
314
+
315
+ """
316
+ pass
317
+
318
+ # from include/numpy/ufuncobject.h
319
+ size_inferred = 2
320
+ can_ignore = 4
321
+
322
+ def test_signature0(self):
323
+ # the arguments to test_signature are: nin, nout, core_signature
324
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
325
+ 2, 1, "(i),(i)->()")
326
+ assert_equal(enabled, 1)
327
+ assert_equal(num_dims, (1, 1, 0))
328
+ assert_equal(ixs, (0, 0))
329
+ assert_equal(flags, (self.size_inferred,))
330
+ assert_equal(sizes, (-1,))
331
+
332
+ def test_signature1(self):
333
+ # empty core signature; treat as plain ufunc (with trivial core)
334
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
335
+ 2, 1, "(),()->()")
336
+ assert_equal(enabled, 0)
337
+ assert_equal(num_dims, (0, 0, 0))
338
+ assert_equal(ixs, ())
339
+ assert_equal(flags, ())
340
+ assert_equal(sizes, ())
341
+
342
+ def test_signature2(self):
343
+ # more complicated names for variables
344
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
345
+ 2, 1, "(i1,i2),(J_1)->(_kAB)")
346
+ assert_equal(enabled, 1)
347
+ assert_equal(num_dims, (2, 1, 1))
348
+ assert_equal(ixs, (0, 1, 2, 3))
349
+ assert_equal(flags, (self.size_inferred,) * 4)
350
+ assert_equal(sizes, (-1, -1, -1, -1))
351
+
352
+ def test_signature3(self):
353
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
354
+ 2, 1, "(i1, i12), (J_1)->(i12, i2)")
355
+ assert_equal(enabled, 1)
356
+ assert_equal(num_dims, (2, 1, 2))
357
+ assert_equal(ixs, (0, 1, 2, 1, 3))
358
+ assert_equal(flags, (self.size_inferred,) * 4)
359
+ assert_equal(sizes, (-1, -1, -1, -1))
360
+
361
+ def test_signature4(self):
362
+ # matrix_multiply signature from _umath_tests
363
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
364
+ 2, 1, "(n,k),(k,m)->(n,m)")
365
+ assert_equal(enabled, 1)
366
+ assert_equal(num_dims, (2, 2, 2))
367
+ assert_equal(ixs, (0, 1, 1, 2, 0, 2))
368
+ assert_equal(flags, (self.size_inferred,) * 3)
369
+ assert_equal(sizes, (-1, -1, -1))
370
+
371
+ def test_signature5(self):
372
+ # matmul signature from _umath_tests
373
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
374
+ 2, 1, "(n?,k),(k,m?)->(n?,m?)")
375
+ assert_equal(enabled, 1)
376
+ assert_equal(num_dims, (2, 2, 2))
377
+ assert_equal(ixs, (0, 1, 1, 2, 0, 2))
378
+ assert_equal(flags, (self.size_inferred | self.can_ignore,
379
+ self.size_inferred,
380
+ self.size_inferred | self.can_ignore))
381
+ assert_equal(sizes, (-1, -1, -1))
382
+
383
+ def test_signature6(self):
384
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
385
+ 1, 1, "(3)->()")
386
+ assert_equal(enabled, 1)
387
+ assert_equal(num_dims, (1, 0))
388
+ assert_equal(ixs, (0,))
389
+ assert_equal(flags, (0,))
390
+ assert_equal(sizes, (3,))
391
+
392
+ def test_signature7(self):
393
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
394
+ 3, 1, "(3),(03,3),(n)->(9)")
395
+ assert_equal(enabled, 1)
396
+ assert_equal(num_dims, (1, 2, 1, 1))
397
+ assert_equal(ixs, (0, 0, 0, 1, 2))
398
+ assert_equal(flags, (0, self.size_inferred, 0))
399
+ assert_equal(sizes, (3, -1, 9))
400
+
401
+ def test_signature8(self):
402
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
403
+ 3, 1, "(3?),(3?,3?),(n)->(9)")
404
+ assert_equal(enabled, 1)
405
+ assert_equal(num_dims, (1, 2, 1, 1))
406
+ assert_equal(ixs, (0, 0, 0, 1, 2))
407
+ assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
408
+ assert_equal(sizes, (3, -1, 9))
409
+
410
+ def test_signature9(self):
411
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
412
+ 1, 1, "( 3) -> ( )")
413
+ assert_equal(enabled, 1)
414
+ assert_equal(num_dims, (1, 0))
415
+ assert_equal(ixs, (0,))
416
+ assert_equal(flags, (0,))
417
+ assert_equal(sizes, (3,))
418
+
419
+ def test_signature10(self):
420
+ enabled, num_dims, ixs, flags, sizes = umt.test_signature(
421
+ 3, 1, "( 3? ) , (3? , 3?) ,(n )-> ( 9)")
422
+ assert_equal(enabled, 1)
423
+ assert_equal(num_dims, (1, 2, 1, 1))
424
+ assert_equal(ixs, (0, 0, 0, 1, 2))
425
+ assert_equal(flags, (self.can_ignore, self.size_inferred, 0))
426
+ assert_equal(sizes, (3, -1, 9))
427
+
428
+ def test_signature_failure_extra_parenthesis(self):
429
+ with assert_raises(ValueError):
430
+ umt.test_signature(2, 1, "((i)),(i)->()")
431
+
432
+ def test_signature_failure_mismatching_parenthesis(self):
433
+ with assert_raises(ValueError):
434
+ umt.test_signature(2, 1, "(i),)i(->()")
435
+
436
+ def test_signature_failure_signature_missing_input_arg(self):
437
+ with assert_raises(ValueError):
438
+ umt.test_signature(2, 1, "(i),->()")
439
+
440
+ def test_signature_failure_signature_missing_output_arg(self):
441
+ with assert_raises(ValueError):
442
+ umt.test_signature(2, 2, "(i),(i)->()")
443
+
444
+ def test_get_signature(self):
445
+ assert_equal(np.vecdot.signature, "(n),(n)->()")
446
+
447
+ def test_forced_sig(self):
448
+ a = 0.5 * np.arange(3, dtype='f8')
449
+ assert_equal(np.add(a, 0.5), [0.5, 1, 1.5])
450
+ with assert_raises(TypeError):
451
+ np.add(a, 0.5, sig='i', casting='unsafe')
452
+ assert_equal(np.add(a, 0.5, sig='ii->i', casting='unsafe'), [0, 0, 1])
453
+ with assert_raises(TypeError):
454
+ np.add(a, 0.5, sig=('i4',), casting='unsafe')
455
+ assert_equal(np.add(a, 0.5, sig=('i4', 'i4', 'i4'),
456
+ casting='unsafe'), [0, 0, 1])
457
+
458
+ b = np.zeros((3,), dtype='f8')
459
+ np.add(a, 0.5, out=b)
460
+ assert_equal(b, [0.5, 1, 1.5])
461
+ b[:] = 0
462
+ with assert_raises(TypeError):
463
+ np.add(a, 0.5, sig='i', out=b, casting='unsafe')
464
+ assert_equal(b, [0, 0, 0])
465
+ np.add(a, 0.5, sig='ii->i', out=b, casting='unsafe')
466
+ assert_equal(b, [0, 0, 1])
467
+ b[:] = 0
468
+ with assert_raises(TypeError):
469
+ np.add(a, 0.5, sig=('i4',), out=b, casting='unsafe')
470
+ assert_equal(b, [0, 0, 0])
471
+ np.add(a, 0.5, sig=('i4', 'i4', 'i4'), out=b, casting='unsafe')
472
+ assert_equal(b, [0, 0, 1])
473
+
474
+ def test_signature_all_None(self):
475
+ # signature all None, is an acceptable alternative (since 1.21)
476
+ # to not providing a signature.
477
+ res1 = np.add([3], [4], sig=(None, None, None))
478
+ res2 = np.add([3], [4])
479
+ assert_array_equal(res1, res2)
480
+ res1 = np.maximum([3], [4], sig=(None, None, None))
481
+ res2 = np.maximum([3], [4])
482
+ assert_array_equal(res1, res2)
483
+
484
+ with pytest.raises(TypeError):
485
+ # special case, that would be deprecated anyway, so errors:
486
+ np.add(3, 4, signature=(None,))
487
+
488
+ def test_signature_dtype_type(self):
489
+ # Since that will be the normal behaviour (past NumPy 1.21)
490
+ # we do support the types already:
491
+ float_dtype = type(np.dtype(np.float64))
492
+ np.add(3, 4, signature=(float_dtype, float_dtype, None))
493
+
494
+ @pytest.mark.parametrize("get_kwarg", [
495
+ param(lambda dt: {"dtype": dt}, id="dtype"),
496
+ param(lambda dt: {"signature": (dt, None, None)}, id="signature")])
497
+ def test_signature_dtype_instances_allowed(self, get_kwarg):
498
+ # We allow certain dtype instances when there is a clear singleton
499
+ # and the given one is equivalent; mainly for backcompat.
500
+ int64 = np.dtype("int64")
501
+ int64_2 = pickle.loads(pickle.dumps(int64))
502
+ # Relies on pickling behavior, if assert fails just remove test...
503
+ assert int64 is not int64_2
504
+
505
+ assert np.add(1, 2, **get_kwarg(int64_2)).dtype == int64
506
+ td = np.timedelta64(2, "s")
507
+ assert np.add(td, td, **get_kwarg("m8")).dtype == "m8[s]"
508
+
509
+ msg = "The `dtype` and `signature` arguments to ufuncs"
510
+
511
+ with pytest.raises(TypeError, match=msg):
512
+ np.add(3, 5, **get_kwarg(np.dtype("int64").newbyteorder()))
513
+ with pytest.raises(TypeError, match=msg):
514
+ np.add(3, 5, **get_kwarg(np.dtype("m8[ns]")))
515
+ with pytest.raises(TypeError, match=msg):
516
+ np.add(3, 5, **get_kwarg("m8[ns]"))
517
+
518
+ @pytest.mark.parametrize("casting", ["unsafe", "same_kind", "safe"])
519
+ def test_partial_signature_mismatch(self, casting):
520
+ # If the second argument matches already, no need to specify it:
521
+ res = np.ldexp(np.float32(1.), np.int_(2), dtype="d")
522
+ assert res.dtype == "d"
523
+ res = np.ldexp(np.float32(1.), np.int_(2), signature=(None, None, "d"))
524
+ assert res.dtype == "d"
525
+
526
+ # ldexp only has a loop for long input as second argument, overriding
527
+ # the output cannot help with that (no matter the casting)
528
+ with pytest.raises(TypeError):
529
+ np.ldexp(1., np.uint64(3), dtype="d")
530
+ with pytest.raises(TypeError):
531
+ np.ldexp(1., np.uint64(3), signature=(None, None, "d"))
532
+
533
+ def test_partial_signature_mismatch_with_cache(self):
534
+ with pytest.raises(TypeError):
535
+ np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
536
+ # Ensure e,d->None is in the dispatching cache (double loop)
537
+ np.add(np.float16(1), np.float64(2))
538
+ # The error must still be raised:
539
+ with pytest.raises(TypeError):
540
+ np.add(np.float16(1), np.uint64(2), sig=("e", "d", None))
541
+
542
+ def test_use_output_signature_for_all_arguments(self):
543
+ # Test that providing only `dtype=` or `signature=(None, None, dtype)`
544
+ # is sufficient if falling back to a homogeneous signature works.
545
+ # In this case, the `intp, intp -> intp` loop is chosen.
546
+ res = np.power(1.5, 2.8, dtype=np.intp, casting="unsafe")
547
+ assert res == 1 # the cast happens first.
548
+ res = np.power(1.5, 2.8, signature=(None, None, np.intp),
549
+ casting="unsafe")
550
+ assert res == 1
551
+ with pytest.raises(TypeError):
552
+ # the unsafe casting would normally cause errors though:
553
+ np.power(1.5, 2.8, dtype=np.intp)
554
+
555
+ def test_signature_errors(self):
556
+ with pytest.raises(TypeError,
557
+ match="the signature object to ufunc must be a string or"):
558
+ np.add(3, 4, signature=123.) # neither a string nor a tuple
559
+
560
+ with pytest.raises(ValueError):
561
+ # bad symbols that do not translate to dtypes
562
+ np.add(3, 4, signature="%^->#")
563
+
564
+ with pytest.raises(ValueError):
565
+ np.add(3, 4, signature=b"ii-i") # incomplete and byte string
566
+
567
+ with pytest.raises(ValueError):
568
+ np.add(3, 4, signature="ii>i") # incomplete string
569
+
570
+ with pytest.raises(ValueError):
571
+ np.add(3, 4, signature=(None, "f8")) # bad length
572
+
573
+ with pytest.raises(UnicodeDecodeError):
574
+ np.add(3, 4, signature=b"\xff\xff->i")
575
+
576
+ def test_forced_dtype_times(self):
577
+ # Signatures only set the type numbers (not the actual loop dtypes)
578
+ # so using `M` in a signature/dtype should generally work:
579
+ a = np.array(['2010-01-02', '1999-03-14', '1833-03'], dtype='>M8[D]')
580
+ np.maximum(a, a, dtype="M")
581
+ np.maximum.reduce(a, dtype="M")
582
+
583
+ arr = np.arange(10, dtype="m8[s]")
584
+ np.add(arr, arr, dtype="m")
585
+ np.maximum(arr, arr, dtype="m")
586
+
587
+ @pytest.mark.parametrize("ufunc", [np.add, np.sqrt])
588
+ def test_cast_safety(self, ufunc):
589
+ """Basic test for the safest casts, because ufuncs inner loops can
590
+ indicate a cast-safety as well (which is normally always "no").
591
+ """
592
+ def call_ufunc(arr, **kwargs):
593
+ return ufunc(*(arr,) * ufunc.nin, **kwargs)
594
+
595
+ arr = np.array([1., 2., 3.], dtype=np.float32)
596
+ arr_bs = arr.astype(arr.dtype.newbyteorder())
597
+ expected = call_ufunc(arr)
598
+ # Normally, a "no" cast:
599
+ res = call_ufunc(arr, casting="no")
600
+ assert_array_equal(expected, res)
601
+ # Byte-swapping is not allowed with "no" though:
602
+ with pytest.raises(TypeError):
603
+ call_ufunc(arr_bs, casting="no")
604
+
605
+ # But is allowed with "equiv":
606
+ res = call_ufunc(arr_bs, casting="equiv")
607
+ assert_array_equal(expected, res)
608
+
609
+ # Casting to float64 is safe, but not equiv:
610
+ with pytest.raises(TypeError):
611
+ call_ufunc(arr_bs, dtype=np.float64, casting="equiv")
612
+
613
+ # but it is safe cast:
614
+ res = call_ufunc(arr_bs, dtype=np.float64, casting="safe")
615
+ expected = call_ufunc(arr.astype(np.float64)) # upcast
616
+ assert_array_equal(expected, res)
617
+
618
+ @pytest.mark.parametrize("ufunc", [np.add, np.equal])
619
+ def test_cast_safety_scalar(self, ufunc):
620
+ # We test add and equal, because equal has special scalar handling
621
+ # Note that the "equiv" casting behavior should maybe be considered
622
+ # a current implementation detail.
623
+ with pytest.raises(TypeError):
624
+ # this picks an integer loop, which is not safe
625
+ ufunc(3., 4., dtype=int, casting="safe")
626
+
627
+ with pytest.raises(TypeError):
628
+ # We accept python float as float64 but not float32 for equiv.
629
+ ufunc(3., 4., dtype="float32", casting="equiv")
630
+
631
+ # Special case for object and equal (note that equiv implies safe)
632
+ ufunc(3, 4, dtype=object, casting="equiv")
633
+ # Picks a double loop for both, first is equiv, second safe:
634
+ ufunc(np.array([3.]), 3., casting="equiv")
635
+ ufunc(np.array([3.]), 3, casting="safe")
636
+ ufunc(np.array([3]), 3, casting="equiv")
637
+
638
+ def test_cast_safety_scalar_special(self):
639
+ # We allow this (and it succeeds) via object, although the equiv
640
+ # part may not be important.
641
+ np.equal(np.array([3]), 2**300, casting="equiv")
642
+
643
+ def test_true_divide(self):
644
+ a = np.array(10)
645
+ b = np.array(20)
646
+ tgt = np.array(0.5)
647
+
648
+ for tc in 'bhilqBHILQefdgFDG':
649
+ dt = np.dtype(tc)
650
+ aa = a.astype(dt)
651
+ bb = b.astype(dt)
652
+
653
+ # Check result value and dtype.
654
+ for x, y in itertools.product([aa, -aa], [bb, -bb]):
655
+
656
+ # Check with no output type specified
657
+ if tc in 'FDG':
658
+ tgt = complex(x) / complex(y)
659
+ else:
660
+ tgt = float(x) / float(y)
661
+
662
+ res = np.true_divide(x, y)
663
+ rtol = max(np.finfo(res).resolution, 1e-15)
664
+ assert_allclose(res, tgt, rtol=rtol)
665
+
666
+ if tc in 'bhilqBHILQ':
667
+ assert_(res.dtype.name == 'float64')
668
+ else:
669
+ assert_(res.dtype.name == dt.name)
670
+
671
+ # Check with output type specified. This also checks for the
672
+ # incorrect casts in issue gh-3484 because the unary '-' does
673
+ # not change types, even for unsigned types, Hence casts in the
674
+ # ufunc from signed to unsigned and vice versa will lead to
675
+ # errors in the values.
676
+ for tcout in 'bhilqBHILQ':
677
+ dtout = np.dtype(tcout)
678
+ assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
679
+
680
+ for tcout in 'efdg':
681
+ dtout = np.dtype(tcout)
682
+ if tc in 'FDG':
683
+ # Casting complex to float is not allowed
684
+ assert_raises(TypeError, np.true_divide, x, y, dtype=dtout)
685
+ else:
686
+ tgt = float(x) / float(y)
687
+ rtol = max(np.finfo(dtout).resolution, 1e-15)
688
+ # The value of tiny for double double is NaN
689
+ with warnings.catch_warnings():
690
+ warnings.simplefilter('ignore', UserWarning)
691
+ if not np.isnan(np.finfo(dtout).tiny):
692
+ atol = max(np.finfo(dtout).tiny, 3e-308)
693
+ else:
694
+ atol = 3e-308
695
+ # Some test values result in invalid for float16
696
+ # and the cast to it may overflow to inf.
697
+ with np.errstate(invalid='ignore', over='ignore'):
698
+ res = np.true_divide(x, y, dtype=dtout)
699
+ if not np.isfinite(res) and tcout == 'e':
700
+ continue
701
+ assert_allclose(res, tgt, rtol=rtol, atol=atol)
702
+ assert_(res.dtype.name == dtout.name)
703
+
704
+ for tcout in 'FDG':
705
+ dtout = np.dtype(tcout)
706
+ tgt = complex(x) / complex(y)
707
+ rtol = max(np.finfo(dtout).resolution, 1e-15)
708
+ # The value of tiny for double double is NaN
709
+ with warnings.catch_warnings():
710
+ warnings.simplefilter('ignore', UserWarning)
711
+ if not np.isnan(np.finfo(dtout).tiny):
712
+ atol = max(np.finfo(dtout).tiny, 3e-308)
713
+ else:
714
+ atol = 3e-308
715
+ res = np.true_divide(x, y, dtype=dtout)
716
+ if not np.isfinite(res):
717
+ continue
718
+ assert_allclose(res, tgt, rtol=rtol, atol=atol)
719
+ assert_(res.dtype.name == dtout.name)
720
+
721
+ # Check booleans
722
+ a = np.ones((), dtype=np.bool)
723
+ res = np.true_divide(a, a)
724
+ assert_(res == 1.0)
725
+ assert_(res.dtype.name == 'float64')
726
+ res = np.true_divide(~a, a)
727
+ assert_(res == 0.0)
728
+ assert_(res.dtype.name == 'float64')
729
+
730
+ def test_sum_stability(self):
731
+ a = np.ones(500, dtype=np.float32)
732
+ assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 4)
733
+
734
+ a = np.ones(500, dtype=np.float64)
735
+ assert_almost_equal((a / 10.).sum() - a.size / 10., 0, 13)
736
+
737
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
738
+ def test_sum(self):
739
+ for dt in (int, np.float16, np.float32, np.float64, np.longdouble):
740
+ for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
741
+ 128, 1024, 1235):
742
+ # warning if sum overflows, which it does in float16
743
+ with warnings.catch_warnings(record=True) as w:
744
+ warnings.simplefilter("always", RuntimeWarning)
745
+
746
+ tgt = dt(v * (v + 1) / 2)
747
+ overflow = not np.isfinite(tgt)
748
+ assert_equal(len(w), 1 * overflow)
749
+
750
+ d = np.arange(1, v + 1, dtype=dt)
751
+
752
+ assert_almost_equal(np.sum(d), tgt)
753
+ assert_equal(len(w), 2 * overflow)
754
+
755
+ assert_almost_equal(np.sum(d[::-1]), tgt)
756
+ assert_equal(len(w), 3 * overflow)
757
+
758
+ d = np.ones(500, dtype=dt)
759
+ assert_almost_equal(np.sum(d[::2]), 250.)
760
+ assert_almost_equal(np.sum(d[1::2]), 250.)
761
+ assert_almost_equal(np.sum(d[::3]), 167.)
762
+ assert_almost_equal(np.sum(d[1::3]), 167.)
763
+ assert_almost_equal(np.sum(d[::-2]), 250.)
764
+ assert_almost_equal(np.sum(d[-1::-2]), 250.)
765
+ assert_almost_equal(np.sum(d[::-3]), 167.)
766
+ assert_almost_equal(np.sum(d[-1::-3]), 167.)
767
+ # sum with first reduction entry != 0
768
+ d = np.ones((1,), dtype=dt)
769
+ d += d
770
+ assert_almost_equal(d, 2.)
771
+
772
+ def test_sum_complex(self):
773
+ for dt in (np.complex64, np.complex128, np.clongdouble):
774
+ for v in (0, 1, 2, 7, 8, 9, 15, 16, 19, 127,
775
+ 128, 1024, 1235):
776
+ tgt = dt(v * (v + 1) / 2) - dt((v * (v + 1) / 2) * 1j)
777
+ d = np.empty(v, dtype=dt)
778
+ d.real = np.arange(1, v + 1)
779
+ d.imag = -np.arange(1, v + 1)
780
+ assert_almost_equal(np.sum(d), tgt)
781
+ assert_almost_equal(np.sum(d[::-1]), tgt)
782
+
783
+ d = np.ones(500, dtype=dt) + 1j
784
+ assert_almost_equal(np.sum(d[::2]), 250. + 250j)
785
+ assert_almost_equal(np.sum(d[1::2]), 250. + 250j)
786
+ assert_almost_equal(np.sum(d[::3]), 167. + 167j)
787
+ assert_almost_equal(np.sum(d[1::3]), 167. + 167j)
788
+ assert_almost_equal(np.sum(d[::-2]), 250. + 250j)
789
+ assert_almost_equal(np.sum(d[-1::-2]), 250. + 250j)
790
+ assert_almost_equal(np.sum(d[::-3]), 167. + 167j)
791
+ assert_almost_equal(np.sum(d[-1::-3]), 167. + 167j)
792
+ # sum with first reduction entry != 0
793
+ d = np.ones((1,), dtype=dt) + 1j
794
+ d += d
795
+ assert_almost_equal(d, 2. + 2j)
796
+
797
+ def test_sum_initial(self):
798
+ # Integer, single axis
799
+ assert_equal(np.sum([3], initial=2), 5)
800
+
801
+ # Floating point
802
+ assert_almost_equal(np.sum([0.2], initial=0.1), 0.3)
803
+
804
+ # Multiple non-adjacent axes
805
+ assert_equal(np.sum(np.ones((2, 3, 5), dtype=np.int64), axis=(0, 2), initial=2),
806
+ [12, 12, 12])
807
+
808
+ def test_sum_where(self):
809
+ # More extensive tests done in test_reduction_with_where.
810
+ assert_equal(np.sum([[1., 2.], [3., 4.]], where=[True, False]), 4.)
811
+ assert_equal(np.sum([[1., 2.], [3., 4.]], axis=0, initial=5.,
812
+ where=[True, False]), [9., 5.])
813
+
814
+ def test_vecdot(self):
815
+ arr1 = np.arange(6).reshape((2, 3))
816
+ arr2 = np.arange(3).reshape((1, 3))
817
+
818
+ actual = np.vecdot(arr1, arr2)
819
+ expected = np.array([5, 14])
820
+
821
+ assert_array_equal(actual, expected)
822
+
823
+ actual2 = np.vecdot(arr1.T, arr2.T, axis=-2)
824
+ assert_array_equal(actual2, expected)
825
+
826
+ actual3 = np.vecdot(arr1.astype("object"), arr2)
827
+ assert_array_equal(actual3, expected.astype("object"))
828
+
829
+ def test_matvec(self):
830
+ arr1 = np.arange(6).reshape((2, 3))
831
+ arr2 = np.arange(3).reshape((1, 3))
832
+
833
+ actual = np.matvec(arr1, arr2)
834
+ expected = np.array([[5, 14]])
835
+
836
+ assert_array_equal(actual, expected)
837
+
838
+ actual2 = np.matvec(arr1.T, arr2.T, axes=[(-1, -2), -2, -1])
839
+ assert_array_equal(actual2, expected)
840
+
841
+ actual3 = np.matvec(arr1.astype("object"), arr2)
842
+ assert_array_equal(actual3, expected.astype("object"))
843
+
844
+ @pytest.mark.parametrize("vec", [
845
+ np.array([[1., 2., 3.], [4., 5., 6.]]),
846
+ np.array([[1., 2j, 3.], [4., 5., 6j]]),
847
+ np.array([[1., 2., 3.], [4., 5., 6.]], dtype=object),
848
+ np.array([[1., 2j, 3.], [4., 5., 6j]], dtype=object)])
849
+ @pytest.mark.parametrize("matrix", [
850
+ None,
851
+ np.array([[1. + 1j, 0.5, -0.5j],
852
+ [0.25, 2j, 0.],
853
+ [4., 0., -1j]])])
854
+ def test_vecmatvec_identity(self, matrix, vec):
855
+ """Check that (x†A)x equals x†(Ax)."""
856
+ mat = matrix if matrix is not None else np.eye(3)
857
+ matvec = np.matvec(mat, vec) # Ax
858
+ vecmat = np.vecmat(vec, mat) # x†A
859
+ if matrix is None:
860
+ assert_array_equal(matvec, vec)
861
+ assert_array_equal(vecmat.conj(), vec)
862
+ assert_array_equal(matvec, (mat @ vec[..., np.newaxis]).squeeze(-1))
863
+ assert_array_equal(vecmat, (vec[..., np.newaxis].mT.conj()
864
+ @ mat).squeeze(-2))
865
+ expected = np.einsum('...i,ij,...j', vec.conj(), mat, vec)
866
+ vec_matvec = (vec.conj() * matvec).sum(-1)
867
+ vecmat_vec = (vecmat * vec).sum(-1)
868
+ assert_array_equal(vec_matvec, expected)
869
+ assert_array_equal(vecmat_vec, expected)
870
+
871
+ @pytest.mark.parametrize("ufunc, shape1, shape2, conj", [
872
+ (np.vecdot, (3,), (3,), True),
873
+ (np.vecmat, (3,), (3, 1), True),
874
+ (np.matvec, (1, 3), (3,), False),
875
+ (np.matmul, (1, 3), (3, 1), False),
876
+ ])
877
+ def test_vecdot_matvec_vecmat_complex(self, ufunc, shape1, shape2, conj):
878
+ arr1 = np.array([1, 2j, 3])
879
+ arr2 = np.array([1, 2, 3])
880
+
881
+ actual1 = ufunc(arr1.reshape(shape1), arr2.reshape(shape2))
882
+ expected1 = np.array(((arr1.conj() if conj else arr1) * arr2).sum(),
883
+ ndmin=min(len(shape1), len(shape2)))
884
+ assert_array_equal(actual1, expected1)
885
+ # This would fail for conj=True, since matmul omits the conjugate.
886
+ if not conj:
887
+ assert_array_equal(arr1.reshape(shape1) @ arr2.reshape(shape2),
888
+ expected1)
889
+
890
+ actual2 = ufunc(arr2.reshape(shape1), arr1.reshape(shape2))
891
+ expected2 = np.array(((arr2.conj() if conj else arr2) * arr1).sum(),
892
+ ndmin=min(len(shape1), len(shape2)))
893
+ assert_array_equal(actual2, expected2)
894
+
895
+ actual3 = ufunc(arr1.reshape(shape1).astype("object"),
896
+ arr2.reshape(shape2).astype("object"))
897
+ expected3 = expected1.astype(object)
898
+ assert_array_equal(actual3, expected3)
899
+
900
+ def test_vecdot_subclass(self):
901
+ class MySubclass(np.ndarray):
902
+ pass
903
+
904
+ arr1 = np.arange(6).reshape((2, 3)).view(MySubclass)
905
+ arr2 = np.arange(3).reshape((1, 3)).view(MySubclass)
906
+ result = np.vecdot(arr1, arr2)
907
+ assert isinstance(result, MySubclass)
908
+
909
+ def test_vecdot_object_no_conjugate(self):
910
+ arr = np.array(["1", "2"], dtype=object)
911
+ with pytest.raises(AttributeError, match="conjugate"):
912
+ np.vecdot(arr, arr)
913
+
914
+ def test_vecdot_object_breaks_outer_loop_on_error(self):
915
+ arr1 = np.ones((3, 3)).astype(object)
916
+ arr2 = arr1.copy()
917
+ arr2[1, 1] = None
918
+ out = np.zeros(3).astype(object)
919
+ with pytest.raises(TypeError, match=r"\*: 'float' and 'NoneType'"):
920
+ np.vecdot(arr1, arr2, out=out)
921
+ assert out[0] == 3
922
+ assert out[1] == out[2] == 0
923
+
924
+ def test_broadcast(self):
925
+ msg = "broadcast"
926
+ a = np.arange(4).reshape((2, 1, 2))
927
+ b = np.arange(4).reshape((1, 2, 2))
928
+ assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
929
+ msg = "extend & broadcast loop dimensions"
930
+ b = np.arange(4).reshape((2, 2))
931
+ assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
932
+ # Broadcast in core dimensions should fail
933
+ a = np.arange(8).reshape((4, 2))
934
+ b = np.arange(4).reshape((4, 1))
935
+ assert_raises(ValueError, np.vecdot, a, b)
936
+ # Extend core dimensions should fail
937
+ a = np.arange(8).reshape((4, 2))
938
+ b = np.array(7)
939
+ assert_raises(ValueError, np.vecdot, a, b)
940
+ # Broadcast should fail
941
+ a = np.arange(2).reshape((2, 1, 1))
942
+ b = np.arange(3).reshape((3, 1, 1))
943
+ assert_raises(ValueError, np.vecdot, a, b)
944
+
945
+ # Writing to a broadcasted array with overlap should warn, gh-2705
946
+ a = np.arange(2)
947
+ b = np.arange(4).reshape((2, 2))
948
+ u, v = np.broadcast_arrays(a, b)
949
+ assert_equal(u.strides[0], 0)
950
+ x = u + v
951
+ with warnings.catch_warnings(record=True) as w:
952
+ warnings.simplefilter("always")
953
+ u += v
954
+ assert_equal(len(w), 1)
955
+ assert_(x[0, 0] != u[0, 0])
956
+
957
+ # Output reduction should not be allowed.
958
+ # See gh-15139
959
+ a = np.arange(6).reshape(3, 2)
960
+ b = np.ones(2)
961
+ out = np.empty(())
962
+ assert_raises(ValueError, np.vecdot, a, b, out)
963
+ out2 = np.empty(3)
964
+ c = np.vecdot(a, b, out2)
965
+ assert_(c is out2)
966
+
967
+ def test_out_broadcasts(self):
968
+ # For ufuncs and gufuncs (not for reductions), we currently allow
969
+ # the output to cause broadcasting of the input arrays.
970
+ # both along dimensions with shape 1 and dimensions which do not
971
+ # exist at all in the inputs.
972
+ arr = np.arange(3).reshape(1, 3)
973
+ out = np.empty((5, 4, 3))
974
+ np.add(arr, arr, out=out)
975
+ assert (out == np.arange(3) * 2).all()
976
+
977
+ # The same holds for gufuncs (gh-16484)
978
+ np.vecdot(arr, arr, out=out)
979
+ # the result would be just a scalar `5`, but is broadcast fully:
980
+ assert (out == 5).all()
981
+
982
+ @pytest.mark.parametrize(["arr", "out"], [
983
+ ([2], np.empty(())),
984
+ ([1, 2], np.empty(1)),
985
+ (np.ones((4, 3)), np.empty((4, 1)))],
986
+ ids=["(1,)->()", "(2,)->(1,)", "(4, 3)->(4, 1)"])
987
+ def test_out_broadcast_errors(self, arr, out):
988
+ # Output is (currently) allowed to broadcast inputs, but it cannot be
989
+ # smaller than the actual result.
990
+ with pytest.raises(ValueError, match="non-broadcastable"):
991
+ np.positive(arr, out=out)
992
+
993
+ with pytest.raises(ValueError, match="non-broadcastable"):
994
+ np.add(np.ones(()), arr, out=out)
995
+
996
+ def test_type_cast(self):
997
+ msg = "type cast"
998
+ a = np.arange(6, dtype='short').reshape((2, 3))
999
+ assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
1000
+ err_msg=msg)
1001
+ msg = "type cast on one argument"
1002
+ a = np.arange(6).reshape((2, 3))
1003
+ b = a + 0.1
1004
+ assert_array_almost_equal(np.vecdot(a, b), np.sum(a * b, axis=-1),
1005
+ err_msg=msg)
1006
+
1007
+ def test_endian(self):
1008
+ msg = "big endian"
1009
+ a = np.arange(6, dtype='>i4').reshape((2, 3))
1010
+ assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
1011
+ err_msg=msg)
1012
+ msg = "little endian"
1013
+ a = np.arange(6, dtype='<i4').reshape((2, 3))
1014
+ assert_array_equal(np.vecdot(a, a), np.sum(a * a, axis=-1),
1015
+ err_msg=msg)
1016
+
1017
+ # Output should always be native-endian
1018
+ Ba = np.arange(1, dtype='>f8')
1019
+ La = np.arange(1, dtype='<f8')
1020
+ assert_equal((Ba + Ba).dtype, np.dtype('f8'))
1021
+ assert_equal((Ba + La).dtype, np.dtype('f8'))
1022
+ assert_equal((La + Ba).dtype, np.dtype('f8'))
1023
+ assert_equal((La + La).dtype, np.dtype('f8'))
1024
+
1025
+ assert_equal(np.absolute(La).dtype, np.dtype('f8'))
1026
+ assert_equal(np.absolute(Ba).dtype, np.dtype('f8'))
1027
+ assert_equal(np.negative(La).dtype, np.dtype('f8'))
1028
+ assert_equal(np.negative(Ba).dtype, np.dtype('f8'))
1029
+
1030
+ def test_incontiguous_array(self):
1031
+ msg = "incontiguous memory layout of array"
1032
+ x = np.arange(64).reshape((2, 2, 2, 2, 2, 2))
1033
+ a = x[:, 0, :, 0, :, 0]
1034
+ b = x[:, 1, :, 1, :, 1]
1035
+ a[0, 0, 0] = -1
1036
+ msg2 = "make sure it references to the original array"
1037
+ assert_equal(x[0, 0, 0, 0, 0, 0], -1, err_msg=msg2)
1038
+ assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
1039
+ x = np.arange(24).reshape(2, 3, 4)
1040
+ a = x.T
1041
+ b = x.T
1042
+ a[0, 0, 0] = -1
1043
+ assert_equal(x[0, 0, 0], -1, err_msg=msg2)
1044
+ assert_array_equal(np.vecdot(a, b), np.sum(a * b, axis=-1), err_msg=msg)
1045
+
1046
+ def test_output_argument(self):
1047
+ msg = "output argument"
1048
+ a = np.arange(12).reshape((2, 3, 2))
1049
+ b = np.arange(4).reshape((2, 1, 2)) + 1
1050
+ c = np.zeros((2, 3), dtype='int')
1051
+ np.vecdot(a, b, c)
1052
+ assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
1053
+ c[:] = -1
1054
+ np.vecdot(a, b, out=c)
1055
+ assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
1056
+
1057
+ msg = "output argument with type cast"
1058
+ c = np.zeros((2, 3), dtype='int16')
1059
+ np.vecdot(a, b, c)
1060
+ assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
1061
+ c[:] = -1
1062
+ np.vecdot(a, b, out=c)
1063
+ assert_array_equal(c, np.sum(a * b, axis=-1), err_msg=msg)
1064
+
1065
+ msg = "output argument with incontiguous layout"
1066
+ c = np.zeros((2, 3, 4), dtype='int16')
1067
+ np.vecdot(a, b, c[..., 0])
1068
+ assert_array_equal(c[..., 0], np.sum(a * b, axis=-1), err_msg=msg)
1069
+ c[:] = -1
1070
+ np.vecdot(a, b, out=c[..., 0])
1071
+ assert_array_equal(c[..., 0], np.sum(a * b, axis=-1), err_msg=msg)
1072
+
1073
+ @pytest.mark.parametrize("arg", ["array", "scalar", "subclass"])
1074
+ def test_output_ellipsis(self, arg):
1075
+ class subclass(np.ndarray):
1076
+ def __array_wrap__(self, obj, context=None, return_value=None):
1077
+ return super().__array_wrap__(obj, context, return_value)
1078
+
1079
+ if arg == "scalar":
1080
+ one = 1
1081
+ expected_type = np.ndarray
1082
+ elif arg == "array":
1083
+ one = np.array(1)
1084
+ expected_type = np.ndarray
1085
+ elif arg == "subclass":
1086
+ one = np.array(1).view(subclass)
1087
+ expected_type = subclass
1088
+
1089
+ assert type(np.add(one, 2, out=...)) is expected_type
1090
+ assert type(np.add.reduce(one, out=...)) is expected_type
1091
+ res1, res2 = np.divmod(one, 2, out=...)
1092
+ assert type(res1) is type(res2) is expected_type
1093
+
1094
+ def test_output_ellipsis_errors(self):
1095
+ with pytest.raises(TypeError,
1096
+ match=r"out=\.\.\. is only allowed as a keyword argument."):
1097
+ np.add(1, 2, ...)
1098
+
1099
+ with pytest.raises(TypeError,
1100
+ match=r"out=\.\.\. is only allowed as a keyword argument."):
1101
+ np.add.reduce(1, (), None, ...)
1102
+
1103
+ type_error = r"must use `\.\.\.` as `out=\.\.\.` and not per-operand/in a tuple"
1104
+ with pytest.raises(TypeError, match=type_error):
1105
+ np.negative(1, out=(...,))
1106
+
1107
+ with pytest.raises(TypeError, match=type_error):
1108
+ # We only allow out=... not individual args for now
1109
+ np.divmod(1, 2, out=(np.empty(()), ...))
1110
+
1111
+ with pytest.raises(TypeError, match=type_error):
1112
+ np.add.reduce(1, out=(...,))
1113
+
1114
+ def test_axes_argument(self):
1115
+ # vecdot signature: '(n),(n)->()'
1116
+ a = np.arange(27.).reshape((3, 3, 3))
1117
+ b = np.arange(10., 19.).reshape((3, 1, 3))
1118
+ # basic tests on inputs (outputs tested below with matrix_multiply).
1119
+ c = np.vecdot(a, b)
1120
+ assert_array_equal(c, (a * b).sum(-1))
1121
+ # default
1122
+ c = np.vecdot(a, b, axes=[(-1,), (-1,), ()])
1123
+ assert_array_equal(c, (a * b).sum(-1))
1124
+ # integers ok for single axis.
1125
+ c = np.vecdot(a, b, axes=[-1, -1, ()])
1126
+ assert_array_equal(c, (a * b).sum(-1))
1127
+ # mix fine
1128
+ c = np.vecdot(a, b, axes=[(-1,), -1, ()])
1129
+ assert_array_equal(c, (a * b).sum(-1))
1130
+ # can omit last axis.
1131
+ c = np.vecdot(a, b, axes=[-1, -1])
1132
+ assert_array_equal(c, (a * b).sum(-1))
1133
+ # can pass in other types of integer (with __index__ protocol)
1134
+ c = np.vecdot(a, b, axes=[np.int8(-1), np.array(-1, dtype=np.int32)])
1135
+ assert_array_equal(c, (a * b).sum(-1))
1136
+ # swap some axes
1137
+ c = np.vecdot(a, b, axes=[0, 0])
1138
+ assert_array_equal(c, (a * b).sum(0))
1139
+ c = np.vecdot(a, b, axes=[0, 2])
1140
+ assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
1141
+ # Check errors for improperly constructed axes arguments.
1142
+ # should have list.
1143
+ assert_raises(TypeError, np.vecdot, a, b, axes=-1)
1144
+ # needs enough elements
1145
+ assert_raises(ValueError, np.vecdot, a, b, axes=[-1])
1146
+ # should pass in indices.
1147
+ assert_raises(TypeError, np.vecdot, a, b, axes=[-1.0, -1.0])
1148
+ assert_raises(TypeError, np.vecdot, a, b, axes=[(-1.0,), -1])
1149
+ assert_raises(TypeError, np.vecdot, a, b, axes=[None, 1])
1150
+ # cannot pass an index unless there is only one dimension
1151
+ # (output is wrong in this case)
1152
+ assert_raises(AxisError, np.vecdot, a, b, axes=[-1, -1, -1])
1153
+ # or pass in generally the wrong number of axes
1154
+ assert_raises(AxisError, np.vecdot, a, b, axes=[-1, -1, (-1,)])
1155
+ assert_raises(AxisError, np.vecdot, a, b, axes=[-1, (-2, -1), ()])
1156
+ # axes need to have same length.
1157
+ assert_raises(ValueError, np.vecdot, a, b, axes=[0, 1])
1158
+
1159
+ # matrix_multiply signature: '(m,n),(n,p)->(m,p)'
1160
+ mm = umt.matrix_multiply
1161
+ a = np.arange(12).reshape((2, 3, 2))
1162
+ b = np.arange(8).reshape((2, 2, 2, 1)) + 1
1163
+ # Sanity check.
1164
+ c = mm(a, b)
1165
+ assert_array_equal(c, np.matmul(a, b))
1166
+ # Default axes.
1167
+ c = mm(a, b, axes=[(-2, -1), (-2, -1), (-2, -1)])
1168
+ assert_array_equal(c, np.matmul(a, b))
1169
+ # Default with explicit axes.
1170
+ c = mm(a, b, axes=[(1, 2), (2, 3), (2, 3)])
1171
+ assert_array_equal(c, np.matmul(a, b))
1172
+ # swap some axes.
1173
+ c = mm(a, b, axes=[(0, -1), (1, 2), (-2, -1)])
1174
+ assert_array_equal(c, np.matmul(a.transpose(1, 0, 2),
1175
+ b.transpose(0, 3, 1, 2)))
1176
+ # Default with output array.
1177
+ c = np.empty((2, 2, 3, 1))
1178
+ d = mm(a, b, out=c, axes=[(1, 2), (2, 3), (2, 3)])
1179
+ assert_(c is d)
1180
+ assert_array_equal(c, np.matmul(a, b))
1181
+ # Transposed output array
1182
+ c = np.empty((1, 2, 2, 3))
1183
+ d = mm(a, b, out=c, axes=[(-2, -1), (-2, -1), (3, 0)])
1184
+ assert_(c is d)
1185
+ assert_array_equal(c, np.matmul(a, b).transpose(3, 0, 1, 2))
1186
+ # Check errors for improperly constructed axes arguments.
1187
+ # wrong argument
1188
+ assert_raises(TypeError, mm, a, b, axis=1)
1189
+ # axes should be list
1190
+ assert_raises(TypeError, mm, a, b, axes=1)
1191
+ assert_raises(TypeError, mm, a, b, axes=((-2, -1), (-2, -1), (-2, -1)))
1192
+ # list needs to have right length
1193
+ assert_raises(ValueError, mm, a, b, axes=[])
1194
+ assert_raises(ValueError, mm, a, b, axes=[(-2, -1)])
1195
+ # list should not contain None, or lists
1196
+ assert_raises(TypeError, mm, a, b, axes=[None, None, None])
1197
+ assert_raises(TypeError,
1198
+ mm, a, b, axes=[[-2, -1], [-2, -1], [-2, -1]])
1199
+ assert_raises(TypeError,
1200
+ mm, a, b, axes=[(-2, -1), (-2, -1), [-2, -1]])
1201
+ assert_raises(TypeError, mm, a, b, axes=[(-2, -1), (-2, -1), None])
1202
+ # single integers are AxisErrors if more are required
1203
+ assert_raises(AxisError, mm, a, b, axes=[-1, -1, -1])
1204
+ assert_raises(AxisError, mm, a, b, axes=[(-2, -1), (-2, -1), -1])
1205
+ # tuples should not have duplicated values
1206
+ assert_raises(ValueError, mm, a, b, axes=[(-2, -1), (-2, -1), (-2, -2)])
1207
+ # arrays should have enough axes.
1208
+ z = np.zeros((2, 2))
1209
+ assert_raises(ValueError, mm, z, z[0])
1210
+ assert_raises(ValueError, mm, z, z, out=z[:, 0])
1211
+ assert_raises(ValueError, mm, z[1], z, axes=[0, 1])
1212
+ assert_raises(ValueError, mm, z, z, out=z[0], axes=[0, 1])
1213
+ # Regular ufuncs should not accept axes.
1214
+ assert_raises(TypeError, np.add, 1., 1., axes=[0])
1215
+ # should be able to deal with bad unrelated kwargs.
1216
+ assert_raises(TypeError, mm, z, z, axes=[0, 1], parrot=True)
1217
+
1218
+ def test_axis_argument(self):
1219
+ # vecdot signature: '(n),(n)->()'
1220
+ a = np.arange(27.).reshape((3, 3, 3))
1221
+ b = np.arange(10., 19.).reshape((3, 1, 3))
1222
+ c = np.vecdot(a, b)
1223
+ assert_array_equal(c, (a * b).sum(-1))
1224
+ c = np.vecdot(a, b, axis=-1)
1225
+ assert_array_equal(c, (a * b).sum(-1))
1226
+ out = np.zeros_like(c)
1227
+ d = np.vecdot(a, b, axis=-1, out=out)
1228
+ assert_(d is out)
1229
+ assert_array_equal(d, c)
1230
+ c = np.vecdot(a, b, axis=0)
1231
+ assert_array_equal(c, (a * b).sum(0))
1232
+ # Sanity checks on innerwt and cumsum.
1233
+ a = np.arange(6).reshape((2, 3))
1234
+ b = np.arange(10, 16).reshape((2, 3))
1235
+ w = np.arange(20, 26).reshape((2, 3))
1236
+ assert_array_equal(umt.innerwt(a, b, w, axis=0),
1237
+ np.sum(a * b * w, axis=0))
1238
+ assert_array_equal(umt.cumsum(a, axis=0), np.cumsum(a, axis=0))
1239
+ assert_array_equal(umt.cumsum(a, axis=-1), np.cumsum(a, axis=-1))
1240
+ out = np.empty_like(a)
1241
+ b = umt.cumsum(a, out=out, axis=0)
1242
+ assert_(out is b)
1243
+ assert_array_equal(b, np.cumsum(a, axis=0))
1244
+ b = umt.cumsum(a, out=out, axis=1)
1245
+ assert_(out is b)
1246
+ assert_array_equal(b, np.cumsum(a, axis=-1))
1247
+ # Check errors.
1248
+ # Cannot pass in both axis and axes.
1249
+ assert_raises(TypeError, np.vecdot, a, b, axis=0, axes=[0, 0])
1250
+ # Not an integer.
1251
+ assert_raises(TypeError, np.vecdot, a, b, axis=[0])
1252
+ # more than 1 core dimensions.
1253
+ mm = umt.matrix_multiply
1254
+ assert_raises(TypeError, mm, a, b, axis=1)
1255
+ # Output wrong size in axis.
1256
+ out = np.empty((1, 2, 3), dtype=a.dtype)
1257
+ assert_raises(ValueError, umt.cumsum, a, out=out, axis=0)
1258
+ # Regular ufuncs should not accept axis.
1259
+ assert_raises(TypeError, np.add, 1., 1., axis=0)
1260
+
1261
+ def test_keepdims_argument(self):
1262
+ # vecdot signature: '(n),(n)->()'
1263
+ a = np.arange(27.).reshape((3, 3, 3))
1264
+ b = np.arange(10., 19.).reshape((3, 1, 3))
1265
+ c = np.vecdot(a, b)
1266
+ assert_array_equal(c, (a * b).sum(-1))
1267
+ c = np.vecdot(a, b, keepdims=False)
1268
+ assert_array_equal(c, (a * b).sum(-1))
1269
+ c = np.vecdot(a, b, keepdims=True)
1270
+ assert_array_equal(c, (a * b).sum(-1, keepdims=True))
1271
+ out = np.zeros_like(c)
1272
+ d = np.vecdot(a, b, keepdims=True, out=out)
1273
+ assert_(d is out)
1274
+ assert_array_equal(d, c)
1275
+ # Now combined with axis and axes.
1276
+ c = np.vecdot(a, b, axis=-1, keepdims=False)
1277
+ assert_array_equal(c, (a * b).sum(-1, keepdims=False))
1278
+ c = np.vecdot(a, b, axis=-1, keepdims=True)
1279
+ assert_array_equal(c, (a * b).sum(-1, keepdims=True))
1280
+ c = np.vecdot(a, b, axis=0, keepdims=False)
1281
+ assert_array_equal(c, (a * b).sum(0, keepdims=False))
1282
+ c = np.vecdot(a, b, axis=0, keepdims=True)
1283
+ assert_array_equal(c, (a * b).sum(0, keepdims=True))
1284
+ c = np.vecdot(a, b, axes=[(-1,), (-1,), ()], keepdims=False)
1285
+ assert_array_equal(c, (a * b).sum(-1))
1286
+ c = np.vecdot(a, b, axes=[(-1,), (-1,), (-1,)], keepdims=True)
1287
+ assert_array_equal(c, (a * b).sum(-1, keepdims=True))
1288
+ c = np.vecdot(a, b, axes=[0, 0], keepdims=False)
1289
+ assert_array_equal(c, (a * b).sum(0))
1290
+ c = np.vecdot(a, b, axes=[0, 0, 0], keepdims=True)
1291
+ assert_array_equal(c, (a * b).sum(0, keepdims=True))
1292
+ c = np.vecdot(a, b, axes=[0, 2], keepdims=False)
1293
+ assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1))
1294
+ c = np.vecdot(a, b, axes=[0, 2], keepdims=True)
1295
+ assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
1296
+ keepdims=True))
1297
+ c = np.vecdot(a, b, axes=[0, 2, 2], keepdims=True)
1298
+ assert_array_equal(c, (a.transpose(1, 2, 0) * b).sum(-1,
1299
+ keepdims=True))
1300
+ c = np.vecdot(a, b, axes=[0, 2, 0], keepdims=True)
1301
+ assert_array_equal(c, (a * b.transpose(2, 0, 1)).sum(0, keepdims=True))
1302
+ # Hardly useful, but should work.
1303
+ c = np.vecdot(a, b, axes=[0, 2, 1], keepdims=True)
1304
+ assert_array_equal(c, (a.transpose(1, 0, 2) * b.transpose(0, 2, 1))
1305
+ .sum(1, keepdims=True))
1306
+ # Check with two core dimensions.
1307
+ a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
1308
+ expected = uml.det(a)
1309
+ c = uml.det(a, keepdims=False)
1310
+ assert_array_equal(c, expected)
1311
+ c = uml.det(a, keepdims=True)
1312
+ assert_array_equal(c, expected[:, np.newaxis, np.newaxis])
1313
+ a = np.eye(3) * np.arange(4.)[:, np.newaxis, np.newaxis]
1314
+ expected_s, expected_l = uml.slogdet(a)
1315
+ cs, cl = uml.slogdet(a, keepdims=False)
1316
+ assert_array_equal(cs, expected_s)
1317
+ assert_array_equal(cl, expected_l)
1318
+ cs, cl = uml.slogdet(a, keepdims=True)
1319
+ assert_array_equal(cs, expected_s[:, np.newaxis, np.newaxis])
1320
+ assert_array_equal(cl, expected_l[:, np.newaxis, np.newaxis])
1321
+ # Sanity check on innerwt.
1322
+ a = np.arange(6).reshape((2, 3))
1323
+ b = np.arange(10, 16).reshape((2, 3))
1324
+ w = np.arange(20, 26).reshape((2, 3))
1325
+ assert_array_equal(umt.innerwt(a, b, w, keepdims=True),
1326
+ np.sum(a * b * w, axis=-1, keepdims=True))
1327
+ assert_array_equal(umt.innerwt(a, b, w, axis=0, keepdims=True),
1328
+ np.sum(a * b * w, axis=0, keepdims=True))
1329
+ # Check errors.
1330
+ # Not a boolean
1331
+ assert_raises(TypeError, np.vecdot, a, b, keepdims='true')
1332
+ # More than 1 core dimension, and core output dimensions.
1333
+ mm = umt.matrix_multiply
1334
+ assert_raises(TypeError, mm, a, b, keepdims=True)
1335
+ assert_raises(TypeError, mm, a, b, keepdims=False)
1336
+ # Regular ufuncs should not accept keepdims.
1337
+ assert_raises(TypeError, np.add, 1., 1., keepdims=False)
1338
+
1339
+ def test_innerwt(self):
1340
+ a = np.arange(6).reshape((2, 3))
1341
+ b = np.arange(10, 16).reshape((2, 3))
1342
+ w = np.arange(20, 26).reshape((2, 3))
1343
+ assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
1344
+ a = np.arange(100, 124).reshape((2, 3, 4))
1345
+ b = np.arange(200, 224).reshape((2, 3, 4))
1346
+ w = np.arange(300, 324).reshape((2, 3, 4))
1347
+ assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
1348
+
1349
+ def test_innerwt_empty(self):
1350
+ """Test generalized ufunc with zero-sized operands"""
1351
+ a = np.array([], dtype='f8')
1352
+ b = np.array([], dtype='f8')
1353
+ w = np.array([], dtype='f8')
1354
+ assert_array_equal(umt.innerwt(a, b, w), np.sum(a * b * w, axis=-1))
1355
+
1356
+ def test_cross1d(self):
1357
+ """Test with fixed-sized signature."""
1358
+ a = np.eye(3)
1359
+ assert_array_equal(umt.cross1d(a, a), np.zeros((3, 3)))
1360
+ out = np.zeros((3, 3))
1361
+ result = umt.cross1d(a[0], a, out)
1362
+ assert_(result is out)
1363
+ assert_array_equal(result, np.vstack((np.zeros(3), a[2], -a[1])))
1364
+ assert_raises(ValueError, umt.cross1d, np.eye(4), np.eye(4))
1365
+ assert_raises(ValueError, umt.cross1d, a, np.arange(4.))
1366
+ # Wrong output core dimension.
1367
+ assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros((3, 4)))
1368
+ # Wrong output broadcast dimension (see gh-15139).
1369
+ assert_raises(ValueError, umt.cross1d, a, np.arange(3.), np.zeros(3))
1370
+
1371
+ def test_can_ignore_signature(self):
1372
+ # Comparing the effects of ? in signature:
1373
+ # matrix_multiply: (m,n),(n,p)->(m,p) # all must be there.
1374
+ # matmul: (m?,n),(n,p?)->(m?,p?) # allow missing m, p.
1375
+ mat = np.arange(12).reshape((2, 3, 2))
1376
+ single_vec = np.arange(2)
1377
+ col_vec = single_vec[:, np.newaxis]
1378
+ col_vec_array = np.arange(8).reshape((2, 2, 2, 1)) + 1
1379
+ # matrix @ single column vector with proper dimension
1380
+ mm_col_vec = umt.matrix_multiply(mat, col_vec)
1381
+ # matmul does the same thing
1382
+ matmul_col_vec = umt.matmul(mat, col_vec)
1383
+ assert_array_equal(matmul_col_vec, mm_col_vec)
1384
+ # matrix @ vector without dimension making it a column vector.
1385
+ # matrix multiply fails -> missing core dim.
1386
+ assert_raises(ValueError, umt.matrix_multiply, mat, single_vec)
1387
+ # matmul mimicker passes, and returns a vector.
1388
+ matmul_col = umt.matmul(mat, single_vec)
1389
+ assert_array_equal(matmul_col, mm_col_vec.squeeze())
1390
+ # Now with a column array: same as for column vector,
1391
+ # broadcasting sensibly.
1392
+ mm_col_vec = umt.matrix_multiply(mat, col_vec_array)
1393
+ matmul_col_vec = umt.matmul(mat, col_vec_array)
1394
+ assert_array_equal(matmul_col_vec, mm_col_vec)
1395
+ # As above, but for row vector
1396
+ single_vec = np.arange(3)
1397
+ row_vec = single_vec[np.newaxis, :]
1398
+ row_vec_array = np.arange(24).reshape((4, 2, 1, 1, 3)) + 1
1399
+ # row vector @ matrix
1400
+ mm_row_vec = umt.matrix_multiply(row_vec, mat)
1401
+ matmul_row_vec = umt.matmul(row_vec, mat)
1402
+ assert_array_equal(matmul_row_vec, mm_row_vec)
1403
+ # single row vector @ matrix
1404
+ assert_raises(ValueError, umt.matrix_multiply, single_vec, mat)
1405
+ matmul_row = umt.matmul(single_vec, mat)
1406
+ assert_array_equal(matmul_row, mm_row_vec.squeeze())
1407
+ # row vector array @ matrix
1408
+ mm_row_vec = umt.matrix_multiply(row_vec_array, mat)
1409
+ matmul_row_vec = umt.matmul(row_vec_array, mat)
1410
+ assert_array_equal(matmul_row_vec, mm_row_vec)
1411
+ # Now for vector combinations
1412
+ # row vector @ column vector
1413
+ col_vec = row_vec.T
1414
+ col_vec_array = row_vec_array.swapaxes(-2, -1)
1415
+ mm_row_col_vec = umt.matrix_multiply(row_vec, col_vec)
1416
+ matmul_row_col_vec = umt.matmul(row_vec, col_vec)
1417
+ assert_array_equal(matmul_row_col_vec, mm_row_col_vec)
1418
+ # single row vector @ single col vector
1419
+ assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec)
1420
+ matmul_row_col = umt.matmul(single_vec, single_vec)
1421
+ assert_array_equal(matmul_row_col, mm_row_col_vec.squeeze())
1422
+ # row vector array @ matrix
1423
+ mm_row_col_array = umt.matrix_multiply(row_vec_array, col_vec_array)
1424
+ matmul_row_col_array = umt.matmul(row_vec_array, col_vec_array)
1425
+ assert_array_equal(matmul_row_col_array, mm_row_col_array)
1426
+ # Finally, check that things are *not* squeezed if one gives an
1427
+ # output.
1428
+ out = np.zeros_like(mm_row_col_array)
1429
+ out = umt.matrix_multiply(row_vec_array, col_vec_array, out=out)
1430
+ assert_array_equal(out, mm_row_col_array)
1431
+ out[:] = 0
1432
+ out = umt.matmul(row_vec_array, col_vec_array, out=out)
1433
+ assert_array_equal(out, mm_row_col_array)
1434
+ # And check one cannot put missing dimensions back.
1435
+ out = np.zeros_like(mm_row_col_vec)
1436
+ assert_raises(ValueError, umt.matrix_multiply, single_vec, single_vec,
1437
+ out)
1438
+ # But fine for matmul, since it is just a broadcast.
1439
+ out = umt.matmul(single_vec, single_vec, out)
1440
+ assert_array_equal(out, mm_row_col_vec.squeeze())
1441
+
1442
+ def test_matrix_multiply(self):
1443
+ self.compare_matrix_multiply_results(np.int64)
1444
+ self.compare_matrix_multiply_results(np.double)
1445
+
1446
+ def test_matrix_multiply_umath_empty(self):
1447
+ res = umt.matrix_multiply(np.ones((0, 10)), np.ones((10, 0)))
1448
+ assert_array_equal(res, np.zeros((0, 0)))
1449
+ res = umt.matrix_multiply(np.ones((10, 0)), np.ones((0, 10)))
1450
+ assert_array_equal(res, np.zeros((10, 10)))
1451
+
1452
+ def compare_matrix_multiply_results(self, tp):
1453
+ d1 = np.array(np.random.rand(2, 3, 4), dtype=tp)
1454
+ d2 = np.array(np.random.rand(2, 3, 4), dtype=tp)
1455
+ msg = f"matrix multiply on type {d1.dtype.name}"
1456
+
1457
+ def permute_n(n):
1458
+ if n == 1:
1459
+ return ([0],)
1460
+ ret = ()
1461
+ base = permute_n(n - 1)
1462
+ for perm in base:
1463
+ for i in range(n):
1464
+ new = perm + [n - 1]
1465
+ new[n - 1] = new[i]
1466
+ new[i] = n - 1
1467
+ ret += (new,)
1468
+ return ret
1469
+
1470
+ def slice_n(n):
1471
+ if n == 0:
1472
+ return ((),)
1473
+ ret = ()
1474
+ base = slice_n(n - 1)
1475
+ for sl in base:
1476
+ ret += (sl + (slice(None),),)
1477
+ ret += (sl + (slice(0, 1),),)
1478
+ return ret
1479
+
1480
+ def broadcastable(s1, s2):
1481
+ return s1 == s2 or 1 in {s1, s2}
1482
+
1483
+ permute_3 = permute_n(3)
1484
+ slice_3 = slice_n(3) + ((slice(None, None, -1),) * 3,)
1485
+
1486
+ ref = True
1487
+ for p1 in permute_3:
1488
+ for p2 in permute_3:
1489
+ for s1 in slice_3:
1490
+ for s2 in slice_3:
1491
+ a1 = d1.transpose(p1)[s1]
1492
+ a2 = d2.transpose(p2)[s2]
1493
+ ref = ref and a1.base is not None
1494
+ ref = ref and a2.base is not None
1495
+ if (a1.shape[-1] == a2.shape[-2] and
1496
+ broadcastable(a1.shape[0], a2.shape[0])):
1497
+ assert_array_almost_equal(
1498
+ umt.matrix_multiply(a1, a2),
1499
+ np.sum(a2[..., np.newaxis].swapaxes(-3, -1) *
1500
+ a1[..., np.newaxis, :], axis=-1),
1501
+ err_msg=msg + f' {str(a1.shape)} {str(a2.shape)}')
1502
+
1503
+ assert_equal(ref, True, err_msg="reference check")
1504
+
1505
+ def test_euclidean_pdist(self):
1506
+ a = np.arange(12, dtype=float).reshape(4, 3)
1507
+ out = np.empty((a.shape[0] * (a.shape[0] - 1) // 2,), dtype=a.dtype)
1508
+ umt.euclidean_pdist(a, out)
1509
+ b = np.sqrt(np.sum((a[:, None] - a)**2, axis=-1))
1510
+ b = b[~np.tri(a.shape[0], dtype=bool)]
1511
+ assert_almost_equal(out, b)
1512
+ # An output array is required to determine p with signature (n,d)->(p)
1513
+ assert_raises(ValueError, umt.euclidean_pdist, a)
1514
+
1515
+ def test_cumsum(self):
1516
+ a = np.arange(10)
1517
+ result = umt.cumsum(a)
1518
+ assert_array_equal(result, a.cumsum())
1519
+
1520
+ def test_object_logical(self):
1521
+ a = np.array([3, None, True, False, "test", ""], dtype=object)
1522
+ assert_equal(np.logical_or(a, None),
1523
+ np.array([x or None for x in a], dtype=object))
1524
+ assert_equal(np.logical_or(a, True),
1525
+ np.array([x or True for x in a], dtype=object))
1526
+ assert_equal(np.logical_or(a, 12),
1527
+ np.array([x or 12 for x in a], dtype=object))
1528
+ assert_equal(np.logical_or(a, "blah"),
1529
+ np.array([x or "blah" for x in a], dtype=object))
1530
+
1531
+ assert_equal(np.logical_and(a, None),
1532
+ np.array([x and None for x in a], dtype=object))
1533
+ assert_equal(np.logical_and(a, True),
1534
+ np.array([x and True for x in a], dtype=object))
1535
+ assert_equal(np.logical_and(a, 12),
1536
+ np.array([x and 12 for x in a], dtype=object))
1537
+ assert_equal(np.logical_and(a, "blah"),
1538
+ np.array([x and "blah" for x in a], dtype=object))
1539
+
1540
+ assert_equal(np.logical_not(a),
1541
+ np.array([not x for x in a], dtype=object))
1542
+
1543
+ assert_equal(np.logical_or.reduce(a), 3)
1544
+ assert_equal(np.logical_and.reduce(a), None)
1545
+
1546
+ def test_object_comparison(self):
1547
+ class HasComparisons:
1548
+ def __eq__(self, other):
1549
+ return '=='
1550
+
1551
+ arr0d = np.array(HasComparisons())
1552
+ assert_equal(arr0d == arr0d, True)
1553
+ assert_equal(np.equal(arr0d, arr0d), True) # normal behavior is a cast
1554
+
1555
+ arr1d = np.array([HasComparisons()])
1556
+ assert_equal(arr1d == arr1d, np.array([True]))
1557
+ # normal behavior is a cast
1558
+ assert_equal(np.equal(arr1d, arr1d), np.array([True]))
1559
+ assert_equal(np.equal(arr1d, arr1d, dtype=object), np.array(['==']))
1560
+
1561
+ def test_object_array_reduction(self):
1562
+ # Reductions on object arrays
1563
+ a = np.array(['a', 'b', 'c'], dtype=object)
1564
+ assert_equal(np.sum(a), 'abc')
1565
+ assert_equal(np.max(a), 'c')
1566
+ assert_equal(np.min(a), 'a')
1567
+ a = np.array([True, False, True], dtype=object)
1568
+ assert_equal(np.sum(a), 2)
1569
+ assert_equal(np.prod(a), 0)
1570
+ assert_equal(np.any(a), True)
1571
+ assert_equal(np.all(a), False)
1572
+ assert_equal(np.max(a), True)
1573
+ assert_equal(np.min(a), False)
1574
+ assert_equal(np.array([[1]], dtype=object).sum(), 1)
1575
+ assert_equal(np.array([[[1, 2]]], dtype=object).sum((0, 1)), [1, 2])
1576
+ assert_equal(np.array([1], dtype=object).sum(initial=1), 2)
1577
+ assert_equal(np.array([[1], [2, 3]], dtype=object)
1578
+ .sum(initial=[0], where=[False, True]), [0, 2, 3])
1579
+
1580
+ def test_object_array_accumulate_inplace(self):
1581
+ # Checks that in-place accumulates work, see also gh-7402
1582
+ arr = np.ones(4, dtype=object)
1583
+ arr[:] = [[1] for i in range(4)]
1584
+ # Twice reproduced also for tuples:
1585
+ np.add.accumulate(arr, out=arr)
1586
+ np.add.accumulate(arr, out=arr)
1587
+ assert_array_equal(arr,
1588
+ np.array([[1] * i for i in [1, 3, 6, 10]], dtype=object),
1589
+ )
1590
+
1591
+ # And the same if the axis argument is used
1592
+ arr = np.ones((2, 4), dtype=object)
1593
+ arr[0, :] = [[2] for i in range(4)]
1594
+ np.add.accumulate(arr, out=arr, axis=-1)
1595
+ np.add.accumulate(arr, out=arr, axis=-1)
1596
+ assert_array_equal(arr[0, :],
1597
+ np.array([[2] * i for i in [1, 3, 6, 10]], dtype=object),
1598
+ )
1599
+
1600
+ def test_object_array_accumulate_failure(self):
1601
+ # Typical accumulation on object works as expected:
1602
+ res = np.add.accumulate(np.array([1, 0, 2], dtype=object))
1603
+ assert_array_equal(res, np.array([1, 1, 3], dtype=object))
1604
+ # But errors are propagated from the inner-loop if they occur:
1605
+ with pytest.raises(TypeError):
1606
+ np.add.accumulate([1, None, 2])
1607
+
1608
+ def test_object_array_reduceat_inplace(self):
1609
+ # Checks that in-place reduceats work, see also gh-7465
1610
+ arr = np.empty(4, dtype=object)
1611
+ arr[:] = [[1] for i in range(4)]
1612
+ out = np.empty(4, dtype=object)
1613
+ out[:] = [[1] for i in range(4)]
1614
+ np.add.reduceat(arr, np.arange(4), out=arr)
1615
+ np.add.reduceat(arr, np.arange(4), out=arr)
1616
+ assert_array_equal(arr, out)
1617
+
1618
+ # And the same if the axis argument is used
1619
+ arr = np.ones((2, 4), dtype=object)
1620
+ arr[0, :] = [[2] for i in range(4)]
1621
+ out = np.ones((2, 4), dtype=object)
1622
+ out[0, :] = [[2] for i in range(4)]
1623
+ np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
1624
+ np.add.reduceat(arr, np.arange(4), out=arr, axis=-1)
1625
+ assert_array_equal(arr, out)
1626
+
1627
+ def test_object_array_reduceat_failure(self):
1628
+ # Reduceat works as expected when no invalid operation occurs (None is
1629
+ # not involved in an operation here)
1630
+ res = np.add.reduceat(np.array([1, None, 2], dtype=object), [1, 2])
1631
+ assert_array_equal(res, np.array([None, 2], dtype=object))
1632
+ # But errors when None would be involved in an operation:
1633
+ with pytest.raises(TypeError):
1634
+ np.add.reduceat([1, None, 2], [0, 2])
1635
+
1636
+ def test_zerosize_reduction(self):
1637
+ # Test with default dtype and object dtype
1638
+ for a in [[], np.array([], dtype=object)]:
1639
+ assert_equal(np.sum(a), 0)
1640
+ assert_equal(np.prod(a), 1)
1641
+ assert_equal(np.any(a), False)
1642
+ assert_equal(np.all(a), True)
1643
+ assert_raises(ValueError, np.max, a)
1644
+ assert_raises(ValueError, np.min, a)
1645
+
1646
+ def test_axis_out_of_bounds(self):
1647
+ a = np.array([False, False])
1648
+ assert_raises(AxisError, a.all, axis=1)
1649
+ a = np.array([False, False])
1650
+ assert_raises(AxisError, a.all, axis=-2)
1651
+
1652
+ a = np.array([False, False])
1653
+ assert_raises(AxisError, a.any, axis=1)
1654
+ a = np.array([False, False])
1655
+ assert_raises(AxisError, a.any, axis=-2)
1656
+
1657
+ def test_scalar_reduction(self):
1658
+ # The functions 'sum', 'prod', etc allow specifying axis=0
1659
+ # even for scalars
1660
+ assert_equal(np.sum(3, axis=0), 3)
1661
+ assert_equal(np.prod(3.5, axis=0), 3.5)
1662
+ assert_equal(np.any(True, axis=0), True)
1663
+ assert_equal(np.all(False, axis=0), False)
1664
+ assert_equal(np.max(3, axis=0), 3)
1665
+ assert_equal(np.min(2.5, axis=0), 2.5)
1666
+
1667
+ # Check scalar behaviour for ufuncs without an identity
1668
+ assert_equal(np.power.reduce(3), 3)
1669
+
1670
+ # Make sure that scalars are coming out from this operation
1671
+ assert_(type(np.prod(np.float32(2.5), axis=0)) is np.float32)
1672
+ assert_(type(np.sum(np.float32(2.5), axis=0)) is np.float32)
1673
+ assert_(type(np.max(np.float32(2.5), axis=0)) is np.float32)
1674
+ assert_(type(np.min(np.float32(2.5), axis=0)) is np.float32)
1675
+
1676
+ # check if scalars/0-d arrays get cast
1677
+ assert_(type(np.any(0, axis=0)) is np.bool)
1678
+
1679
+ # assert that 0-d arrays get wrapped
1680
+ class MyArray(np.ndarray):
1681
+ pass
1682
+ a = np.array(1).view(MyArray)
1683
+ assert_(type(np.any(a)) is MyArray)
1684
+
1685
+ def test_casting_out_param(self):
1686
+ # Test that it's possible to do casts on output
1687
+ a = np.ones((200, 100), np.int64)
1688
+ b = np.ones((200, 100), np.int64)
1689
+ c = np.ones((200, 100), np.float64)
1690
+ np.add(a, b, out=c)
1691
+ assert_equal(c, 2)
1692
+
1693
+ a = np.zeros(65536)
1694
+ b = np.zeros(65536, dtype=np.float32)
1695
+ np.subtract(a, 0, out=b)
1696
+ assert_equal(b, 0)
1697
+
1698
+ def test_where_param(self):
1699
+ # Test that the where= ufunc parameter works with regular arrays
1700
+ a = np.arange(7)
1701
+ b = np.ones(7)
1702
+ c = np.zeros(7)
1703
+ np.add(a, b, out=c, where=(a % 2 == 1))
1704
+ assert_equal(c, [0, 2, 0, 4, 0, 6, 0])
1705
+
1706
+ a = np.arange(4).reshape(2, 2) + 2
1707
+ np.power(a, [2, 3], out=a, where=[[0, 1], [1, 0]])
1708
+ assert_equal(a, [[2, 27], [16, 5]])
1709
+ # Broadcasting the where= parameter
1710
+ np.subtract(a, 2, out=a, where=[True, False])
1711
+ assert_equal(a, [[0, 27], [14, 5]])
1712
+
1713
+ def test_where_param_buffer_output(self):
1714
+ # With casting on output
1715
+ a = np.ones(10, np.int64)
1716
+ b = np.ones(10, np.int64)
1717
+ c = 1.5 * np.ones(10, np.float64)
1718
+ np.add(a, b, out=c, where=[1, 0, 0, 1, 0, 0, 1, 1, 1, 0])
1719
+ assert_equal(c, [2, 1.5, 1.5, 2, 1.5, 1.5, 2, 2, 2, 1.5])
1720
+
1721
+ def test_where_param_alloc(self):
1722
+ # With casting and allocated output
1723
+ a = np.array([1], dtype=np.int64)
1724
+ m = np.array([True], dtype=bool)
1725
+ assert_equal(np.sqrt(a, where=m, out=None), [1])
1726
+
1727
+ # No casting and allocated output
1728
+ a = np.array([1], dtype=np.float64)
1729
+ m = np.array([True], dtype=bool)
1730
+ assert_equal(np.sqrt(a, where=m, out=None), [1])
1731
+
1732
+ def test_where_with_broadcasting(self):
1733
+ # See gh-17198
1734
+ a = np.random.random((5000, 4))
1735
+ b = np.random.random((5000, 1))
1736
+
1737
+ where = a > 0.3
1738
+ out = np.full_like(a, 0)
1739
+ np.less(a, b, where=where, out=out)
1740
+ b_where = np.broadcast_to(b, a.shape)[where]
1741
+ assert_array_equal((a[where] < b_where), out[where].astype(bool))
1742
+ assert not out[~where].any() # outside mask, out remains all 0
1743
+
1744
+ def test_where_warns(self):
1745
+ a = np.arange(7)
1746
+ mask = a % 2 == 0
1747
+ with pytest.warns(UserWarning, match="'where' used without 'out'"):
1748
+ result1 = np.add(a, a, where=mask)
1749
+ # Does not warn
1750
+ result2 = np.add(a, a, where=mask, out=None)
1751
+ # Sanity check
1752
+ assert np.all(result1[::2] == [0, 4, 8, 12])
1753
+ assert np.all(result2[::2] == [0, 4, 8, 12])
1754
+
1755
+ @staticmethod
1756
+ def identityless_reduce_arrs():
1757
+ yield np.empty((2, 3, 4), order='C')
1758
+ yield np.empty((2, 3, 4), order='F')
1759
+ # Mixed order (reduce order differs outer)
1760
+ yield np.empty((2, 4, 3), order='C').swapaxes(1, 2)
1761
+ # Reversed order
1762
+ yield np.empty((2, 3, 4), order='C')[::-1, ::-1, ::-1]
1763
+ # Not contiguous
1764
+ yield np.empty((3, 5, 4), order='C').swapaxes(1, 2)[1:, 1:, 1:]
1765
+ # Not contiguous and not aligned
1766
+ a = np.empty((3 * 4 * 5 * 8 + 1,), dtype='i1')
1767
+ a = a[1:].view(dtype='f8')
1768
+ a.shape = (3, 4, 5)
1769
+ a = a[1:, 1:, 1:]
1770
+ yield a
1771
+
1772
+ @pytest.mark.parametrize("arrs", identityless_reduce_arrs())
1773
+ @pytest.mark.parametrize("pos", [(1, 0, 0), (0, 1, 0), (0, 0, 1)])
1774
+ def test_identityless_reduction(self, arrs, pos):
1775
+ # np.minimum.reduce is an identityless reduction
1776
+ a = arrs.copy()
1777
+ a[...] = 1
1778
+ a[pos] = 0
1779
+
1780
+ for axis in [None, (0, 1), (0, 2), (1, 2), 0, 1, 2, ()]:
1781
+ if axis is None:
1782
+ axes = np.array([], dtype=np.intp)
1783
+ else:
1784
+ axes = np.delete(np.arange(a.ndim), axis)
1785
+
1786
+ expected_pos = tuple(np.array(pos)[axes])
1787
+ expected = np.ones(np.array(a.shape)[axes])
1788
+ expected[expected_pos] = 0
1789
+
1790
+ res = np.minimum.reduce(a, axis=axis)
1791
+ assert_equal(res, expected, strict=True)
1792
+
1793
+ res = np.full_like(res, np.nan)
1794
+ np.minimum.reduce(a, axis=axis, out=res)
1795
+ assert_equal(res, expected, strict=True)
1796
+
1797
+ @requires_memory(6 * 1024**3)
1798
+ @pytest.mark.skipif(sys.maxsize < 2**32,
1799
+ reason="test array too large for 32bit platform")
1800
+ @pytest.mark.thread_unsafe(reason="crashes with low memory")
1801
+ def test_identityless_reduction_huge_array(self):
1802
+ # Regression test for gh-20921 (copying identity incorrectly failed)
1803
+ arr = np.zeros((2, 2**31), 'uint8')
1804
+ arr[:, 0] = [1, 3]
1805
+ arr[:, -1] = [4, 1]
1806
+ res = np.maximum.reduce(arr, axis=0)
1807
+ del arr
1808
+ assert res[0] == 3
1809
+ assert res[-1] == 4
1810
+
1811
+ def test_reduce_identity_depends_on_loop(self):
1812
+ """
1813
+ The type of the result should always depend on the selected loop, not
1814
+ necessarily the output (only relevant for object arrays).
1815
+ """
1816
+ # For an object loop, the default value 0 with type int is used:
1817
+ assert type(np.add.reduce([], dtype=object)) is int
1818
+ out = np.array(None, dtype=object)
1819
+ # When the loop is float64 but `out` is object this does not happen,
1820
+ # the result is float64 cast to object (which gives Python `float`).
1821
+ np.add.reduce([], out=out, dtype=np.float64)
1822
+ assert type(out[()]) is float
1823
+
1824
+ def test_initial_reduction(self):
1825
+ # np.minimum.reduce is an identityless reduction
1826
+
1827
+ # For cases like np.maximum(np.abs(...), initial=0)
1828
+ # More generally, a supremum over non-negative numbers.
1829
+ assert_equal(np.maximum.reduce([], initial=0), 0)
1830
+
1831
+ # For cases like reduction of an empty array over the reals.
1832
+ assert_equal(np.minimum.reduce([], initial=np.inf), np.inf)
1833
+ assert_equal(np.maximum.reduce([], initial=-np.inf), -np.inf)
1834
+
1835
+ # Random tests
1836
+ assert_equal(np.minimum.reduce([5], initial=4), 4)
1837
+ assert_equal(np.maximum.reduce([4], initial=5), 5)
1838
+ assert_equal(np.maximum.reduce([5], initial=4), 5)
1839
+ assert_equal(np.minimum.reduce([4], initial=5), 4)
1840
+
1841
+ # Check initial=None raises ValueError for both types of ufunc reductions
1842
+ assert_raises(ValueError, np.minimum.reduce, [], initial=None)
1843
+ assert_raises(ValueError, np.add.reduce, [], initial=None)
1844
+ # Also in the somewhat special object case:
1845
+ with pytest.raises(ValueError):
1846
+ np.add.reduce([], initial=None, dtype=object)
1847
+
1848
+ # Check that np._NoValue gives default behavior.
1849
+ assert_equal(np.add.reduce([], initial=np._NoValue), 0)
1850
+
1851
+ # Check that initial kwarg behaves as intended for dtype=object
1852
+ a = np.array([10], dtype=object)
1853
+ res = np.add.reduce(a, initial=5)
1854
+ assert_equal(res, 15)
1855
+
1856
+ def test_empty_reduction_and_identity(self):
1857
+ arr = np.zeros((0, 5))
1858
+ # OK, since the reduction itself is *not* empty, the result is
1859
+ assert np.true_divide.reduce(arr, axis=1).shape == (0,)
1860
+ # Not OK, the reduction itself is empty and we have no identity
1861
+ with pytest.raises(ValueError):
1862
+ np.true_divide.reduce(arr, axis=0)
1863
+
1864
+ # Test that an empty reduction fails also if the result is empty
1865
+ arr = np.zeros((0, 0, 5))
1866
+ with pytest.raises(ValueError):
1867
+ np.true_divide.reduce(arr, axis=1)
1868
+
1869
+ # Division reduction makes sense with `initial=1` (empty or not):
1870
+ res = np.true_divide.reduce(arr, axis=1, initial=1)
1871
+ assert_array_equal(res, np.ones((0, 5)))
1872
+
1873
+ @pytest.mark.parametrize('axis', (0, 1, None))
1874
+ @pytest.mark.parametrize('where', (np.array([False, True, True]),
1875
+ np.array([[True], [False], [True]]),
1876
+ np.array([[True, False, False],
1877
+ [False, True, False],
1878
+ [False, True, True]])))
1879
+ def test_reduction_with_where(self, axis, where):
1880
+ a = np.arange(9.).reshape(3, 3)
1881
+ a_copy = a.copy()
1882
+ a_check = np.zeros_like(a)
1883
+ np.positive(a, out=a_check, where=where)
1884
+
1885
+ res = np.add.reduce(a, axis=axis, where=where)
1886
+ check = a_check.sum(axis)
1887
+ assert_equal(res, check)
1888
+ # Check we do not overwrite elements of a internally.
1889
+ assert_array_equal(a, a_copy)
1890
+
1891
+ @pytest.mark.parametrize(('axis', 'where'),
1892
+ ((0, np.array([True, False, True])),
1893
+ (1, [True, True, False]),
1894
+ (None, True)))
1895
+ @pytest.mark.parametrize('initial', (-np.inf, 5.))
1896
+ def test_reduction_with_where_and_initial(self, axis, where, initial):
1897
+ a = np.arange(9.).reshape(3, 3)
1898
+ a_copy = a.copy()
1899
+ a_check = np.full(a.shape, -np.inf)
1900
+ np.positive(a, out=a_check, where=where)
1901
+
1902
+ res = np.maximum.reduce(a, axis=axis, where=where, initial=initial)
1903
+ check = a_check.max(axis, initial=initial)
1904
+ assert_equal(res, check)
1905
+
1906
+ def test_reduction_where_initial_needed(self):
1907
+ a = np.arange(9.).reshape(3, 3)
1908
+ m = [False, True, False]
1909
+ assert_raises(ValueError, np.maximum.reduce, a, where=m)
1910
+
1911
+ def test_identityless_reduction_nonreorderable(self):
1912
+ a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]])
1913
+
1914
+ res = np.divide.reduce(a, axis=0)
1915
+ assert_equal(res, [8.0, 4.0, 8.0])
1916
+
1917
+ res = np.divide.reduce(a, axis=1)
1918
+ assert_equal(res, [2.0, 8.0])
1919
+
1920
+ res = np.divide.reduce(a, axis=())
1921
+ assert_equal(res, a)
1922
+
1923
+ assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1))
1924
+
1925
+ def test_reduce_zero_axis(self):
1926
+ # If we have an n x m array and do a reduction with axis=1, then we are
1927
+ # doing n reductions, and each reduction takes an m-element array. For
1928
+ # a reduction operation without an identity, then:
1929
+ # n > 0, m > 0: fine
1930
+ # n = 0, m > 0: fine, doing 0 reductions of m-element arrays
1931
+ # n > 0, m = 0: can't reduce a 0-element array, ValueError
1932
+ # n = 0, m = 0: can't reduce a 0-element array, ValueError (for
1933
+ # consistency with the above case)
1934
+ # This test doesn't actually look at return values, it just checks to
1935
+ # make sure that error we get an error in exactly those cases where we
1936
+ # expect one, and assumes the calculations themselves are done
1937
+ # correctly.
1938
+
1939
+ def ok(f, *args, **kwargs):
1940
+ f(*args, **kwargs)
1941
+
1942
+ def err(f, *args, **kwargs):
1943
+ assert_raises(ValueError, f, *args, **kwargs)
1944
+
1945
+ def t(expect, func, n, m):
1946
+ expect(func, np.zeros((n, m)), axis=1)
1947
+ expect(func, np.zeros((m, n)), axis=0)
1948
+ expect(func, np.zeros((n // 2, n // 2, m)), axis=2)
1949
+ expect(func, np.zeros((n // 2, m, n // 2)), axis=1)
1950
+ expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2))
1951
+ expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2))
1952
+ expect(func, np.zeros((m // 3, m // 3, m // 3,
1953
+ n // 2, n // 2)),
1954
+ axis=(0, 1, 2))
1955
+ # Check what happens if the inner (resp. outer) dimensions are a
1956
+ # mix of zero and non-zero:
1957
+ expect(func, np.zeros((10, m, n)), axis=(0, 1))
1958
+ expect(func, np.zeros((10, n, m)), axis=(0, 2))
1959
+ expect(func, np.zeros((m, 10, n)), axis=0)
1960
+ expect(func, np.zeros((10, m, n)), axis=1)
1961
+ expect(func, np.zeros((10, n, m)), axis=2)
1962
+
1963
+ # np.maximum is just an arbitrary ufunc with no reduction identity
1964
+ assert_equal(np.maximum.identity, None)
1965
+ t(ok, np.maximum.reduce, 30, 30)
1966
+ t(ok, np.maximum.reduce, 0, 30)
1967
+ t(err, np.maximum.reduce, 30, 0)
1968
+ t(err, np.maximum.reduce, 0, 0)
1969
+ err(np.maximum.reduce, [])
1970
+ np.maximum.reduce(np.zeros((0, 0)), axis=())
1971
+
1972
+ # all of the combinations are fine for a reduction that has an
1973
+ # identity
1974
+ t(ok, np.add.reduce, 30, 30)
1975
+ t(ok, np.add.reduce, 0, 30)
1976
+ t(ok, np.add.reduce, 30, 0)
1977
+ t(ok, np.add.reduce, 0, 0)
1978
+ np.add.reduce([])
1979
+ np.add.reduce(np.zeros((0, 0)), axis=())
1980
+
1981
+ # OTOH, accumulate always makes sense for any combination of n and m,
1982
+ # because it maps an m-element array to an m-element array. These
1983
+ # tests are simpler because accumulate doesn't accept multiple axes.
1984
+ for uf in (np.maximum, np.add):
1985
+ uf.accumulate(np.zeros((30, 0)), axis=0)
1986
+ uf.accumulate(np.zeros((0, 30)), axis=0)
1987
+ uf.accumulate(np.zeros((30, 30)), axis=0)
1988
+ uf.accumulate(np.zeros((0, 0)), axis=0)
1989
+
1990
+ def test_safe_casting(self):
1991
+ # In old versions of numpy, in-place operations used the 'unsafe'
1992
+ # casting rules. In versions >= 1.10, 'same_kind' is the
1993
+ # default and an exception is raised instead of a warning.
1994
+ # when 'same_kind' is not satisfied.
1995
+ a = np.array([1, 2, 3], dtype=int)
1996
+ # Non-in-place addition is fine
1997
+ assert_array_equal(assert_no_warnings(np.add, a, 1.1),
1998
+ [2.1, 3.1, 4.1])
1999
+ assert_raises(TypeError, np.add, a, 1.1, out=a)
2000
+
2001
+ def add_inplace(a, b):
2002
+ a += b
2003
+
2004
+ assert_raises(TypeError, add_inplace, a, 1.1)
2005
+ # Make sure that explicitly overriding the exception is allowed:
2006
+ assert_no_warnings(np.add, a, 1.1, out=a, casting="unsafe")
2007
+ assert_array_equal(a, [2, 3, 4])
2008
+
2009
+ def test_ufunc_custom_out(self):
2010
+ # Test ufunc with built in input types and custom output type
2011
+
2012
+ a = np.array([0, 1, 2], dtype='i8')
2013
+ b = np.array([0, 1, 2], dtype='i8')
2014
+ c = np.empty(3, dtype=_rational_tests.rational)
2015
+
2016
+ # Output must be specified so numpy knows what
2017
+ # ufunc signature to look for
2018
+ result = _rational_tests.test_add(a, b, c)
2019
+ target = np.array([0, 2, 4], dtype=_rational_tests.rational)
2020
+ assert_equal(result, target)
2021
+
2022
+ # The new resolution means that we can (usually) find custom loops
2023
+ # as long as they match exactly:
2024
+ result = _rational_tests.test_add(a, b)
2025
+ assert_equal(result, target)
2026
+
2027
+ # This works even more generally, so long the default common-dtype
2028
+ # promoter works out:
2029
+ result = _rational_tests.test_add(a, b.astype(np.uint16), out=c)
2030
+ assert_equal(result, target)
2031
+
2032
+ # This scalar path used to go into legacy promotion, but doesn't now:
2033
+ result = _rational_tests.test_add(a, np.uint16(2))
2034
+ target = np.array([2, 3, 4], dtype=_rational_tests.rational)
2035
+ assert_equal(result, target)
2036
+
2037
+ def test_operand_flags(self):
2038
+ a = np.arange(16, dtype=int).reshape(4, 4)
2039
+ b = np.arange(9, dtype=int).reshape(3, 3)
2040
+ opflag_tests.inplace_add(a[:-1, :-1], b)
2041
+ assert_equal(a, np.array([[0, 2, 4, 3], [7, 9, 11, 7],
2042
+ [14, 16, 18, 11], [12, 13, 14, 15]]))
2043
+
2044
+ a = np.array(0)
2045
+ opflag_tests.inplace_add(a, 3)
2046
+ assert_equal(a, 3)
2047
+ opflag_tests.inplace_add(a, [3, 4])
2048
+ assert_equal(a, 10)
2049
+
2050
+ def test_struct_ufunc(self):
2051
+ import numpy._core._struct_ufunc_tests as struct_ufunc
2052
+
2053
+ a = np.array([(1, 2, 3)], dtype='u8,u8,u8')
2054
+ b = np.array([(1, 2, 3)], dtype='u8,u8,u8')
2055
+
2056
+ result = struct_ufunc.add_triplet(a, b)
2057
+ assert_equal(result, np.array([(2, 4, 6)], dtype='u8,u8,u8'))
2058
+ assert_raises(RuntimeError, struct_ufunc.register_fail)
2059
+
2060
+ def test_custom_ufunc(self):
2061
+ a = np.array(
2062
+ [_rational_tests.rational(1, 2),
2063
+ _rational_tests.rational(1, 3),
2064
+ _rational_tests.rational(1, 4)],
2065
+ dtype=_rational_tests.rational)
2066
+ b = np.array(
2067
+ [_rational_tests.rational(1, 2),
2068
+ _rational_tests.rational(1, 3),
2069
+ _rational_tests.rational(1, 4)],
2070
+ dtype=_rational_tests.rational)
2071
+
2072
+ result = _rational_tests.test_add_rationals(a, b)
2073
+ expected = np.array(
2074
+ [_rational_tests.rational(1),
2075
+ _rational_tests.rational(2, 3),
2076
+ _rational_tests.rational(1, 2)],
2077
+ dtype=_rational_tests.rational)
2078
+ assert_equal(result, expected)
2079
+
2080
+ def test_custom_ufunc_forced_sig(self):
2081
+ # gh-9351 - looking for a non-first userloop would previously hang
2082
+ with assert_raises(TypeError):
2083
+ np.multiply(_rational_tests.rational(1), 1,
2084
+ signature=(_rational_tests.rational, int, None))
2085
+
2086
+ def test_custom_array_like(self):
2087
+
2088
+ class MyThing:
2089
+ __array_priority__ = 1000
2090
+
2091
+ rmul_count = 0
2092
+ getitem_count = 0
2093
+
2094
+ def __init__(self, shape):
2095
+ self.shape = shape
2096
+
2097
+ def __len__(self):
2098
+ return self.shape[0]
2099
+
2100
+ def __getitem__(self, i):
2101
+ MyThing.getitem_count += 1
2102
+ if not isinstance(i, tuple):
2103
+ i = (i,)
2104
+ if len(i) > self.ndim:
2105
+ raise IndexError("boo")
2106
+
2107
+ return MyThing(self.shape[len(i):])
2108
+
2109
+ def __rmul__(self, other):
2110
+ MyThing.rmul_count += 1
2111
+ return self
2112
+
2113
+ np.float64(5) * MyThing((3, 3))
2114
+ assert_(MyThing.rmul_count == 1, MyThing.rmul_count)
2115
+ assert_(MyThing.getitem_count <= 2, MyThing.getitem_count)
2116
+
2117
+ def test_array_wrap_array_priority(self):
2118
+ class ArrayPriorityBase(np.ndarray):
2119
+ @classmethod
2120
+ def __array_wrap__(cls, array, context=None, return_scalar=False):
2121
+ return cls
2122
+
2123
+ class ArrayPriorityMinus0(ArrayPriorityBase):
2124
+ __array_priority__ = 0
2125
+
2126
+ class ArrayPriorityMinus1000(ArrayPriorityBase):
2127
+ __array_priority__ = -1000
2128
+
2129
+ class ArrayPriorityMinus1000b(ArrayPriorityBase):
2130
+ __array_priority__ = -1000
2131
+
2132
+ class ArrayPriorityMinus2000(ArrayPriorityBase):
2133
+ __array_priority__ = -2000
2134
+
2135
+ x = np.ones(2).view(ArrayPriorityMinus1000)
2136
+ xb = np.ones(2).view(ArrayPriorityMinus1000b)
2137
+ y = np.ones(2).view(ArrayPriorityMinus2000)
2138
+
2139
+ assert np.add(x, y) is ArrayPriorityMinus1000
2140
+ assert np.add(y, x) is ArrayPriorityMinus1000
2141
+ assert np.add(x, xb) is ArrayPriorityMinus1000
2142
+ assert np.add(xb, x) is ArrayPriorityMinus1000b
2143
+ y_minus0 = np.zeros(2).view(ArrayPriorityMinus0)
2144
+ assert np.add(np.zeros(2), y_minus0) is ArrayPriorityMinus0
2145
+ assert type(np.add(xb, x, np.zeros(2))) is np.ndarray
2146
+
2147
+ @pytest.mark.parametrize("a", (
2148
+ np.arange(10, dtype=int),
2149
+ np.arange(10, dtype=_rational_tests.rational),
2150
+ ))
2151
+ def test_ufunc_at_basic(self, a):
2152
+
2153
+ aa = a.copy()
2154
+ np.add.at(aa, [2, 5, 2], 1)
2155
+ assert_equal(aa, [0, 1, 4, 3, 4, 6, 6, 7, 8, 9])
2156
+
2157
+ with pytest.raises(ValueError):
2158
+ # missing second operand
2159
+ np.add.at(aa, [2, 5, 3])
2160
+
2161
+ aa = a.copy()
2162
+ np.negative.at(aa, [2, 5, 3])
2163
+ assert_equal(aa, [0, 1, -2, -3, 4, -5, 6, 7, 8, 9])
2164
+
2165
+ aa = a.copy()
2166
+ b = np.array([100, 100, 100])
2167
+ np.add.at(aa, [2, 5, 2], b)
2168
+ assert_equal(aa, [0, 1, 202, 3, 4, 105, 6, 7, 8, 9])
2169
+
2170
+ with pytest.raises(ValueError):
2171
+ # extraneous second operand
2172
+ np.negative.at(a, [2, 5, 3], [1, 2, 3])
2173
+
2174
+ with pytest.raises(ValueError):
2175
+ # second operand cannot be converted to an array
2176
+ np.add.at(a, [2, 5, 3], [[1, 2], 1])
2177
+
2178
+ # ufuncs with indexed loops for performance in ufunc.at
2179
+ indexed_ufuncs = [np.add, np.subtract, np.multiply, np.floor_divide,
2180
+ np.maximum, np.minimum, np.fmax, np.fmin]
2181
+
2182
+ @pytest.mark.parametrize(
2183
+ "typecode", np.typecodes['AllInteger'] + np.typecodes['Float'])
2184
+ @pytest.mark.parametrize("ufunc", indexed_ufuncs)
2185
+ def test_ufunc_at_inner_loops(self, typecode, ufunc):
2186
+ if ufunc is np.divide and typecode in np.typecodes['AllInteger']:
2187
+ # Avoid divide-by-zero and inf for integer divide
2188
+ a = np.ones(100, dtype=typecode)
2189
+ indx = np.random.randint(100, size=30, dtype=np.intp)
2190
+ vals = np.arange(1, 31, dtype=typecode)
2191
+ else:
2192
+ a = np.ones(1000, dtype=typecode)
2193
+ indx = np.random.randint(1000, size=3000, dtype=np.intp)
2194
+ vals = np.arange(3000, dtype=typecode)
2195
+ atag = a.copy()
2196
+ # Do the calculation twice and compare the answers
2197
+ with warnings.catch_warnings(record=True) as w_at:
2198
+ warnings.simplefilter('always')
2199
+ ufunc.at(a, indx, vals)
2200
+ with warnings.catch_warnings(record=True) as w_loop:
2201
+ warnings.simplefilter('always')
2202
+ for i, v in zip(indx, vals):
2203
+ # Make sure all the work happens inside the ufunc
2204
+ # in order to duplicate error/warning handling
2205
+ ufunc(atag[i], v, out=atag[i:i + 1], casting="unsafe")
2206
+ assert_equal(atag, a)
2207
+ # If w_loop warned, make sure w_at warned as well
2208
+ if len(w_loop) > 0:
2209
+ #
2210
+ assert len(w_at) > 0
2211
+ assert w_at[0].category == w_loop[0].category
2212
+ assert str(w_at[0].message)[:10] == str(w_loop[0].message)[:10]
2213
+
2214
+ @pytest.mark.parametrize("typecode", np.typecodes['Complex'])
2215
+ @pytest.mark.parametrize("ufunc", [np.add, np.subtract, np.multiply])
2216
+ def test_ufunc_at_inner_loops_complex(self, typecode, ufunc):
2217
+ a = np.ones(10, dtype=typecode)
2218
+ indx = np.concatenate([np.ones(6, dtype=np.intp),
2219
+ np.full(18, 4, dtype=np.intp)])
2220
+ value = a.dtype.type(1j)
2221
+ ufunc.at(a, indx, value)
2222
+ expected = np.ones_like(a)
2223
+ if ufunc is np.multiply:
2224
+ expected[1] = expected[4] = -1
2225
+ else:
2226
+ expected[1] += 6 * (value if ufunc is np.add else -value)
2227
+ expected[4] += 18 * (value if ufunc is np.add else -value)
2228
+
2229
+ assert_array_equal(a, expected)
2230
+
2231
+ def test_ufunc_at_ellipsis(self):
2232
+ # Make sure the indexed loop check does not choke on iters
2233
+ # with subspaces
2234
+ arr = np.zeros(5)
2235
+ np.add.at(arr, slice(None), np.ones(5))
2236
+ assert_array_equal(arr, np.ones(5))
2237
+
2238
+ def test_ufunc_at_negative(self):
2239
+ arr = np.ones(5, dtype=np.int32)
2240
+ indx = np.arange(5)
2241
+ umt.indexed_negative.at(arr, indx)
2242
+ # If it is [-1, -1, -1, -100, 0] then the regular strided loop was used
2243
+ assert np.all(arr == [-1, -1, -1, -200, -1])
2244
+
2245
+ def test_ufunc_at_large(self):
2246
+ # issue gh-23457
2247
+ indices = np.zeros(8195, dtype=np.int16)
2248
+ b = np.zeros(8195, dtype=float)
2249
+ b[0] = 10
2250
+ b[1] = 5
2251
+ b[8192:] = 100
2252
+ a = np.zeros(1, dtype=float)
2253
+ np.add.at(a, indices, b)
2254
+ assert a[0] == b.sum()
2255
+
2256
+ def test_cast_index_fastpath(self):
2257
+ arr = np.zeros(10)
2258
+ values = np.ones(100000)
2259
+ # index must be cast, which may be buffered in chunks:
2260
+ index = np.zeros(len(values), dtype=np.uint8)
2261
+ np.add.at(arr, index, values)
2262
+ assert arr[0] == len(values)
2263
+
2264
+ @pytest.mark.parametrize("value", [
2265
+ np.ones(1), np.ones(()), np.float64(1.), 1.])
2266
+ def test_ufunc_at_scalar_value_fastpath(self, value):
2267
+ arr = np.zeros(1000)
2268
+ # index must be cast, which may be buffered in chunks:
2269
+ index = np.repeat(np.arange(1000), 2)
2270
+ np.add.at(arr, index, value)
2271
+ assert_array_equal(arr, np.full_like(arr, 2 * value))
2272
+
2273
+ def test_ufunc_at_multiD(self):
2274
+ a = np.arange(9).reshape(3, 3)
2275
+ b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
2276
+ np.add.at(a, (slice(None), [1, 2, 1]), b)
2277
+ assert_equal(a, [[0, 201, 102], [3, 404, 205], [6, 607, 308]])
2278
+
2279
+ a = np.arange(27).reshape(3, 3, 3)
2280
+ b = np.array([100, 200, 300])
2281
+ np.add.at(a, (slice(None), slice(None), [1, 2, 1]), b)
2282
+ assert_equal(a,
2283
+ [[[0, 401, 202],
2284
+ [3, 404, 205],
2285
+ [6, 407, 208]],
2286
+
2287
+ [[9, 410, 211],
2288
+ [12, 413, 214],
2289
+ [15, 416, 217]],
2290
+
2291
+ [[18, 419, 220],
2292
+ [21, 422, 223],
2293
+ [24, 425, 226]]])
2294
+
2295
+ a = np.arange(9).reshape(3, 3)
2296
+ b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
2297
+ np.add.at(a, ([1, 2, 1], slice(None)), b)
2298
+ assert_equal(a, [[0, 1, 2], [403, 404, 405], [206, 207, 208]])
2299
+
2300
+ a = np.arange(27).reshape(3, 3, 3)
2301
+ b = np.array([100, 200, 300])
2302
+ np.add.at(a, (slice(None), [1, 2, 1], slice(None)), b)
2303
+ assert_equal(a,
2304
+ [[[0, 1, 2],
2305
+ [203, 404, 605],
2306
+ [106, 207, 308]],
2307
+
2308
+ [[9, 10, 11],
2309
+ [212, 413, 614],
2310
+ [115, 216, 317]],
2311
+
2312
+ [[18, 19, 20],
2313
+ [221, 422, 623],
2314
+ [124, 225, 326]]])
2315
+
2316
+ a = np.arange(9).reshape(3, 3)
2317
+ b = np.array([100, 200, 300])
2318
+ np.add.at(a, (0, [1, 2, 1]), b)
2319
+ assert_equal(a, [[0, 401, 202], [3, 4, 5], [6, 7, 8]])
2320
+
2321
+ a = np.arange(27).reshape(3, 3, 3)
2322
+ b = np.array([100, 200, 300])
2323
+ np.add.at(a, ([1, 2, 1], 0, slice(None)), b)
2324
+ assert_equal(a,
2325
+ [[[0, 1, 2],
2326
+ [3, 4, 5],
2327
+ [6, 7, 8]],
2328
+
2329
+ [[209, 410, 611],
2330
+ [12, 13, 14],
2331
+ [15, 16, 17]],
2332
+
2333
+ [[118, 219, 320],
2334
+ [21, 22, 23],
2335
+ [24, 25, 26]]])
2336
+
2337
+ a = np.arange(27).reshape(3, 3, 3)
2338
+ b = np.array([100, 200, 300])
2339
+ np.add.at(a, (slice(None), slice(None), slice(None)), b)
2340
+ assert_equal(a,
2341
+ [[[100, 201, 302],
2342
+ [103, 204, 305],
2343
+ [106, 207, 308]],
2344
+
2345
+ [[109, 210, 311],
2346
+ [112, 213, 314],
2347
+ [115, 216, 317]],
2348
+
2349
+ [[118, 219, 320],
2350
+ [121, 222, 323],
2351
+ [124, 225, 326]]])
2352
+
2353
+ def test_ufunc_at_0D(self):
2354
+ a = np.array(0)
2355
+ np.add.at(a, (), 1)
2356
+ assert_equal(a, 1)
2357
+
2358
+ assert_raises(IndexError, np.add.at, a, 0, 1)
2359
+ assert_raises(IndexError, np.add.at, a, [], 1)
2360
+
2361
+ def test_ufunc_at_dtypes(self):
2362
+ # Test mixed dtypes
2363
+ a = np.arange(10)
2364
+ np.power.at(a, [1, 2, 3, 2], 3.5)
2365
+ assert_equal(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9]))
2366
+
2367
+ def test_ufunc_at_boolean(self):
2368
+ # Test boolean indexing and boolean ufuncs
2369
+ a = np.arange(10)
2370
+ index = a % 2 == 0
2371
+ np.equal.at(a, index, [0, 2, 4, 6, 8])
2372
+ assert_equal(a, [1, 1, 1, 3, 1, 5, 1, 7, 1, 9])
2373
+
2374
+ # Test unary operator
2375
+ a = np.arange(10, dtype='u4')
2376
+ np.invert.at(a, [2, 5, 2])
2377
+ assert_equal(a, [0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, 7, 8, 9])
2378
+
2379
+ def test_ufunc_at_advanced(self):
2380
+ # Test empty subspace
2381
+ orig = np.arange(4)
2382
+ a = orig[:, None][:, 0:0]
2383
+ np.add.at(a, [0, 1], 3)
2384
+ assert_array_equal(orig, np.arange(4))
2385
+
2386
+ # Test with swapped byte order
2387
+ index = np.array([1, 2, 1], np.dtype('i').newbyteorder())
2388
+ values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder())
2389
+ np.add.at(values, index, 3)
2390
+ assert_array_equal(values, [1, 8, 6, 4])
2391
+
2392
+ # Test exception thrown
2393
+ values = np.array(['a', 1], dtype=object)
2394
+ assert_raises(TypeError, np.add.at, values, [0, 1], 1)
2395
+ assert_array_equal(values, np.array(['a', 1], dtype=object))
2396
+
2397
+ # Test multiple output ufuncs raise error, gh-5665
2398
+ assert_raises(ValueError, np.modf.at, np.arange(10), [1])
2399
+
2400
+ # Test maximum
2401
+ a = np.array([1, 2, 3])
2402
+ np.maximum.at(a, [0], 0)
2403
+ assert_equal(a, np.array([1, 2, 3]))
2404
+
2405
+ @pytest.mark.parametrize("dtype",
2406
+ np.typecodes['AllInteger'] + np.typecodes['Float'])
2407
+ @pytest.mark.parametrize("ufunc",
2408
+ [np.add, np.subtract, np.divide, np.minimum, np.maximum])
2409
+ def test_at_negative_indexes(self, dtype, ufunc):
2410
+ a = np.arange(0, 10).astype(dtype)
2411
+ indxs = np.array([-1, 1, -1, 2]).astype(np.intp)
2412
+ vals = np.array([1, 5, 2, 10], dtype=a.dtype)
2413
+
2414
+ expected = a.copy()
2415
+ for i, v in zip(indxs, vals):
2416
+ expected[i] = ufunc(expected[i], v)
2417
+
2418
+ ufunc.at(a, indxs, vals)
2419
+ assert_array_equal(a, expected)
2420
+ assert np.all(indxs == [-1, 1, -1, 2])
2421
+
2422
+ def test_at_not_none_signature(self):
2423
+ # Test ufuncs with non-trivial signature raise a TypeError
2424
+ a = np.ones((2, 2, 2))
2425
+ b = np.ones((1, 2, 2))
2426
+ assert_raises(TypeError, np.matmul.at, a, [0], b)
2427
+
2428
+ a = np.array([[[1, 2], [3, 4]]])
2429
+ assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0])
2430
+
2431
+ def test_at_no_loop_for_op(self):
2432
+ # str dtype does not have a ufunc loop for np.add
2433
+ arr = np.ones(10, dtype=str)
2434
+ with pytest.raises(np._core._exceptions._UFuncNoLoopError):
2435
+ np.add.at(arr, [0, 1], [0, 1])
2436
+
2437
+ def test_at_output_casting(self):
2438
+ arr = np.array([-1])
2439
+ np.equal.at(arr, [0], [0])
2440
+ assert arr[0] == 0
2441
+
2442
+ def test_at_broadcast_failure(self):
2443
+ arr = np.arange(5)
2444
+ with pytest.raises(ValueError):
2445
+ np.add.at(arr, [0, 1], [1, 2, 3])
2446
+
2447
+ def test_reduce_arguments(self):
2448
+ f = np.add.reduce
2449
+ d = np.ones((5, 2), dtype=int)
2450
+ o = np.ones((2,), dtype=d.dtype)
2451
+ r = o * 5
2452
+ assert_equal(f(d), r)
2453
+ # a, axis=0, dtype=None, out=None, keepdims=False
2454
+ assert_equal(f(d, axis=0), r)
2455
+ assert_equal(f(d, 0), r)
2456
+ assert_equal(f(d, 0, dtype=None), r)
2457
+ assert_equal(f(d, 0, dtype='i'), r)
2458
+ assert_equal(f(d, 0, 'i'), r)
2459
+ assert_equal(f(d, 0, None), r)
2460
+ assert_equal(f(d, 0, None, out=None), r)
2461
+ assert_equal(f(d, 0, None, out=o), r)
2462
+ assert_equal(f(d, 0, None, o), r)
2463
+ assert_equal(f(d, 0, None, None), r)
2464
+ assert_equal(f(d, 0, None, None, keepdims=False), r)
2465
+ assert_equal(f(d, 0, None, None, True), r.reshape((1,) + r.shape))
2466
+ assert_equal(f(d, 0, None, None, False, 0), r)
2467
+ assert_equal(f(d, 0, None, None, False, initial=0), r)
2468
+ assert_equal(f(d, 0, None, None, False, 0, True), r)
2469
+ assert_equal(f(d, 0, None, None, False, 0, where=True), r)
2470
+ # multiple keywords
2471
+ assert_equal(f(d, axis=0, dtype=None, out=None, keepdims=False), r)
2472
+ assert_equal(f(d, 0, dtype=None, out=None, keepdims=False), r)
2473
+ assert_equal(f(d, 0, None, out=None, keepdims=False), r)
2474
+ assert_equal(f(d, 0, None, out=None, keepdims=False, initial=0,
2475
+ where=True), r)
2476
+
2477
+ # too little
2478
+ assert_raises(TypeError, f)
2479
+ # too much
2480
+ assert_raises(TypeError, f, d, 0, None, None, False, 0, True, 1)
2481
+ # invalid axis
2482
+ assert_raises(TypeError, f, d, "invalid")
2483
+ assert_raises(TypeError, f, d, axis="invalid")
2484
+ assert_raises(TypeError, f, d, axis="invalid", dtype=None,
2485
+ keepdims=True)
2486
+ # invalid dtype
2487
+ assert_raises(TypeError, f, d, 0, "invalid")
2488
+ assert_raises(TypeError, f, d, dtype="invalid")
2489
+ assert_raises(TypeError, f, d, dtype="invalid", out=None)
2490
+ # invalid out
2491
+ assert_raises(TypeError, f, d, 0, None, "invalid")
2492
+ assert_raises(TypeError, f, d, out="invalid")
2493
+ assert_raises(TypeError, f, d, out="invalid", dtype=None)
2494
+ # keepdims boolean, no invalid value
2495
+ # assert_raises(TypeError, f, d, 0, None, None, "invalid")
2496
+ # assert_raises(TypeError, f, d, keepdims="invalid", axis=0, dtype=None)
2497
+ # invalid mix
2498
+ assert_raises(TypeError, f, d, 0, keepdims="invalid", dtype="invalid",
2499
+ out=None)
2500
+
2501
+ # invalid keyword
2502
+ assert_raises(TypeError, f, d, axis=0, dtype=None, invalid=0)
2503
+ assert_raises(TypeError, f, d, invalid=0)
2504
+ assert_raises(TypeError, f, d, 0, keepdims=True, invalid="invalid",
2505
+ out=None)
2506
+ assert_raises(TypeError, f, d, axis=0, dtype=None, keepdims=True,
2507
+ out=None, invalid=0)
2508
+ assert_raises(TypeError, f, d, axis=0, dtype=None,
2509
+ out=None, invalid=0)
2510
+
2511
+ def test_structured_equal(self):
2512
+ # https://github.com/numpy/numpy/issues/4855
2513
+
2514
+ class MyA(np.ndarray):
2515
+ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
2516
+ return getattr(ufunc, method)(*(input.view(np.ndarray)
2517
+ for input in inputs), **kwargs)
2518
+ a = np.arange(12.).reshape(4, 3)
2519
+ ra = a.view(dtype=('f8,f8,f8')).squeeze()
2520
+ mra = ra.view(MyA)
2521
+
2522
+ target = np.array([True, False, False, False], dtype=bool)
2523
+ assert_equal(np.all(target == (mra == ra[0])), True)
2524
+
2525
+ def test_scalar_equal(self):
2526
+ # Scalar comparisons should always work, without deprecation warnings.
2527
+ # even when the ufunc fails.
2528
+ a = np.array(0.)
2529
+ b = np.array('a')
2530
+ assert_(a != b)
2531
+ assert_(b != a)
2532
+ assert_(not (a == b))
2533
+ assert_(not (b == a))
2534
+
2535
+ def test_NotImplemented_not_returned(self):
2536
+ # See gh-5964 and gh-2091. Some of these functions are not operator
2537
+ # related and were fixed for other reasons in the past.
2538
+ binary_funcs = [
2539
+ np.power, np.add, np.subtract, np.multiply, np.divide,
2540
+ np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
2541
+ np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
2542
+ np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
2543
+ np.maximum, np.minimum, np.mod,
2544
+ np.greater, np.greater_equal, np.less, np.less_equal,
2545
+ np.equal, np.not_equal]
2546
+
2547
+ a = np.array('1')
2548
+ b = 1
2549
+ c = np.array([1., 2.])
2550
+ for f in binary_funcs:
2551
+ assert_raises(TypeError, f, a, b)
2552
+ assert_raises(TypeError, f, c, a)
2553
+
2554
+ @pytest.mark.parametrize("ufunc",
2555
+ [np.logical_and, np.logical_or]) # logical_xor object loop is bad
2556
+ @pytest.mark.parametrize("signature",
2557
+ [(None, None, object), (object, None, None),
2558
+ (None, object, None)])
2559
+ def test_logical_ufuncs_object_signatures(self, ufunc, signature):
2560
+ a = np.array([True, None, False], dtype=object)
2561
+ res = ufunc(a, a, signature=signature)
2562
+ assert res.dtype == object
2563
+
2564
+ @pytest.mark.parametrize("ufunc",
2565
+ [np.logical_and, np.logical_or, np.logical_xor])
2566
+ @pytest.mark.parametrize("signature",
2567
+ [(bool, None, object), (object, None, bool),
2568
+ (None, object, bool)])
2569
+ def test_logical_ufuncs_mixed_object_signatures(self, ufunc, signature):
2570
+ # Most mixed signatures fail (except those with bool out, e.g. `OO->?`)
2571
+ a = np.array([True, None, False])
2572
+ with pytest.raises(TypeError):
2573
+ ufunc(a, a, signature=signature)
2574
+
2575
+ @pytest.mark.parametrize("ufunc",
2576
+ [np.logical_and, np.logical_or, np.logical_xor])
2577
+ def test_logical_ufuncs_support_anything(self, ufunc):
2578
+ # The logical ufuncs support even input that can't be promoted:
2579
+ a = np.array(b'1', dtype="V3")
2580
+ c = np.array([1., 2.])
2581
+ assert_array_equal(ufunc(a, c), ufunc([True, True], True))
2582
+ assert ufunc.reduce(a) == True
2583
+ # check that the output has no effect:
2584
+ out = np.zeros(2, dtype=np.int32)
2585
+ expected = ufunc([True, True], True).astype(out.dtype)
2586
+ assert_array_equal(ufunc(a, c, out=out), expected)
2587
+ out = np.zeros((), dtype=np.int32)
2588
+ assert ufunc.reduce(a, out=out) == True
2589
+ # Last check, test reduction when out and a match (the complexity here
2590
+ # is that the "i,i->?" may seem right, but should not match.
2591
+ a = np.array([3], dtype="i")
2592
+ out = np.zeros((), dtype=a.dtype)
2593
+ assert ufunc.reduce(a, out=out) == 1
2594
+
2595
+ @pytest.mark.parametrize("ufunc",
2596
+ [np.logical_and, np.logical_or, np.logical_xor])
2597
+ @pytest.mark.parametrize("dtype", ["S", "U"])
2598
+ @pytest.mark.parametrize("values", [["1", "hi", "0"], ["", ""]])
2599
+ def test_logical_ufuncs_supports_string(self, ufunc, dtype, values):
2600
+ # note that values are either all true or all false
2601
+ arr = np.array(values, dtype=dtype)
2602
+ obj_arr = np.array(values, dtype=object)
2603
+ res = ufunc(arr, arr)
2604
+ expected = ufunc(obj_arr, obj_arr, dtype=bool)
2605
+
2606
+ assert_array_equal(res, expected)
2607
+
2608
+ res = ufunc.reduce(arr)
2609
+ expected = ufunc.reduce(obj_arr, dtype=bool)
2610
+ assert_array_equal(res, expected)
2611
+
2612
+ @pytest.mark.parametrize("ufunc",
2613
+ [np.logical_and, np.logical_or, np.logical_xor])
2614
+ def test_logical_ufuncs_out_cast_check(self, ufunc):
2615
+ a = np.array('1')
2616
+ c = np.array([1., 2.])
2617
+ out = a.copy()
2618
+ with pytest.raises(TypeError):
2619
+ # It would be safe, but not equiv casting:
2620
+ ufunc(a, c, out=out, casting="equiv")
2621
+
2622
+ def test_reducelike_byteorder_resolution(self):
2623
+ # See gh-20699, byte-order changes need some extra care in the type
2624
+ # resolution to make the following succeed:
2625
+ arr_be = np.arange(10, dtype=">i8")
2626
+ arr_le = np.arange(10, dtype="<i8")
2627
+
2628
+ assert np.add.reduce(arr_be) == np.add.reduce(arr_le)
2629
+ assert_array_equal(np.add.accumulate(arr_be), np.add.accumulate(arr_le))
2630
+ assert_array_equal(
2631
+ np.add.reduceat(arr_be, [1]), np.add.reduceat(arr_le, [1]))
2632
+
2633
+ def test_reducelike_out_promotes(self):
2634
+ # Check that the out argument to reductions is considered for
2635
+ # promotion. See also gh-20455.
2636
+ # Note that these paths could prefer `initial=` in the future and
2637
+ # do not up-cast to the default integer for add and prod
2638
+ arr = np.ones(1000, dtype=np.uint8)
2639
+ out = np.zeros((), dtype=np.uint16)
2640
+ assert np.add.reduce(arr, out=out) == 1000
2641
+ arr[:10] = 2
2642
+ assert np.multiply.reduce(arr, out=out) == 2**10
2643
+
2644
+ # For legacy dtypes, the signature currently has to be forced if `out=`
2645
+ # is passed. The two paths below should differ, without `dtype=` the
2646
+ # expected result should be: `np.prod(arr.astype("f8")).astype("f4")`!
2647
+ arr = np.full(5, 2**25 - 1, dtype=np.int64)
2648
+
2649
+ # float32 and int64 promote to float64:
2650
+ res = np.zeros((), dtype=np.float32)
2651
+ # If `dtype=` is passed, the calculation is forced to float32:
2652
+ single_res = np.zeros((), dtype=np.float32)
2653
+ np.multiply.reduce(arr, out=single_res, dtype=np.float32)
2654
+ assert single_res != res
2655
+
2656
+ def test_reducelike_output_needs_identical_cast(self):
2657
+ # Checks the case where a simple byte-swap works, mainly tests that
2658
+ # this is not rejected directly.
2659
+ # (interesting because we require descriptor identity in reducelikes).
2660
+ arr = np.ones(20, dtype="f8")
2661
+ out = np.empty((), dtype=arr.dtype.newbyteorder())
2662
+ expected = np.add.reduce(arr)
2663
+ np.add.reduce(arr, out=out)
2664
+ assert_array_equal(expected, out)
2665
+ # Check reduceat:
2666
+ out = np.empty(2, dtype=arr.dtype.newbyteorder())
2667
+ expected = np.add.reduceat(arr, [0, 1])
2668
+ np.add.reduceat(arr, [0, 1], out=out)
2669
+ assert_array_equal(expected, out)
2670
+ # And accumulate:
2671
+ out = np.empty(arr.shape, dtype=arr.dtype.newbyteorder())
2672
+ expected = np.add.accumulate(arr)
2673
+ np.add.accumulate(arr, out=out)
2674
+ assert_array_equal(expected, out)
2675
+
2676
+ def test_reduce_noncontig_output(self):
2677
+ # Check that reduction deals with non-contiguous output arrays
2678
+ # appropriately.
2679
+ #
2680
+ # gh-8036
2681
+
2682
+ x = np.arange(7 * 13 * 8, dtype=np.int16).reshape(7, 13, 8)
2683
+ x = x[4:6, 1:11:6, 1:5].transpose(1, 2, 0)
2684
+ y_base = np.arange(4 * 4, dtype=np.int16).reshape(4, 4)
2685
+ y = y_base[::2, :]
2686
+
2687
+ y_base_copy = y_base.copy()
2688
+
2689
+ r0 = np.add.reduce(x, out=y.copy(), axis=2)
2690
+ r1 = np.add.reduce(x, out=y, axis=2)
2691
+
2692
+ # The results should match, and y_base shouldn't get clobbered
2693
+ assert_equal(r0, r1)
2694
+ assert_equal(y_base[1, :], y_base_copy[1, :])
2695
+ assert_equal(y_base[3, :], y_base_copy[3, :])
2696
+
2697
+ @pytest.mark.parametrize("with_cast", [True, False])
2698
+ def test_reduceat_and_accumulate_out_shape_mismatch(self, with_cast):
2699
+ # Should raise an error mentioning "shape" or "size"
2700
+ arr = np.arange(5)
2701
+ out = np.arange(3) # definitely wrong shape
2702
+ if with_cast:
2703
+ # If a cast is necessary on the output, we can be sure to use
2704
+ # the generic NpyIter (non-fast) path.
2705
+ out = out.astype(np.float64)
2706
+
2707
+ with pytest.raises(ValueError, match="(shape|size)"):
2708
+ np.add.reduceat(arr, [0, 3], out=out)
2709
+
2710
+ with pytest.raises(ValueError, match="(shape|size)"):
2711
+ np.add.accumulate(arr, out=out)
2712
+
2713
+ @pytest.mark.parametrize('out_shape',
2714
+ [(), (1,), (3,), (1, 1), (1, 3), (4, 3)])
2715
+ @pytest.mark.parametrize('keepdims', [True, False])
2716
+ @pytest.mark.parametrize('f_reduce', [np.add.reduce, np.minimum.reduce])
2717
+ def test_reduce_wrong_dimension_output(self, f_reduce, keepdims, out_shape):
2718
+ # Test that we're not incorrectly broadcasting dimensions.
2719
+ # See gh-15144 (failed for np.add.reduce previously).
2720
+ a = np.arange(12.).reshape(4, 3)
2721
+ out = np.empty(out_shape, a.dtype)
2722
+
2723
+ correct_out = f_reduce(a, axis=0, keepdims=keepdims)
2724
+ if out_shape != correct_out.shape:
2725
+ with assert_raises(ValueError):
2726
+ f_reduce(a, axis=0, out=out, keepdims=keepdims)
2727
+ else:
2728
+ check = f_reduce(a, axis=0, out=out, keepdims=keepdims)
2729
+ assert_(check is out)
2730
+ assert_array_equal(check, correct_out)
2731
+
2732
+ def test_reduce_output_does_not_broadcast_input(self):
2733
+ # Test that the output shape cannot broadcast an input dimension
2734
+ # (it never can add dimensions, but it might expand an existing one)
2735
+ a = np.ones((1, 10))
2736
+ out_correct = (np.empty((1, 1)))
2737
+ out_incorrect = np.empty((3, 1))
2738
+ np.add.reduce(a, axis=-1, out=out_correct, keepdims=True)
2739
+ np.add.reduce(a, axis=-1, out=out_correct[:, 0], keepdims=False)
2740
+ with assert_raises(ValueError):
2741
+ np.add.reduce(a, axis=-1, out=out_incorrect, keepdims=True)
2742
+ with assert_raises(ValueError):
2743
+ np.add.reduce(a, axis=-1, out=out_incorrect[:, 0], keepdims=False)
2744
+
2745
+ def test_reduce_output_subclass_ok(self):
2746
+ class MyArr(np.ndarray):
2747
+ pass
2748
+
2749
+ out = np.empty(())
2750
+ np.add.reduce(np.ones(5), out=out) # no subclass, all fine
2751
+ out = out.view(MyArr)
2752
+ assert np.add.reduce(np.ones(5), out=out) is out
2753
+ assert type(np.add.reduce(out)) is MyArr
2754
+
2755
+ def test_no_doc_string(self):
2756
+ # gh-9337
2757
+ assert_('\n' not in umt.inner1d_no_doc.__doc__)
2758
+
2759
+ def test_invalid_args(self):
2760
+ # gh-7961
2761
+ exc = pytest.raises(TypeError, np.sqrt, None)
2762
+ # minimally check the exception text
2763
+ assert exc.match('loop of ufunc does not support')
2764
+
2765
+ @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
2766
+ def test_nat_is_not_finite(self, nat):
2767
+ try:
2768
+ assert not np.isfinite(nat)
2769
+ except TypeError:
2770
+ pass # ok, just not implemented
2771
+
2772
+ @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
2773
+ def test_nat_is_nan(self, nat):
2774
+ try:
2775
+ assert np.isnan(nat)
2776
+ except TypeError:
2777
+ pass # ok, just not implemented
2778
+
2779
+ @pytest.mark.parametrize('nat', [np.datetime64('nat'), np.timedelta64('nat')])
2780
+ def test_nat_is_not_inf(self, nat):
2781
+ try:
2782
+ assert not np.isinf(nat)
2783
+ except TypeError:
2784
+ pass # ok, just not implemented
2785
+
2786
+
2787
+ class TestGUFuncProcessCoreDims:
2788
+
2789
+ def test_conv1d_full_without_out(self):
2790
+ x = np.arange(5.0)
2791
+ y = np.arange(13.0)
2792
+ w = umt.conv1d_full(x, y)
2793
+ assert_equal(w, np.convolve(x, y, mode='full'))
2794
+
2795
+ def test_conv1d_full_with_out(self):
2796
+ x = np.arange(5.0)
2797
+ y = np.arange(13.0)
2798
+ out = np.zeros(len(x) + len(y) - 1)
2799
+ umt.conv1d_full(x, y, out=out)
2800
+ assert_equal(out, np.convolve(x, y, mode='full'))
2801
+
2802
+ def test_conv1d_full_basic_broadcast(self):
2803
+ # x.shape is (3, 6)
2804
+ x = np.array([[1, 3, 0, -10, 2, 2],
2805
+ [0, -1, 2, 2, 10, 4],
2806
+ [8, 9, 10, 2, 23, 3]])
2807
+ # y.shape is (2, 1, 7)
2808
+ y = np.array([[[3, 4, 5, 20, 30, 40, 29]],
2809
+ [[5, 6, 7, 10, 11, 12, -5]]])
2810
+ # result should have shape (2, 3, 12)
2811
+ result = umt.conv1d_full(x, y)
2812
+ assert result.shape == (2, 3, 12)
2813
+ for i in range(2):
2814
+ for j in range(3):
2815
+ assert_equal(result[i, j], np.convolve(x[j], y[i, 0]))
2816
+
2817
+ def test_bad_out_shape(self):
2818
+ x = np.ones((1, 2))
2819
+ y = np.ones((2, 3))
2820
+ out = np.zeros((2, 3)) # Not the correct shape.
2821
+ with pytest.raises(ValueError, match=r'does not equal m \+ n - 1'):
2822
+ umt.conv1d_full(x, y, out=out)
2823
+
2824
+ def test_bad_input_both_inputs_length_zero(self):
2825
+ with pytest.raises(ValueError,
2826
+ match='both inputs have core dimension 0'):
2827
+ umt.conv1d_full([], [])
2828
+
2829
+
2830
+ @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np)
2831
+ if isinstance(getattr(np, x), np.ufunc)])
2832
+ def test_ufunc_types(ufunc):
2833
+ '''
2834
+ Check all ufuncs that the correct type is returned. Avoid
2835
+ object and boolean types since many operations are not defined for
2836
+ for them.
2837
+
2838
+ Choose the shape so even dot and matmul will succeed
2839
+ '''
2840
+ for typ in ufunc.types:
2841
+ # types is a list of strings like ii->i
2842
+ if 'O' in typ or '?' in typ:
2843
+ continue
2844
+ inp, out = typ.split('->')
2845
+ args = [np.ones((3, 3), t) for t in inp]
2846
+ with warnings.catch_warnings(record=True):
2847
+ warnings.filterwarnings("always")
2848
+ res = ufunc(*args)
2849
+ if isinstance(res, tuple):
2850
+ outs = tuple(out)
2851
+ assert len(res) == len(outs)
2852
+ for r, t in zip(res, outs):
2853
+ assert r.dtype == np.dtype(t)
2854
+ else:
2855
+ assert res.dtype == np.dtype(out)
2856
+
2857
+ @pytest.mark.parametrize('ufunc', [getattr(np, x) for x in dir(np)
2858
+ if isinstance(getattr(np, x), np.ufunc)])
2859
+ def test_ufunc_noncontiguous(ufunc):
2860
+ '''
2861
+ Check that contiguous and non-contiguous calls to ufuncs
2862
+ have the same results for values in range(9)
2863
+ '''
2864
+ for typ in ufunc.types:
2865
+ # types is a list of strings like ii->i
2866
+ if any(set('O?mM') & set(typ)):
2867
+ # bool, object, datetime are too irregular for this simple test
2868
+ continue
2869
+ inp, out = typ.split('->')
2870
+ args_c = [np.empty((6, 6), t) for t in inp]
2871
+ # non contiguous (2, 3 step on the two dimensions)
2872
+ args_n = [np.empty((12, 18), t)[::2, ::3] for t in inp]
2873
+ # alignment != itemsize is possible. So create an array with such
2874
+ # an odd step manually.
2875
+ args_o = []
2876
+ for t in inp:
2877
+ orig_dt = np.dtype(t)
2878
+ off_dt = f"S{orig_dt.alignment}" # offset by alignment
2879
+ dtype = np.dtype([("_", off_dt), ("t", orig_dt)], align=False)
2880
+ args_o.append(np.empty((6, 6), dtype=dtype)["t"])
2881
+ for a in args_c + args_n + args_o:
2882
+ a.flat = range(1, 37)
2883
+
2884
+ with warnings.catch_warnings(record=True):
2885
+ warnings.filterwarnings("always")
2886
+ res_c = ufunc(*args_c)
2887
+ res_n = ufunc(*args_n)
2888
+ res_o = ufunc(*args_o)
2889
+ if len(out) == 1:
2890
+ res_c = (res_c,)
2891
+ res_n = (res_n,)
2892
+ res_o = (res_o,)
2893
+ for c_ar, n_ar, o_ar in zip(res_c, res_n, res_o):
2894
+ dt = c_ar.dtype
2895
+ if np.issubdtype(dt, np.floating):
2896
+ # for floating point results allow a small fuss in comparisons
2897
+ # since different algorithms (libm vs. intrinsics) can be used
2898
+ # for different input strides
2899
+ res_eps = np.finfo(dt).eps
2900
+ tol = 3 * res_eps
2901
+ assert_allclose(res_c, res_n, atol=tol, rtol=tol)
2902
+ assert_allclose(res_c, res_o, atol=tol, rtol=tol)
2903
+ else:
2904
+ assert_equal(c_ar, n_ar)
2905
+ assert_equal(c_ar, o_ar)
2906
+
2907
+
2908
+ @pytest.mark.parametrize('ufunc', [np.sign, np.equal])
2909
+ def test_ufunc_warn_with_nan(ufunc):
2910
+ # issue gh-15127
2911
+ # test that calling certain ufuncs with a non-standard `nan` value does not
2912
+ # emit a warning
2913
+ # `b` holds a 64 bit signaling nan: the most significant bit of the
2914
+ # significand is zero.
2915
+ b = np.array([0x7ff0000000000001], 'i8').view('f8')
2916
+ assert np.isnan(b)
2917
+ if ufunc.nin == 1:
2918
+ ufunc(b)
2919
+ elif ufunc.nin == 2:
2920
+ ufunc(b, b.copy())
2921
+ else:
2922
+ raise ValueError('ufunc with more than 2 inputs')
2923
+
2924
+
2925
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2926
+ def test_ufunc_out_casterrors():
2927
+ # Tests that casting errors are correctly reported and buffers are
2928
+ # cleared.
2929
+ # The following array can be added to itself as an object array, but
2930
+ # the result cannot be cast to an integer output:
2931
+ value = 123 # relies on python cache (leak-check will still find it)
2932
+ arr = np.array([value] * int(ncu.BUFSIZE * 1.5) +
2933
+ ["string"] +
2934
+ [value] * int(1.5 * ncu.BUFSIZE), dtype=object)
2935
+ out = np.ones(len(arr), dtype=np.intp)
2936
+
2937
+ count = sys.getrefcount(value)
2938
+ with pytest.raises(ValueError):
2939
+ # Output casting failure:
2940
+ np.add(arr, arr, out=out, casting="unsafe")
2941
+
2942
+ assert count == sys.getrefcount(value)
2943
+ # output is unchanged after the error, this shows that the iteration
2944
+ # was aborted (this is not necessarily defined behaviour)
2945
+ assert out[-1] == 1
2946
+
2947
+ with pytest.raises(ValueError):
2948
+ # Input casting failure:
2949
+ np.add(arr, arr, out=out, dtype=np.intp, casting="unsafe")
2950
+
2951
+ assert count == sys.getrefcount(value)
2952
+ # output is unchanged after the error, this shows that the iteration
2953
+ # was aborted (this is not necessarily defined behaviour)
2954
+ assert out[-1] == 1
2955
+
2956
+
2957
+ @pytest.mark.parametrize("bad_offset", [0, int(ncu.BUFSIZE * 1.5)])
2958
+ def test_ufunc_input_casterrors(bad_offset):
2959
+ value = 123
2960
+ arr = np.array([value] * bad_offset +
2961
+ ["string"] +
2962
+ [value] * int(1.5 * ncu.BUFSIZE), dtype=object)
2963
+ with pytest.raises(ValueError):
2964
+ # Force cast inputs, but the buffered cast of `arr` to intp fails:
2965
+ np.add(arr, arr, dtype=np.intp, casting="unsafe")
2966
+
2967
+
2968
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
2969
+ @pytest.mark.parametrize("bad_offset", [0, int(ncu.BUFSIZE * 1.5)])
2970
+ def test_ufunc_input_floatingpoint_error(bad_offset):
2971
+ value = 123
2972
+ arr = np.array([value] * bad_offset +
2973
+ [np.nan] +
2974
+ [value] * int(1.5 * ncu.BUFSIZE))
2975
+ with np.errstate(invalid="raise"), pytest.raises(FloatingPointError):
2976
+ # Force cast inputs, but the buffered cast of `arr` to intp fails:
2977
+ np.add(arr, arr, dtype=np.intp, casting="unsafe")
2978
+
2979
+
2980
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
2981
+ @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc")
2982
+ @pytest.mark.parametrize(
2983
+ "methodname",
2984
+ ["__call__", "accumulate", "at", "outer", "reduce", "reduceat", "resolve_dtypes"],
2985
+ )
2986
+ def test_ufunc_method_signatures(methodname: str):
2987
+ method = getattr(np.ufunc, methodname)
2988
+
2989
+ try:
2990
+ _ = inspect.signature(method)
2991
+ except ValueError as e:
2992
+ pytest.fail(e.args[0])
2993
+
2994
+
2995
+ def test_trivial_loop_invalid_cast():
2996
+ # This tests the fast-path "invalid cast", see gh-19904.
2997
+ with pytest.raises(TypeError,
2998
+ match="cast ufunc 'add' input 0"):
2999
+ # the void dtype definitely cannot cast to double:
3000
+ np.add(np.array(1, "i,i"), 3, signature="dd->d")
3001
+
3002
+
3003
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
3004
+ @pytest.mark.parametrize("offset",
3005
+ [0, ncu.BUFSIZE // 2, int(1.5 * ncu.BUFSIZE)])
3006
+ def test_reduce_casterrors(offset):
3007
+ # Test reporting of casting errors in reductions, we test various
3008
+ # offsets to where the casting error will occur, since these may occur
3009
+ # at different places during the reduction procedure. For example
3010
+ # the first item may be special.
3011
+ value = 123 # relies on python cache (leak-check will still find it)
3012
+ arr = np.array([value] * offset +
3013
+ ["string"] +
3014
+ [value] * int(1.5 * ncu.BUFSIZE), dtype=object)
3015
+ out = np.array(-1, dtype=np.intp)
3016
+
3017
+ count = sys.getrefcount(value)
3018
+ with pytest.raises(ValueError, match="invalid literal"):
3019
+ # This is an unsafe cast, but we currently always allow that.
3020
+ # Note that the double loop is picked, but the cast fails.
3021
+ # `initial=None` disables the use of an identity here to test failures
3022
+ # while copying the first values path (not used when identity exists).
3023
+ np.add.reduce(arr, dtype=np.intp, out=out, initial=None)
3024
+ assert count == sys.getrefcount(value)
3025
+ # If an error occurred during casting, the operation is done at most until
3026
+ # the error occurs (the result of which would be `value * offset`) and -1
3027
+ # if the error happened immediately.
3028
+ # This does not define behaviour, the output is invalid and thus undefined
3029
+ assert out[()] < value * offset
3030
+
3031
+
3032
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
3033
+ def test_reduction_no_reference_leak():
3034
+ # Test that the generic reduction does not leak references.
3035
+ # gh-29358
3036
+ arr = np.array([1, 2, 3], dtype=np.int32)
3037
+ count = sys.getrefcount(arr)
3038
+
3039
+ np.add.reduce(arr, dtype=np.int32, initial=0)
3040
+ assert count == sys.getrefcount(arr)
3041
+
3042
+ np.add.accumulate(arr, dtype=np.int32)
3043
+ assert count == sys.getrefcount(arr)
3044
+
3045
+ np.add.reduceat(arr, [0, 1], dtype=np.int32)
3046
+ assert count == sys.getrefcount(arr)
3047
+
3048
+ # with `out=` the reference count is not changed
3049
+ out = np.empty((), dtype=np.int32)
3050
+ out_count = sys.getrefcount(out)
3051
+
3052
+ np.add.reduce(arr, dtype=np.int32, out=out, initial=0)
3053
+ assert count == sys.getrefcount(arr)
3054
+ assert out_count == sys.getrefcount(out)
3055
+
3056
+ out = np.empty(arr.shape, dtype=np.int32)
3057
+ out_count = sys.getrefcount(out)
3058
+
3059
+ np.add.accumulate(arr, dtype=np.int32, out=out)
3060
+ assert count == sys.getrefcount(arr)
3061
+ assert out_count == sys.getrefcount(out)
3062
+
3063
+ out = np.empty((2,), dtype=np.int32)
3064
+ out_count = sys.getrefcount(out)
3065
+
3066
+ np.add.reduceat(arr, [0, 1], dtype=np.int32, out=out)
3067
+ assert count == sys.getrefcount(arr)
3068
+ assert out_count == sys.getrefcount(out)
3069
+
3070
+
3071
+ def test_object_reduce_cleanup_on_failure():
3072
+ # Test cleanup, including of the initial value (manually provided or not)
3073
+ with pytest.raises(TypeError):
3074
+ np.add.reduce([1, 2, None], initial=4)
3075
+
3076
+ with pytest.raises(TypeError):
3077
+ np.add.reduce([1, 2, None])
3078
+
3079
+
3080
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
3081
+ @pytest.mark.parametrize("method",
3082
+ [np.add.accumulate, np.add.reduce,
3083
+ pytest.param(lambda x: np.add.reduceat(x, [0]), id="reduceat"),
3084
+ pytest.param(lambda x: np.log.at(x, [2]), id="at")])
3085
+ def test_ufunc_methods_floaterrors(method):
3086
+ # adding inf and -inf (or log(-inf) creates an invalid float and warns
3087
+ arr = np.array([np.inf, 0, -np.inf])
3088
+ with np.errstate(all="warn"):
3089
+ with pytest.warns(RuntimeWarning, match="invalid value"):
3090
+ method(arr)
3091
+
3092
+ arr = np.array([np.inf, 0, -np.inf])
3093
+ with np.errstate(all="raise"):
3094
+ with pytest.raises(FloatingPointError):
3095
+ method(arr)
3096
+
3097
+
3098
+ def _check_neg_zero(value):
3099
+ if value != 0.0:
3100
+ return False
3101
+ if not np.signbit(value.real):
3102
+ return False
3103
+ if value.dtype.kind == "c":
3104
+ return np.signbit(value.imag)
3105
+ return True
3106
+
3107
+ @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
3108
+ def test_addition_negative_zero(dtype):
3109
+ dtype = np.dtype(dtype)
3110
+ if dtype.kind == "c":
3111
+ neg_zero = dtype.type(complex(-0.0, -0.0))
3112
+ else:
3113
+ neg_zero = dtype.type(-0.0)
3114
+
3115
+ arr = np.array(neg_zero)
3116
+ arr2 = np.array(neg_zero)
3117
+
3118
+ assert _check_neg_zero(arr + arr2)
3119
+ # In-place ops may end up on a different path (reduce path) see gh-21211
3120
+ arr += arr2
3121
+ assert _check_neg_zero(arr)
3122
+
3123
+
3124
+ @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
3125
+ @pytest.mark.parametrize("use_initial", [True, False])
3126
+ def test_addition_reduce_negative_zero(dtype, use_initial):
3127
+ dtype = np.dtype(dtype)
3128
+ if dtype.kind == "c":
3129
+ neg_zero = dtype.type(complex(-0.0, -0.0))
3130
+ else:
3131
+ neg_zero = dtype.type(-0.0)
3132
+
3133
+ kwargs = {}
3134
+ if use_initial:
3135
+ kwargs["initial"] = neg_zero
3136
+ else:
3137
+ pytest.xfail("-0. propagation in sum currently requires initial")
3138
+
3139
+ # Test various length, in case SIMD paths or chunking play a role.
3140
+ # 150 extends beyond the pairwise blocksize; probably not important.
3141
+ for i in range(150):
3142
+ arr = np.array([neg_zero] * i, dtype=dtype)
3143
+ res = np.sum(arr, **kwargs)
3144
+ if i > 0 or use_initial:
3145
+ assert _check_neg_zero(res)
3146
+ else:
3147
+ # `sum([])` should probably be 0.0 and not -0.0 like `sum([-0.0])`
3148
+ assert not np.signbit(res.real)
3149
+ assert not np.signbit(res.imag)
3150
+
3151
+
3152
+ @pytest.mark.parametrize(["dt1", "dt2"],
3153
+ [("S", "U"), ("U", "S"), ("S", "d"), ("S", "V"), ("U", "l")])
3154
+ def test_addition_string_types(dt1, dt2):
3155
+ arr1 = np.array([1234234], dtype=dt1)
3156
+ arr2 = np.array([b"423"], dtype=dt2)
3157
+ with pytest.raises(np._core._exceptions.UFuncTypeError) as exc:
3158
+ np.add(arr1, arr2)
3159
+
3160
+
3161
+ @pytest.mark.parametrize("order1,order2",
3162
+ [(">", ">"), ("<", "<"), (">", "<"), ("<", ">")])
3163
+ def test_addition_unicode_inverse_byte_order(order1, order2):
3164
+ element = 'abcd'
3165
+ arr1 = np.array([element], dtype=f"{order1}U4")
3166
+ arr2 = np.array([element], dtype=f"{order2}U4")
3167
+ result = arr1 + arr2
3168
+ assert result == 2 * element
3169
+
3170
+
3171
+ @pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64])
3172
+ def test_find_non_long_args(dtype):
3173
+ element = 'abcd'
3174
+ start = dtype(0)
3175
+ end = dtype(len(element))
3176
+ arr = np.array([element])
3177
+ result = np._core.umath.find(arr, "a", start, end)
3178
+ assert result.dtype == np.dtype("intp")
3179
+ assert result == 0
3180
+
3181
+
3182
+ def test_find_access_past_buffer():
3183
+ # This checks that no read past the string buffer occurs in
3184
+ # string_fastsearch.h. The buffer class makes sure this is checked.
3185
+ # To see it in action, you can remove the checks in the buffer and
3186
+ # this test will produce an 'Invalid read' if run under valgrind.
3187
+ arr = np.array([b'abcd', b'ebcd'])
3188
+ result = np._core.umath.find(arr, b'cde', 0, np.iinfo(np.int64).max)
3189
+ assert np.all(result == -1)
3190
+
3191
+
3192
+ class TestLowlevelAPIAccess:
3193
+ def test_resolve_dtypes_basic(self):
3194
+ # Basic test for dtype resolution:
3195
+ i4 = np.dtype("i4")
3196
+ f4 = np.dtype("f4")
3197
+ f8 = np.dtype("f8")
3198
+
3199
+ r = np.add.resolve_dtypes((i4, f4, None))
3200
+ assert r == (f8, f8, f8)
3201
+
3202
+ # Signature uses the same logic to parse as ufunc (less strict)
3203
+ # the following is "same-kind" casting so works:
3204
+ r = np.add.resolve_dtypes((
3205
+ i4, i4, None), signature=(None, None, "f4"))
3206
+ assert r == (f4, f4, f4)
3207
+
3208
+ # Check NEP 50 "weak" promotion also:
3209
+ r = np.add.resolve_dtypes((f4, int, None))
3210
+ assert r == (f4, f4, f4)
3211
+
3212
+ with pytest.raises(TypeError):
3213
+ np.add.resolve_dtypes((i4, f4, None), casting="no")
3214
+
3215
+ def test_resolve_dtypes_comparison(self):
3216
+ i4 = np.dtype("i4")
3217
+ i8 = np.dtype("i8")
3218
+ b = np.dtype("?")
3219
+ r = np.equal.resolve_dtypes((i4, i8, None))
3220
+ assert r == (i8, i8, b)
3221
+
3222
+ def test_weird_dtypes(self):
3223
+ S0 = np.dtype("S0")
3224
+ # S0 is often converted by NumPy to S1, but not here:
3225
+ r = np.equal.resolve_dtypes((S0, S0, None))
3226
+ assert r == (S0, S0, np.dtype(bool))
3227
+
3228
+ # Subarray dtypes are weird and may not work fully, we preserve them
3229
+ # leading to a TypeError (currently no equal loop for void/structured)
3230
+ dts = np.dtype("10i")
3231
+ with pytest.raises(TypeError):
3232
+ np.equal.resolve_dtypes((dts, dts, None))
3233
+
3234
+ def test_resolve_dtypes_reduction(self):
3235
+ i2 = np.dtype("i2")
3236
+ default_int_ = np.dtype(np.int_)
3237
+ # Check special addition resolution:
3238
+ res = np.add.resolve_dtypes((None, i2, None), reduction=True)
3239
+ assert res == (default_int_, default_int_, default_int_)
3240
+
3241
+ def test_resolve_dtypes_reduction_no_output(self):
3242
+ i4 = np.dtype("i4")
3243
+ with pytest.raises(TypeError):
3244
+ # May be allowable at some point?
3245
+ np.add.resolve_dtypes((i4, i4, i4), reduction=True)
3246
+
3247
+ @pytest.mark.parametrize("dtypes", [
3248
+ (np.dtype("i"), np.dtype("i")),
3249
+ (None, np.dtype("i"), np.dtype("f")),
3250
+ (np.dtype("i"), None, np.dtype("f")),
3251
+ ("i4", "i4", None)])
3252
+ def test_resolve_dtypes_errors(self, dtypes):
3253
+ with pytest.raises(TypeError):
3254
+ np.add.resolve_dtypes(dtypes)
3255
+
3256
+ def test_resolve_dtypes_reduction_errors(self):
3257
+ i2 = np.dtype("i2")
3258
+
3259
+ with pytest.raises(TypeError):
3260
+ np.add.resolve_dtypes((None, i2, i2))
3261
+
3262
+ with pytest.raises(TypeError):
3263
+ np.add.signature((None, None, "i4"))
3264
+
3265
+ @pytest.mark.skipif(not hasattr(ct, "pythonapi"),
3266
+ reason="`ctypes.pythonapi` required for capsule unpacking.")
3267
+ @pytest.mark.thread_unsafe(reason="modifies global object in the ctypes API")
3268
+ def test_loop_access(self):
3269
+ # This is a basic test for the full strided loop access
3270
+ data_t = ct.c_char_p * 2
3271
+ dim_t = ct.c_ssize_t * 1
3272
+ strides_t = ct.c_ssize_t * 2
3273
+ strided_loop_t = ct.CFUNCTYPE(
3274
+ ct.c_int, ct.c_void_p, data_t, dim_t, strides_t, ct.c_void_p)
3275
+
3276
+ class call_info_t(ct.Structure):
3277
+ _fields_ = [
3278
+ ("strided_loop", strided_loop_t),
3279
+ ("context", ct.c_void_p),
3280
+ ("auxdata", ct.c_void_p),
3281
+ ("requires_pyapi", ct.c_byte),
3282
+ ("no_floatingpoint_errors", ct.c_byte),
3283
+ ]
3284
+
3285
+ i4 = np.dtype("i4")
3286
+ dt, call_info_obj = np.negative._resolve_dtypes_and_context((i4, i4))
3287
+ assert dt == (i4, i4) # can be used without casting
3288
+
3289
+ # Fill in the rest of the information:
3290
+ np.negative._get_strided_loop(call_info_obj)
3291
+
3292
+ ct.pythonapi.PyCapsule_GetPointer.restype = ct.c_void_p
3293
+ call_info = ct.pythonapi.PyCapsule_GetPointer(
3294
+ ct.py_object(call_info_obj),
3295
+ ct.c_char_p(b"numpy_1.24_ufunc_call_info"))
3296
+
3297
+ call_info = ct.cast(call_info, ct.POINTER(call_info_t)).contents
3298
+
3299
+ arr = np.arange(10, dtype=i4)
3300
+ call_info.strided_loop(
3301
+ call_info.context,
3302
+ data_t(arr.ctypes.data, arr.ctypes.data),
3303
+ arr.ctypes.shape, # is a C-array with 10 here
3304
+ strides_t(arr.ctypes.strides[0], arr.ctypes.strides[0]),
3305
+ call_info.auxdata)
3306
+
3307
+ # We just directly called the negative inner-loop in-place:
3308
+ assert_array_equal(arr, -np.arange(10, dtype=i4))
3309
+
3310
+ @pytest.mark.parametrize("strides", [1, (1, 2, 3), (1, "2")])
3311
+ def test__get_strided_loop_errors_bad_strides(self, strides):
3312
+ i4 = np.dtype("i4")
3313
+ dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
3314
+
3315
+ with pytest.raises(TypeError, match="fixed_strides.*tuple.*or None"):
3316
+ np.negative._get_strided_loop(call_info, fixed_strides=strides)
3317
+
3318
+ def test__get_strided_loop_errors_bad_call_info(self):
3319
+ i4 = np.dtype("i4")
3320
+ dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
3321
+
3322
+ with pytest.raises(ValueError, match="PyCapsule"):
3323
+ np.negative._get_strided_loop("not the capsule!")
3324
+
3325
+ with pytest.raises(TypeError, match=".*incompatible context"):
3326
+ np.add._get_strided_loop(call_info)
3327
+
3328
+ np.negative._get_strided_loop(call_info)
3329
+ with pytest.raises(TypeError):
3330
+ # cannot call it a second time:
3331
+ np.negative._get_strided_loop(call_info)
3332
+
3333
+ def test_long_arrays(self):
3334
+ t = np.zeros((1029, 917), dtype=np.single)
3335
+ t[0][0] = 1
3336
+ t[28][414] = 1
3337
+ tc = np.cos(t)
3338
+ assert_equal(tc[0][0], tc[28][414])
3339
+
3340
+
3341
+ class TestUFuncInspectSignature:
3342
+ PARAMS_COMMON = {
3343
+ "casting": "same_kind",
3344
+ "order": "K",
3345
+ "dtype": None,
3346
+ "subok": True,
3347
+ "signature": None,
3348
+ }
3349
+
3350
+ PARAMS_UFUNC = {
3351
+ "where": True,
3352
+ } | PARAMS_COMMON
3353
+
3354
+ PARAMS_GUFUNC = {
3355
+ "axes": np._NoValue,
3356
+ "axis": np._NoValue,
3357
+ "keepdims": False,
3358
+ } | PARAMS_COMMON
3359
+
3360
+ @pytest.mark.parametrize("ufunc", [np.log, np.gcd, np.frexp, np.divmod, np.matvec])
3361
+ def test_dunder_signature_attr(self, ufunc: np.ufunc):
3362
+ assert hasattr(ufunc, "__signature__")
3363
+ assert isinstance(ufunc.__signature__, inspect.Signature)
3364
+ assert inspect.signature(ufunc) == ufunc.__signature__
3365
+
3366
+ @pytest.mark.parametrize("ufunc", [np.exp, np.mod, np.frexp, np.divmod, np.vecmat])
3367
+ def test_params_common_positional(self, ufunc: np.ufunc):
3368
+ sig = inspect.signature(ufunc)
3369
+
3370
+ # check positional-only parameters
3371
+ posonly_params = {name: param.default
3372
+ for name, param in sig.parameters.items()
3373
+ if param.kind is param.POSITIONAL_ONLY}
3374
+ assert len(posonly_params) == ufunc.nin
3375
+ assert all(default is inspect.Parameter.empty
3376
+ for default in posonly_params.values())
3377
+
3378
+ # check 'out' parameter
3379
+ out_param = sig.parameters.get("out")
3380
+ assert out_param is not None
3381
+ assert out_param.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
3382
+
3383
+ @pytest.mark.parametrize("ufunc", [np.sin, np.add, np.frexp, np.divmod])
3384
+ def test_params_common_ufunc(self, ufunc: np.ufunc):
3385
+ assert ufunc.signature is None # sanity check
3386
+
3387
+ sig = inspect.signature(ufunc)
3388
+
3389
+ # check keyword-only parameters
3390
+ keyword_params = {name: param.default
3391
+ for name, param in sig.parameters.items()
3392
+ if param.kind is param.KEYWORD_ONLY}
3393
+ assert keyword_params == self.PARAMS_UFUNC
3394
+
3395
+ @pytest.mark.parametrize("gufunc", [np.matmul, np.matvec, np.vecdot, np.vecmat])
3396
+ def test_params_common_gufunc(self, gufunc: np.ufunc):
3397
+ assert gufunc.signature is not None # sanity check
3398
+
3399
+ sig = inspect.signature(gufunc)
3400
+
3401
+ # check keyword-only parameters
3402
+ keyword_params = {name: param.default
3403
+ for name, param in sig.parameters.items()
3404
+ if param.kind is param.KEYWORD_ONLY}
3405
+ assert keyword_params == self.PARAMS_GUFUNC