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,4295 @@
1
+ import inspect
2
+ import itertools
3
+ import math
4
+ import platform
5
+ import sys
6
+ import warnings
7
+ from decimal import Decimal
8
+
9
+ import pytest
10
+ from hypothesis import given, strategies as st
11
+ from hypothesis.extra import numpy as hynp
12
+
13
+ import numpy as np
14
+ from numpy import ma
15
+ from numpy._core import sctypes
16
+ from numpy._core._rational_tests import rational
17
+ from numpy._core.numerictypes import obj2sctype
18
+ from numpy.exceptions import AxisError
19
+ from numpy.random import rand, randint, randn
20
+ from numpy.testing import (
21
+ HAS_REFCOUNT,
22
+ IS_PYPY,
23
+ IS_WASM,
24
+ assert_,
25
+ assert_almost_equal,
26
+ assert_array_almost_equal,
27
+ assert_array_equal,
28
+ assert_array_max_ulp,
29
+ assert_equal,
30
+ assert_raises,
31
+ assert_raises_regex,
32
+ )
33
+
34
+
35
+ class TestResize:
36
+ def test_copies(self):
37
+ A = np.array([[1, 2], [3, 4]])
38
+ Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
39
+ assert_equal(np.resize(A, (2, 4)), Ar1)
40
+
41
+ Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
42
+ assert_equal(np.resize(A, (4, 2)), Ar2)
43
+
44
+ Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])
45
+ assert_equal(np.resize(A, (4, 3)), Ar3)
46
+
47
+ def test_repeats(self):
48
+ A = np.array([1, 2, 3])
49
+ Ar1 = np.array([[1, 2, 3, 1], [2, 3, 1, 2]])
50
+ assert_equal(np.resize(A, (2, 4)), Ar1)
51
+
52
+ Ar2 = np.array([[1, 2], [3, 1], [2, 3], [1, 2]])
53
+ assert_equal(np.resize(A, (4, 2)), Ar2)
54
+
55
+ Ar3 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
56
+ assert_equal(np.resize(A, (4, 3)), Ar3)
57
+
58
+ def test_zeroresize(self):
59
+ A = np.array([[1, 2], [3, 4]])
60
+ Ar = np.resize(A, (0,))
61
+ assert_array_equal(Ar, np.array([]))
62
+ assert_equal(A.dtype, Ar.dtype)
63
+
64
+ Ar = np.resize(A, (0, 2))
65
+ assert_equal(Ar.shape, (0, 2))
66
+
67
+ Ar = np.resize(A, (2, 0))
68
+ assert_equal(Ar.shape, (2, 0))
69
+
70
+ def test_reshape_from_zero(self):
71
+ # See also gh-6740
72
+ A = np.zeros(0, dtype=[('a', np.float32)])
73
+ Ar = np.resize(A, (2, 1))
74
+ assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))
75
+ assert_equal(A.dtype, Ar.dtype)
76
+
77
+ def test_negative_resize(self):
78
+ A = np.arange(0, 10, dtype=np.float32)
79
+ new_shape = (-10, -1)
80
+ with pytest.raises(ValueError, match=r"negative"):
81
+ np.resize(A, new_shape=new_shape)
82
+
83
+ def test_unsigned_resize(self):
84
+ # ensure unsigned integer sizes don't lead to underflows
85
+ for dt_pair in [(np.int32, np.uint32), (np.int64, np.uint64)]:
86
+ arr = np.array([[23, 95], [66, 37]])
87
+ assert_array_equal(np.resize(arr, dt_pair[0](1)),
88
+ np.resize(arr, dt_pair[1](1)))
89
+
90
+ def test_subclass(self):
91
+ class MyArray(np.ndarray):
92
+ __array_priority__ = 1.
93
+
94
+ my_arr = np.array([1]).view(MyArray)
95
+ assert type(np.resize(my_arr, 5)) is MyArray
96
+ assert type(np.resize(my_arr, 0)) is MyArray
97
+
98
+ my_arr = np.array([]).view(MyArray)
99
+ assert type(np.resize(my_arr, 5)) is MyArray
100
+
101
+
102
+ class TestNonarrayArgs:
103
+ # check that non-array arguments to functions wrap them in arrays
104
+ def test_choose(self):
105
+ choices = [[0, 1, 2],
106
+ [3, 4, 5],
107
+ [5, 6, 7]]
108
+ tgt = [5, 1, 5]
109
+ a = [2, 0, 1]
110
+
111
+ out = np.choose(a, choices)
112
+ assert_equal(out, tgt)
113
+
114
+ def test_clip(self):
115
+ arr = [-1, 5, 2, 3, 10, -4, -9]
116
+ out = np.clip(arr, 2, 7)
117
+ tgt = [2, 5, 2, 3, 7, 2, 2]
118
+ assert_equal(out, tgt)
119
+
120
+ def test_compress(self):
121
+ arr = [[0, 1, 2, 3, 4],
122
+ [5, 6, 7, 8, 9]]
123
+ tgt = [[5, 6, 7, 8, 9]]
124
+ out = np.compress([0, 1], arr, axis=0)
125
+ assert_equal(out, tgt)
126
+
127
+ def test_count_nonzero(self):
128
+ arr = [[0, 1, 7, 0, 0],
129
+ [3, 0, 0, 2, 19]]
130
+ tgt = np.array([2, 3])
131
+ out = np.count_nonzero(arr, axis=1)
132
+ assert_equal(out, tgt)
133
+
134
+ def test_diagonal(self):
135
+ a = [[0, 1, 2, 3],
136
+ [4, 5, 6, 7],
137
+ [8, 9, 10, 11]]
138
+ out = np.diagonal(a)
139
+ tgt = [0, 5, 10]
140
+
141
+ assert_equal(out, tgt)
142
+
143
+ def test_mean(self):
144
+ A = [[1, 2, 3], [4, 5, 6]]
145
+ assert_(np.mean(A) == 3.5)
146
+ assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])))
147
+ assert_(np.all(np.mean(A, 1) == np.array([2., 5.])))
148
+
149
+ with warnings.catch_warnings(record=True) as w:
150
+ warnings.filterwarnings('always', '', RuntimeWarning)
151
+ assert_(np.isnan(np.mean([])))
152
+ assert_(w[0].category is RuntimeWarning)
153
+
154
+ def test_ptp(self):
155
+ a = [3, 4, 5, 10, -3, -5, 6.0]
156
+ assert_equal(np.ptp(a, axis=0), 15.0)
157
+
158
+ def test_prod(self):
159
+ arr = [[1, 2, 3, 4],
160
+ [5, 6, 7, 9],
161
+ [10, 3, 4, 5]]
162
+ tgt = [24, 1890, 600]
163
+
164
+ assert_equal(np.prod(arr, axis=-1), tgt)
165
+
166
+ def test_ravel(self):
167
+ a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
168
+ tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
169
+ assert_equal(np.ravel(a), tgt)
170
+
171
+ def test_repeat(self):
172
+ a = [1, 2, 3]
173
+ tgt = [1, 1, 2, 2, 3, 3]
174
+
175
+ out = np.repeat(a, 2)
176
+ assert_equal(out, tgt)
177
+
178
+ def test_reshape(self):
179
+ arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
180
+ tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
181
+ assert_equal(np.reshape(arr, (2, 6)), tgt)
182
+
183
+ def test_reshape_shape_arg(self):
184
+ arr = np.arange(12)
185
+ shape = (3, 4)
186
+ expected = arr.reshape(shape)
187
+
188
+ with pytest.raises(
189
+ TypeError,
190
+ match=r"reshape\(\) missing 1 required positional "
191
+ "argument: 'shape'"
192
+ ):
193
+ np.reshape(arr)
194
+
195
+ assert_equal(np.reshape(arr, shape), expected)
196
+ assert_equal(np.reshape(arr, shape, order="C"), expected)
197
+ assert_equal(np.reshape(arr, shape, "C"), expected)
198
+ assert_equal(np.reshape(arr, shape=shape), expected)
199
+ assert_equal(np.reshape(arr, shape=shape, order="C"), expected)
200
+
201
+ def test_reshape_copy_arg(self):
202
+ arr = np.arange(24).reshape(2, 3, 4)
203
+ arr_f_ord = np.array(arr, order="F")
204
+ shape = (12, 2)
205
+
206
+ assert np.shares_memory(np.reshape(arr, shape), arr)
207
+ assert np.shares_memory(np.reshape(arr, shape, order="C"), arr)
208
+ assert np.shares_memory(
209
+ np.reshape(arr_f_ord, shape, order="F"), arr_f_ord)
210
+ assert np.shares_memory(np.reshape(arr, shape, copy=None), arr)
211
+ assert np.shares_memory(np.reshape(arr, shape, copy=False), arr)
212
+ assert np.shares_memory(arr.reshape(shape, copy=False), arr)
213
+ assert not np.shares_memory(np.reshape(arr, shape, copy=True), arr)
214
+ assert not np.shares_memory(
215
+ np.reshape(arr, shape, order="C", copy=True), arr)
216
+ assert not np.shares_memory(
217
+ np.reshape(arr, shape, order="F", copy=True), arr)
218
+ assert not np.shares_memory(
219
+ np.reshape(arr, shape, order="F", copy=None), arr)
220
+
221
+ err_msg = "Unable to avoid creating a copy while reshaping."
222
+ with pytest.raises(ValueError, match=err_msg):
223
+ np.reshape(arr, shape, order="F", copy=False)
224
+ with pytest.raises(ValueError, match=err_msg):
225
+ np.reshape(arr_f_ord, shape, order="C", copy=False)
226
+
227
+ def test_round(self):
228
+ arr = [1.56, 72.54, 6.35, 3.25]
229
+ tgt = [1.6, 72.5, 6.4, 3.2]
230
+ assert_equal(np.around(arr, decimals=1), tgt)
231
+ s = np.float64(1.)
232
+ assert_(isinstance(s.round(), np.float64))
233
+ assert_equal(s.round(), 1.)
234
+
235
+ @pytest.mark.parametrize('dtype', [
236
+ np.int8, np.int16, np.int32, np.int64,
237
+ np.uint8, np.uint16, np.uint32, np.uint64,
238
+ np.float16, np.float32, np.float64,
239
+ ])
240
+ def test_dunder_round(self, dtype):
241
+ s = dtype(1)
242
+ assert_(isinstance(round(s), int))
243
+ assert_(isinstance(round(s, None), int))
244
+ assert_(isinstance(round(s, ndigits=None), int))
245
+ assert_equal(round(s), 1)
246
+ assert_equal(round(s, None), 1)
247
+ assert_equal(round(s, ndigits=None), 1)
248
+
249
+ @pytest.mark.parametrize('val, ndigits', [
250
+ pytest.param(2**31 - 1, -1,
251
+ marks=pytest.mark.skip(reason="Out of range of int32")
252
+ ),
253
+ (2**31 - 1, 1 - math.ceil(math.log10(2**31 - 1))),
254
+ (2**31 - 1, -math.ceil(math.log10(2**31 - 1)))
255
+ ])
256
+ def test_dunder_round_edgecases(self, val, ndigits):
257
+ assert_equal(round(val, ndigits), round(np.int32(val), ndigits))
258
+
259
+ def test_dunder_round_accuracy(self):
260
+ f = np.float64(5.1 * 10**73)
261
+ assert_(isinstance(round(f, -73), np.float64))
262
+ assert_array_max_ulp(round(f, -73), 5.0 * 10**73)
263
+ assert_(isinstance(round(f, ndigits=-73), np.float64))
264
+ assert_array_max_ulp(round(f, ndigits=-73), 5.0 * 10**73)
265
+
266
+ i = np.int64(501)
267
+ assert_(isinstance(round(i, -2), np.int64))
268
+ assert_array_max_ulp(round(i, -2), 500)
269
+ assert_(isinstance(round(i, ndigits=-2), np.int64))
270
+ assert_array_max_ulp(round(i, ndigits=-2), 500)
271
+
272
+ @pytest.mark.xfail(raises=AssertionError, reason="gh-15896")
273
+ def test_round_py_consistency(self):
274
+ f = 5.1 * 10**73
275
+ assert_equal(round(np.float64(f), -73), round(f, -73))
276
+
277
+ def test_searchsorted(self):
278
+ arr = [-8, -5, -1, 3, 6, 10]
279
+ out = np.searchsorted(arr, 0)
280
+ assert_equal(out, 3)
281
+
282
+ def test_size(self):
283
+ A = [[1, 2, 3], [4, 5, 6]]
284
+ assert_(np.size(A) == 6)
285
+ assert_(np.size(A, 0) == 2)
286
+ assert_(np.size(A, 1) == 3)
287
+ assert_(np.size(A, ()) == 1)
288
+ assert_(np.size(A, (0,)) == 2)
289
+ assert_(np.size(A, (1,)) == 3)
290
+ assert_(np.size(A, (0, 1)) == 6)
291
+
292
+ def test_squeeze(self):
293
+ A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]
294
+ assert_equal(np.squeeze(A).shape, (3, 3))
295
+ assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))
296
+ assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))
297
+ assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))
298
+ assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))
299
+ assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))
300
+ assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))
301
+ assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))
302
+ assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))
303
+
304
+ def test_std(self):
305
+ A = [[1, 2, 3], [4, 5, 6]]
306
+ assert_almost_equal(np.std(A), 1.707825127659933)
307
+ assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5]))
308
+ assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658]))
309
+
310
+ with warnings.catch_warnings(record=True) as w:
311
+ warnings.filterwarnings('always', '', RuntimeWarning)
312
+ assert_(np.isnan(np.std([])))
313
+ assert_(w[0].category is RuntimeWarning)
314
+
315
+ def test_swapaxes(self):
316
+ tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]]
317
+ a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
318
+ out = np.swapaxes(a, 0, 2)
319
+ assert_equal(out, tgt)
320
+
321
+ def test_sum(self):
322
+ m = [[1, 2, 3],
323
+ [4, 5, 6],
324
+ [7, 8, 9]]
325
+ tgt = [[6], [15], [24]]
326
+ out = np.sum(m, axis=1, keepdims=True)
327
+
328
+ assert_equal(tgt, out)
329
+
330
+ def test_take(self):
331
+ tgt = [2, 3, 5]
332
+ indices = [1, 2, 4]
333
+ a = [1, 2, 3, 4, 5]
334
+
335
+ out = np.take(a, indices)
336
+ assert_equal(out, tgt)
337
+
338
+ pairs = [
339
+ (np.int32, np.int32), (np.int32, np.int64),
340
+ (np.int64, np.int32), (np.int64, np.int64)
341
+ ]
342
+ for array_type, indices_type in pairs:
343
+ x = np.array([1, 2, 3, 4, 5], dtype=array_type)
344
+ ind = np.array([0, 2, 2, 3], dtype=indices_type)
345
+ tgt = np.array([1, 3, 3, 4], dtype=array_type)
346
+ out = np.take(x, ind)
347
+ assert_equal(out, tgt)
348
+ assert_equal(out.dtype, tgt.dtype)
349
+
350
+ def test_trace(self):
351
+ c = [[1, 2], [3, 4], [5, 6]]
352
+ assert_equal(np.trace(c), 5)
353
+
354
+ def test_transpose(self):
355
+ arr = [[1, 2], [3, 4], [5, 6]]
356
+ tgt = [[1, 3, 5], [2, 4, 6]]
357
+ assert_equal(np.transpose(arr, (1, 0)), tgt)
358
+ assert_equal(np.transpose(arr, (-1, -2)), tgt)
359
+ assert_equal(np.matrix_transpose(arr), tgt)
360
+
361
+ def test_var(self):
362
+ A = [[1, 2, 3], [4, 5, 6]]
363
+ assert_almost_equal(np.var(A), 2.9166666666666665)
364
+ assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25]))
365
+ assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667]))
366
+
367
+ with warnings.catch_warnings(record=True) as w:
368
+ warnings.filterwarnings('always', '', RuntimeWarning)
369
+ assert_(np.isnan(np.var([])))
370
+ assert_(w[0].category is RuntimeWarning)
371
+
372
+ B = np.array([None, 0])
373
+ B[0] = 1j
374
+ assert_almost_equal(np.var(B), 0.25)
375
+
376
+ def test_std_with_mean_keyword(self):
377
+ # Setting the seed to make the test reproducible
378
+ rng = np.random.RandomState(1234)
379
+ A = rng.randn(10, 20, 5) + 0.5
380
+
381
+ mean_out = np.zeros((10, 1, 5))
382
+ std_out = np.zeros((10, 1, 5))
383
+
384
+ mean = np.mean(A,
385
+ out=mean_out,
386
+ axis=1,
387
+ keepdims=True)
388
+
389
+ # The returned object should be the object specified during calling
390
+ assert mean_out is mean
391
+
392
+ std = np.std(A,
393
+ out=std_out,
394
+ axis=1,
395
+ keepdims=True,
396
+ mean=mean)
397
+
398
+ # The returned object should be the object specified during calling
399
+ assert std_out is std
400
+
401
+ # Shape of returned mean and std should be same
402
+ assert std.shape == mean.shape
403
+ assert std.shape == (10, 1, 5)
404
+
405
+ # Output should be the same as from the individual algorithms
406
+ std_old = np.std(A, axis=1, keepdims=True)
407
+
408
+ assert std_old.shape == mean.shape
409
+ assert_almost_equal(std, std_old)
410
+
411
+ def test_var_with_mean_keyword(self):
412
+ # Setting the seed to make the test reproducible
413
+ rng = np.random.RandomState(1234)
414
+ A = rng.randn(10, 20, 5) + 0.5
415
+
416
+ mean_out = np.zeros((10, 1, 5))
417
+ var_out = np.zeros((10, 1, 5))
418
+
419
+ mean = np.mean(A,
420
+ out=mean_out,
421
+ axis=1,
422
+ keepdims=True)
423
+
424
+ # The returned object should be the object specified during calling
425
+ assert mean_out is mean
426
+
427
+ var = np.var(A,
428
+ out=var_out,
429
+ axis=1,
430
+ keepdims=True,
431
+ mean=mean)
432
+
433
+ # The returned object should be the object specified during calling
434
+ assert var_out is var
435
+
436
+ # Shape of returned mean and var should be same
437
+ assert var.shape == mean.shape
438
+ assert var.shape == (10, 1, 5)
439
+
440
+ # Output should be the same as from the individual algorithms
441
+ var_old = np.var(A, axis=1, keepdims=True)
442
+
443
+ assert var_old.shape == mean.shape
444
+ assert_almost_equal(var, var_old)
445
+
446
+ def test_std_with_mean_keyword_keepdims_false(self):
447
+ rng = np.random.RandomState(1234)
448
+ A = rng.randn(10, 20, 5) + 0.5
449
+
450
+ mean = np.mean(A,
451
+ axis=1,
452
+ keepdims=True)
453
+
454
+ std = np.std(A,
455
+ axis=1,
456
+ keepdims=False,
457
+ mean=mean)
458
+
459
+ # Shape of returned mean and std should be same
460
+ assert std.shape == (10, 5)
461
+
462
+ # Output should be the same as from the individual algorithms
463
+ std_old = np.std(A, axis=1, keepdims=False)
464
+ mean_old = np.mean(A, axis=1, keepdims=False)
465
+
466
+ assert std_old.shape == mean_old.shape
467
+ assert_equal(std, std_old)
468
+
469
+ def test_var_with_mean_keyword_keepdims_false(self):
470
+ rng = np.random.RandomState(1234)
471
+ A = rng.randn(10, 20, 5) + 0.5
472
+
473
+ mean = np.mean(A,
474
+ axis=1,
475
+ keepdims=True)
476
+
477
+ var = np.var(A,
478
+ axis=1,
479
+ keepdims=False,
480
+ mean=mean)
481
+
482
+ # Shape of returned mean and var should be same
483
+ assert var.shape == (10, 5)
484
+
485
+ # Output should be the same as from the individual algorithms
486
+ var_old = np.var(A, axis=1, keepdims=False)
487
+ mean_old = np.mean(A, axis=1, keepdims=False)
488
+
489
+ assert var_old.shape == mean_old.shape
490
+ assert_equal(var, var_old)
491
+
492
+ def test_std_with_mean_keyword_where_nontrivial(self):
493
+ rng = np.random.RandomState(1234)
494
+ A = rng.randn(10, 20, 5) + 0.5
495
+
496
+ where = A > 0.5
497
+
498
+ mean = np.mean(A,
499
+ axis=1,
500
+ keepdims=True,
501
+ where=where)
502
+
503
+ std = np.std(A,
504
+ axis=1,
505
+ keepdims=False,
506
+ mean=mean,
507
+ where=where)
508
+
509
+ # Shape of returned mean and std should be same
510
+ assert std.shape == (10, 5)
511
+
512
+ # Output should be the same as from the individual algorithms
513
+ std_old = np.std(A, axis=1, where=where)
514
+ mean_old = np.mean(A, axis=1, where=where)
515
+
516
+ assert std_old.shape == mean_old.shape
517
+ assert_equal(std, std_old)
518
+
519
+ def test_var_with_mean_keyword_where_nontrivial(self):
520
+ rng = np.random.RandomState(1234)
521
+ A = rng.randn(10, 20, 5) + 0.5
522
+
523
+ where = A > 0.5
524
+
525
+ mean = np.mean(A,
526
+ axis=1,
527
+ keepdims=True,
528
+ where=where)
529
+
530
+ var = np.var(A,
531
+ axis=1,
532
+ keepdims=False,
533
+ mean=mean,
534
+ where=where)
535
+
536
+ # Shape of returned mean and var should be same
537
+ assert var.shape == (10, 5)
538
+
539
+ # Output should be the same as from the individual algorithms
540
+ var_old = np.var(A, axis=1, where=where)
541
+ mean_old = np.mean(A, axis=1, where=where)
542
+
543
+ assert var_old.shape == mean_old.shape
544
+ assert_equal(var, var_old)
545
+
546
+ def test_std_with_mean_keyword_multiple_axis(self):
547
+ # Setting the seed to make the test reproducible
548
+ rng = np.random.RandomState(1234)
549
+ A = rng.randn(10, 20, 5) + 0.5
550
+
551
+ axis = (0, 2)
552
+
553
+ mean = np.mean(A,
554
+ out=None,
555
+ axis=axis,
556
+ keepdims=True)
557
+
558
+ std = np.std(A,
559
+ out=None,
560
+ axis=axis,
561
+ keepdims=False,
562
+ mean=mean)
563
+
564
+ # Shape of returned mean and std should be same
565
+ assert std.shape == (20,)
566
+
567
+ # Output should be the same as from the individual algorithms
568
+ std_old = np.std(A, axis=axis, keepdims=False)
569
+
570
+ assert_almost_equal(std, std_old)
571
+
572
+ def test_std_with_mean_keyword_axis_None(self):
573
+ # Setting the seed to make the test reproducible
574
+ rng = np.random.RandomState(1234)
575
+ A = rng.randn(10, 20, 5) + 0.5
576
+
577
+ axis = None
578
+
579
+ mean = np.mean(A,
580
+ out=None,
581
+ axis=axis,
582
+ keepdims=True)
583
+
584
+ std = np.std(A,
585
+ out=None,
586
+ axis=axis,
587
+ keepdims=False,
588
+ mean=mean)
589
+
590
+ # Shape of returned mean and std should be same
591
+ assert std.shape == ()
592
+
593
+ # Output should be the same as from the individual algorithms
594
+ std_old = np.std(A, axis=axis, keepdims=False)
595
+
596
+ assert_almost_equal(std, std_old)
597
+
598
+ def test_std_with_mean_keyword_keepdims_true_masked(self):
599
+
600
+ A = ma.array([[2., 3., 4., 5.],
601
+ [1., 2., 3., 4.]],
602
+ mask=[[True, False, True, False],
603
+ [True, False, True, False]])
604
+
605
+ B = ma.array([[100., 3., 104., 5.],
606
+ [101., 2., 103., 4.]],
607
+ mask=[[True, False, True, False],
608
+ [True, False, True, False]])
609
+
610
+ mean_out = ma.array([[0., 0., 0., 0.]],
611
+ mask=[[False, False, False, False]])
612
+ std_out = ma.array([[0., 0., 0., 0.]],
613
+ mask=[[False, False, False, False]])
614
+
615
+ axis = 0
616
+
617
+ mean = np.mean(A, out=mean_out,
618
+ axis=axis, keepdims=True)
619
+
620
+ std = np.std(A, out=std_out,
621
+ axis=axis, keepdims=True,
622
+ mean=mean)
623
+
624
+ # Shape of returned mean and std should be same
625
+ assert std.shape == mean.shape
626
+ assert std.shape == (1, 4)
627
+
628
+ # Output should be the same as from the individual algorithms
629
+ std_old = np.std(A, axis=axis, keepdims=True)
630
+ mean_old = np.mean(A, axis=axis, keepdims=True)
631
+
632
+ assert std_old.shape == mean_old.shape
633
+ assert_almost_equal(std, std_old)
634
+ assert_almost_equal(mean, mean_old)
635
+
636
+ assert mean_out is mean
637
+ assert std_out is std
638
+
639
+ # masked elements should be ignored
640
+ mean_b = np.mean(B, axis=axis, keepdims=True)
641
+ std_b = np.std(B, axis=axis, keepdims=True, mean=mean_b)
642
+ assert_almost_equal(std, std_b)
643
+ assert_almost_equal(mean, mean_b)
644
+
645
+ def test_var_with_mean_keyword_keepdims_true_masked(self):
646
+
647
+ A = ma.array([[2., 3., 4., 5.],
648
+ [1., 2., 3., 4.]],
649
+ mask=[[True, False, True, False],
650
+ [True, False, True, False]])
651
+
652
+ B = ma.array([[100., 3., 104., 5.],
653
+ [101., 2., 103., 4.]],
654
+ mask=[[True, False, True, False],
655
+ [True, False, True, False]])
656
+
657
+ mean_out = ma.array([[0., 0., 0., 0.]],
658
+ mask=[[False, False, False, False]])
659
+ var_out = ma.array([[0., 0., 0., 0.]],
660
+ mask=[[False, False, False, False]])
661
+
662
+ axis = 0
663
+
664
+ mean = np.mean(A, out=mean_out,
665
+ axis=axis, keepdims=True)
666
+
667
+ var = np.var(A, out=var_out,
668
+ axis=axis, keepdims=True,
669
+ mean=mean)
670
+
671
+ # Shape of returned mean and var should be same
672
+ assert var.shape == mean.shape
673
+ assert var.shape == (1, 4)
674
+
675
+ # Output should be the same as from the individual algorithms
676
+ var_old = np.var(A, axis=axis, keepdims=True)
677
+ mean_old = np.mean(A, axis=axis, keepdims=True)
678
+
679
+ assert var_old.shape == mean_old.shape
680
+ assert_almost_equal(var, var_old)
681
+ assert_almost_equal(mean, mean_old)
682
+
683
+ assert mean_out is mean
684
+ assert var_out is var
685
+
686
+ # masked elements should be ignored
687
+ mean_b = np.mean(B, axis=axis, keepdims=True)
688
+ var_b = np.var(B, axis=axis, keepdims=True, mean=mean_b)
689
+ assert_almost_equal(var, var_b)
690
+ assert_almost_equal(mean, mean_b)
691
+
692
+
693
+ class TestIsscalar:
694
+ def test_isscalar(self):
695
+ assert_(np.isscalar(3.1))
696
+ assert_(np.isscalar(np.int16(12345)))
697
+ assert_(np.isscalar(False))
698
+ assert_(np.isscalar('numpy'))
699
+ assert_(not np.isscalar([3.1]))
700
+ assert_(not np.isscalar(None))
701
+
702
+ # PEP 3141
703
+ from fractions import Fraction
704
+ assert_(np.isscalar(Fraction(5, 17)))
705
+ from numbers import Number
706
+ assert_(np.isscalar(Number()))
707
+
708
+
709
+ class TestBoolScalar:
710
+ def test_logical(self):
711
+ f = np.False_
712
+ t = np.True_
713
+ s = "xyz"
714
+ assert_((t and s) is s)
715
+ assert_((f and s) is f)
716
+
717
+ def test_bitwise_or(self):
718
+ f = np.False_
719
+ t = np.True_
720
+ assert_((t | t) is t)
721
+ assert_((f | t) is t)
722
+ assert_((t | f) is t)
723
+ assert_((f | f) is f)
724
+
725
+ def test_bitwise_and(self):
726
+ f = np.False_
727
+ t = np.True_
728
+ assert_((t & t) is t)
729
+ assert_((f & t) is f)
730
+ assert_((t & f) is f)
731
+ assert_((f & f) is f)
732
+
733
+ def test_bitwise_xor(self):
734
+ f = np.False_
735
+ t = np.True_
736
+ assert_((t ^ t) is f)
737
+ assert_((f ^ t) is t)
738
+ assert_((t ^ f) is t)
739
+ assert_((f ^ f) is f)
740
+
741
+
742
+ class TestBoolArray:
743
+ def _create_bool_arrays(self):
744
+ # offset for simd tests
745
+ t = np.array([True] * 41, dtype=bool)[1::]
746
+ f = np.array([False] * 41, dtype=bool)[1::]
747
+ o = np.array([False] * 42, dtype=bool)[2::]
748
+ nm = f.copy()
749
+ im = t.copy()
750
+ nm[3] = True
751
+ nm[-2] = True
752
+ im[3] = False
753
+ im[-2] = False
754
+ return t, f, o, nm, im
755
+
756
+ def test_all_any(self):
757
+ t, f, _, nm, im = self._create_bool_arrays()
758
+ assert_(t.all())
759
+ assert_(t.any())
760
+ assert_(not f.all())
761
+ assert_(not f.any())
762
+ assert_(nm.any())
763
+ assert_(im.any())
764
+ assert_(not nm.all())
765
+ assert_(not im.all())
766
+ # check bad element in all positions
767
+ for i in range(256 - 7):
768
+ d = np.array([False] * 256, dtype=bool)[7::]
769
+ d[i] = True
770
+ assert_(np.any(d))
771
+ e = np.array([True] * 256, dtype=bool)[7::]
772
+ e[i] = False
773
+ assert_(not np.all(e))
774
+ assert_array_equal(e, ~d)
775
+ # big array test for blocked libc loops
776
+ for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
777
+ d = np.array([False] * 100043, dtype=bool)
778
+ d[i] = True
779
+ assert_(np.any(d), msg=f"{i!r}")
780
+ e = np.array([True] * 100043, dtype=bool)
781
+ e[i] = False
782
+ assert_(not np.all(e), msg=f"{i!r}")
783
+
784
+ def test_logical_not_abs(self):
785
+ t, f, o, nm, im = self._create_bool_arrays()
786
+ assert_array_equal(~t, f)
787
+ assert_array_equal(np.abs(~t), f)
788
+ assert_array_equal(np.abs(~f), t)
789
+ assert_array_equal(np.abs(f), f)
790
+ assert_array_equal(~np.abs(f), t)
791
+ assert_array_equal(~np.abs(t), f)
792
+ assert_array_equal(np.abs(~nm), im)
793
+ np.logical_not(t, out=o)
794
+ assert_array_equal(o, f)
795
+ np.abs(t, out=o)
796
+ assert_array_equal(o, t)
797
+
798
+ def test_logical_and_or_xor(self):
799
+ t, f, o, nm, im = self._create_bool_arrays()
800
+ assert_array_equal(t | t, t)
801
+ assert_array_equal(f | f, f)
802
+ assert_array_equal(t | f, t)
803
+ assert_array_equal(f | t, t)
804
+ np.logical_or(t, t, out=o)
805
+ assert_array_equal(o, t)
806
+ assert_array_equal(t & t, t)
807
+ assert_array_equal(f & f, f)
808
+ assert_array_equal(t & f, f)
809
+ assert_array_equal(f & t, f)
810
+ np.logical_and(t, t, out=o)
811
+ assert_array_equal(o, t)
812
+ assert_array_equal(t ^ t, f)
813
+ assert_array_equal(f ^ f, f)
814
+ assert_array_equal(t ^ f, t)
815
+ assert_array_equal(f ^ t, t)
816
+ np.logical_xor(t, t, out=o)
817
+ assert_array_equal(o, f)
818
+
819
+ assert_array_equal(nm & t, nm)
820
+ assert_array_equal(im & f, False)
821
+ assert_array_equal(nm & True, nm)
822
+ assert_array_equal(im & False, f)
823
+ assert_array_equal(nm | t, t)
824
+ assert_array_equal(im | f, im)
825
+ assert_array_equal(nm | True, t)
826
+ assert_array_equal(im | False, im)
827
+ assert_array_equal(nm ^ t, im)
828
+ assert_array_equal(im ^ f, im)
829
+ assert_array_equal(nm ^ True, im)
830
+ assert_array_equal(im ^ False, im)
831
+
832
+
833
+ class TestBoolCmp:
834
+ def _create_data(self, dtype, size):
835
+ # generate data using given dtype and num for size of array
836
+ a = np.ones(size, dtype=dtype)
837
+ e = np.ones(a.size, dtype=bool)
838
+ # generate values for all permutation of 256bit simd vectors
839
+ s = 0
840
+ r = int(size / 32)
841
+ for i in range(int(size / 8)):
842
+ a[s:s + r] = [i & 2**x for x in range(r)]
843
+ e[s:s + r] = [(i & 2**x) != 0 for x in range(r)]
844
+ s += r
845
+ n = a.copy()
846
+ n[e] = np.nan
847
+
848
+ inf = a.copy()
849
+ inf[::3][e[::3]] = np.inf
850
+ inf[1::3][e[1::3]] = -np.inf
851
+ inf[2::3][e[2::3]] = np.nan
852
+ enonan = e.copy()
853
+ enonan[2::3] = False
854
+
855
+ sign = a.copy()
856
+ sign[e] *= -1.
857
+ sign[1::6][e[1::6]] = -np.inf
858
+ # On RISC-V, many operations that produce NaNs, such as converting
859
+ # a -NaN from f64 to f32, return a canonical NaN. The canonical
860
+ # NaNs are always positive. See section 11.3 NaN Generation and
861
+ # Propagation of the RISC-V Unprivileged ISA for more details.
862
+ # We disable the float32 sign test on riscv64 for -np.nan as the sign
863
+ # of the NaN will be lost when it's converted to a float32.
864
+ if not (dtype == np.float32 and platform.machine() == 'riscv64'):
865
+ sign[3::6][e[3::6]] = -np.nan
866
+ sign[4::6][e[4::6]] = -0.
867
+ return a, e, n, inf, enonan, sign
868
+
869
+ def test_float(self):
870
+ # offset for alignment test
871
+ f, ef, nf, inff, efnonan, signf = self._create_data(np.float32, 256)
872
+ for i in range(4):
873
+ assert_array_equal(f[i:] > 0, ef[i:])
874
+ assert_array_equal(f[i:] - 1 >= 0, ef[i:])
875
+ assert_array_equal(f[i:] == 0, ~ef[i:])
876
+ assert_array_equal(-f[i:] < 0, ef[i:])
877
+ assert_array_equal(-f[i:] + 1 <= 0, ef[i:])
878
+ r = f[i:] != 0
879
+ assert_array_equal(r, ef[i:])
880
+ r2 = f[i:] != np.zeros_like(f[i:])
881
+ r3 = 0 != f[i:]
882
+ assert_array_equal(r, r2)
883
+ assert_array_equal(r, r3)
884
+ # check bool == 0x1
885
+ assert_array_equal(r.view(np.int8), r.astype(np.int8))
886
+ assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
887
+ assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
888
+
889
+ # isnan on amd64 takes the same code path
890
+ assert_array_equal(np.isnan(nf[i:]), ef[i:])
891
+ assert_array_equal(np.isfinite(nf[i:]), ~ef[i:])
892
+ assert_array_equal(np.isfinite(inff[i:]), ~ef[i:])
893
+ assert_array_equal(np.isinf(inff[i:]), efnonan[i:])
894
+ assert_array_equal(np.signbit(signf[i:]), ef[i:])
895
+
896
+ def test_double(self):
897
+ # offset for alignment test
898
+ d, ed, nd, infd, ednonan, signd = self._create_data(np.float64, 128)
899
+ for i in range(2):
900
+ assert_array_equal(d[i:] > 0, ed[i:])
901
+ assert_array_equal(d[i:] - 1 >= 0, ed[i:])
902
+ assert_array_equal(d[i:] == 0, ~ed[i:])
903
+ assert_array_equal(-d[i:] < 0, ed[i:])
904
+ assert_array_equal(-d[i:] + 1 <= 0, ed[i:])
905
+ r = d[i:] != 0
906
+ assert_array_equal(r, ed[i:])
907
+ r2 = d[i:] != np.zeros_like(d[i:])
908
+ r3 = 0 != d[i:]
909
+ assert_array_equal(r, r2)
910
+ assert_array_equal(r, r3)
911
+ # check bool == 0x1
912
+ assert_array_equal(r.view(np.int8), r.astype(np.int8))
913
+ assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
914
+ assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
915
+
916
+ # isnan on amd64 takes the same code path
917
+ assert_array_equal(np.isnan(nd[i:]), ed[i:])
918
+ assert_array_equal(np.isfinite(nd[i:]), ~ed[i:])
919
+ assert_array_equal(np.isfinite(infd[i:]), ~ed[i:])
920
+ assert_array_equal(np.isinf(infd[i:]), ednonan[i:])
921
+ assert_array_equal(np.signbit(signd[i:]), ed[i:])
922
+
923
+
924
+ class TestSeterr:
925
+ def test_default(self):
926
+ err = np.geterr()
927
+ assert_equal(err,
928
+ {'divide': 'warn',
929
+ 'invalid': 'warn',
930
+ 'over': 'warn',
931
+ 'under': 'ignore'}
932
+ )
933
+
934
+ def test_set(self):
935
+ with np.errstate():
936
+ err = np.seterr()
937
+ old = np.seterr(divide='print')
938
+ assert_(err == old)
939
+ new = np.seterr()
940
+ assert_(new['divide'] == 'print')
941
+ np.seterr(over='raise')
942
+ assert_(np.geterr()['over'] == 'raise')
943
+ assert_(new['divide'] == 'print')
944
+ np.seterr(**old)
945
+ assert_(np.geterr() == old)
946
+
947
+ @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
948
+ @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
949
+ def test_divide_err(self):
950
+ with np.errstate(divide='raise'):
951
+ with assert_raises(FloatingPointError):
952
+ np.array([1.]) / np.array([0.])
953
+
954
+ np.seterr(divide='ignore')
955
+ np.array([1.]) / np.array([0.])
956
+
957
+
958
+ class TestFloatExceptions:
959
+ def assert_raises_fpe(self, fpeerr, flop, x, y):
960
+ ftype = type(x)
961
+ try:
962
+ flop(x, y)
963
+ assert_(False,
964
+ f"Type {ftype} did not raise fpe error '{fpeerr}'.")
965
+ except FloatingPointError as exc:
966
+ assert_(str(exc).find(fpeerr) >= 0,
967
+ f"Type {ftype} raised wrong fpe error '{exc}'.")
968
+
969
+ def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):
970
+ # Check that fpe exception is raised.
971
+ #
972
+ # Given a floating operation `flop` and two scalar values, check that
973
+ # the operation raises the floating point exception specified by
974
+ # `fpeerr`. Tests all variants with 0-d array scalars as well.
975
+
976
+ self.assert_raises_fpe(fpeerr, flop, sc1, sc2)
977
+ self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2)
978
+ self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()])
979
+ self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()])
980
+
981
+ # Test for all real and complex float types
982
+ @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
983
+ @pytest.mark.parametrize("typecode", np.typecodes["AllFloat"])
984
+ def test_floating_exceptions(self, typecode):
985
+ if 'bsd' in sys.platform and typecode in 'gG':
986
+ pytest.skip(reason="Fallback impl for (c)longdouble may not raise "
987
+ "FPE errors as expected on BSD OSes, "
988
+ "see gh-24876, gh-23379")
989
+
990
+ # Test basic arithmetic function errors
991
+ with np.errstate(all='raise'):
992
+ ftype = obj2sctype(typecode)
993
+ if np.dtype(ftype).kind == 'f':
994
+ # Get some extreme values for the type
995
+ fi = np.finfo(ftype)
996
+ ft_tiny = fi.tiny
997
+ ft_max = fi.max
998
+ ft_eps = fi.eps
999
+ underflow = 'underflow'
1000
+ divbyzero = 'divide by zero'
1001
+ else:
1002
+ # 'c', complex, corresponding real dtype
1003
+ rtype = type(ftype(0).real)
1004
+ fi = np.finfo(rtype)
1005
+ ft_tiny = ftype(fi.tiny)
1006
+ ft_max = ftype(fi.max)
1007
+ ft_eps = ftype(fi.eps)
1008
+ # The complex types raise different exceptions
1009
+ underflow = ''
1010
+ divbyzero = ''
1011
+ overflow = 'overflow'
1012
+ invalid = 'invalid'
1013
+
1014
+ # The value of tiny for double double is NaN, so we need to
1015
+ # pass the assert
1016
+ if not np.isnan(ft_tiny):
1017
+ self.assert_raises_fpe(underflow,
1018
+ lambda a, b: a / b, ft_tiny, ft_max)
1019
+ self.assert_raises_fpe(underflow,
1020
+ lambda a, b: a * b, ft_tiny, ft_tiny)
1021
+ self.assert_raises_fpe(overflow,
1022
+ lambda a, b: a * b, ft_max, ftype(2))
1023
+ self.assert_raises_fpe(overflow,
1024
+ lambda a, b: a / b, ft_max, ftype(0.5))
1025
+ self.assert_raises_fpe(overflow,
1026
+ lambda a, b: a + b, ft_max, ft_max * ft_eps)
1027
+ self.assert_raises_fpe(overflow,
1028
+ lambda a, b: a - b, -ft_max, ft_max * ft_eps)
1029
+ # On AIX, pow() with double does not raise the overflow exception,
1030
+ # it returns inf. Long double is the same as double.
1031
+ if sys.platform != 'aix' or typecode not in 'dDgG':
1032
+ self.assert_raises_fpe(overflow,
1033
+ np.power, ftype(2), ftype(2**fi.nexp))
1034
+ self.assert_raises_fpe(divbyzero,
1035
+ lambda a, b: a / b, ftype(1), ftype(0))
1036
+ self.assert_raises_fpe(
1037
+ invalid, lambda a, b: a / b, ftype(np.inf), ftype(np.inf)
1038
+ )
1039
+ self.assert_raises_fpe(invalid,
1040
+ lambda a, b: a / b, ftype(0), ftype(0))
1041
+ self.assert_raises_fpe(
1042
+ invalid, lambda a, b: a - b, ftype(np.inf), ftype(np.inf)
1043
+ )
1044
+ self.assert_raises_fpe(
1045
+ invalid, lambda a, b: a + b, ftype(np.inf), ftype(-np.inf)
1046
+ )
1047
+ self.assert_raises_fpe(invalid,
1048
+ lambda a, b: a * b, ftype(0), ftype(np.inf))
1049
+
1050
+ @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
1051
+ def test_warnings(self):
1052
+ # test warning code path
1053
+ with warnings.catch_warnings(record=True) as w:
1054
+ warnings.simplefilter("always")
1055
+ with np.errstate(all="warn"):
1056
+ np.divide(1, 0.)
1057
+ assert_equal(len(w), 1)
1058
+ assert_("divide by zero" in str(w[0].message))
1059
+ np.array(1e300) * np.array(1e300)
1060
+ assert_equal(len(w), 2)
1061
+ assert_("overflow" in str(w[-1].message))
1062
+ np.array(np.inf) - np.array(np.inf)
1063
+ assert_equal(len(w), 3)
1064
+ assert_("invalid value" in str(w[-1].message))
1065
+ np.array(1e-300) * np.array(1e-300)
1066
+ assert_equal(len(w), 4)
1067
+ assert_("underflow" in str(w[-1].message))
1068
+
1069
+
1070
+ class TestTypes:
1071
+ def check_promotion_cases(self, promote_func):
1072
+ # tests that the scalars get coerced correctly.
1073
+ b = np.bool(0)
1074
+ i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
1075
+ u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0)
1076
+ f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0)
1077
+ c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0)
1078
+
1079
+ # coercion within the same kind
1080
+ assert_equal(promote_func(i8, i16), np.dtype(np.int16))
1081
+ assert_equal(promote_func(i32, i8), np.dtype(np.int32))
1082
+ assert_equal(promote_func(i16, i64), np.dtype(np.int64))
1083
+ assert_equal(promote_func(u8, u32), np.dtype(np.uint32))
1084
+ assert_equal(promote_func(f32, f64), np.dtype(np.float64))
1085
+ assert_equal(promote_func(fld, f32), np.dtype(np.longdouble))
1086
+ assert_equal(promote_func(f64, fld), np.dtype(np.longdouble))
1087
+ assert_equal(promote_func(c128, c64), np.dtype(np.complex128))
1088
+ assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble))
1089
+ assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble))
1090
+
1091
+ # coercion between kinds
1092
+ assert_equal(promote_func(b, i32), np.dtype(np.int32))
1093
+ assert_equal(promote_func(b, u8), np.dtype(np.uint8))
1094
+ assert_equal(promote_func(i8, u8), np.dtype(np.int16))
1095
+ assert_equal(promote_func(u8, i32), np.dtype(np.int32))
1096
+ assert_equal(promote_func(i64, u32), np.dtype(np.int64))
1097
+ assert_equal(promote_func(u64, i32), np.dtype(np.float64))
1098
+ assert_equal(promote_func(i32, f32), np.dtype(np.float64))
1099
+ assert_equal(promote_func(i64, f32), np.dtype(np.float64))
1100
+ assert_equal(promote_func(f32, i16), np.dtype(np.float32))
1101
+ assert_equal(promote_func(f32, u32), np.dtype(np.float64))
1102
+ assert_equal(promote_func(f32, c64), np.dtype(np.complex64))
1103
+ assert_equal(promote_func(c128, f32), np.dtype(np.complex128))
1104
+ assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble))
1105
+
1106
+ # coercion between scalars and 1-D arrays
1107
+ assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8))
1108
+ assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8))
1109
+ assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32))
1110
+ assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32))
1111
+ assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int64))
1112
+ # unsigned and signed unfortunately tend to promote to float64:
1113
+ assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.float64))
1114
+ assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.int64))
1115
+ assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.int32))
1116
+ assert_equal(promote_func(np.int32(-1), np.array([u64])),
1117
+ np.dtype(np.float64))
1118
+ assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float64))
1119
+ assert_equal(promote_func(fld, np.array([f32])),
1120
+ np.dtype(np.longdouble))
1121
+ assert_equal(promote_func(np.array([f64]), fld),
1122
+ np.dtype(np.longdouble))
1123
+ assert_equal(promote_func(fld, np.array([c64])),
1124
+ np.dtype(np.clongdouble))
1125
+ assert_equal(promote_func(c64, np.array([f64])),
1126
+ np.dtype(np.complex128))
1127
+ assert_equal(promote_func(np.complex64(3j), np.array([f64])),
1128
+ np.dtype(np.complex128))
1129
+ assert_equal(promote_func(np.array([f32]), c128),
1130
+ np.dtype(np.complex128))
1131
+
1132
+ # coercion between scalars and 1-D arrays, where
1133
+ # the scalar has greater kind than the array
1134
+ assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64))
1135
+ assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64))
1136
+ assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64))
1137
+ assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64))
1138
+ assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64))
1139
+
1140
+ def test_coercion(self):
1141
+ def res_type(a, b):
1142
+ return np.add(a, b).dtype
1143
+
1144
+ self.check_promotion_cases(res_type)
1145
+
1146
+ # Use-case: float/complex scalar * bool/int8 array
1147
+ # shouldn't narrow the float/complex type
1148
+ for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:
1149
+ b = 1.234 * a
1150
+ assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
1151
+ b = np.longdouble(1.234) * a
1152
+ assert_equal(b.dtype, np.dtype(np.longdouble),
1153
+ f"array type {a.dtype}")
1154
+ b = np.float64(1.234) * a
1155
+ assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
1156
+ b = np.float32(1.234) * a
1157
+ assert_equal(b.dtype, np.dtype('f4'), f"array type {a.dtype}")
1158
+ b = np.float16(1.234) * a
1159
+ assert_equal(b.dtype, np.dtype('f2'), f"array type {a.dtype}")
1160
+
1161
+ b = 1.234j * a
1162
+ assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
1163
+ b = np.clongdouble(1.234j) * a
1164
+ assert_equal(b.dtype, np.dtype(np.clongdouble),
1165
+ f"array type {a.dtype}")
1166
+ b = np.complex128(1.234j) * a
1167
+ assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
1168
+ b = np.complex64(1.234j) * a
1169
+ assert_equal(b.dtype, np.dtype('c8'), f"array type {a.dtype}")
1170
+
1171
+ # The following use-case is problematic, and to resolve its
1172
+ # tricky side-effects requires more changes.
1173
+ #
1174
+ # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is
1175
+ # a float32, shouldn't promote to float64
1176
+ #
1177
+ # a = np.array([1.0, 1.5], dtype=np.float32)
1178
+ # t = np.array([True, False])
1179
+ # b = t*a
1180
+ # assert_equal(b, [1.0, 0.0])
1181
+ # assert_equal(b.dtype, np.dtype('f4'))
1182
+ # b = (1-t)*a
1183
+ # assert_equal(b, [0.0, 1.5])
1184
+ # assert_equal(b.dtype, np.dtype('f4'))
1185
+ #
1186
+ # Probably ~t (bitwise negation) is more proper to use here,
1187
+ # but this is arguably less intuitive to understand at a glance, and
1188
+ # would fail if 't' is actually an integer array instead of boolean:
1189
+ #
1190
+ # b = (~t)*a
1191
+ # assert_equal(b, [0.0, 1.5])
1192
+ # assert_equal(b.dtype, np.dtype('f4'))
1193
+
1194
+ def test_result_type(self):
1195
+ self.check_promotion_cases(np.result_type)
1196
+ assert_(np.result_type(None) == np.dtype(None))
1197
+
1198
+ def test_promote_types_endian(self):
1199
+ # promote_types should always return native-endian types
1200
+ assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))
1201
+ assert_equal(np.promote_types('>i8', '>i8'), np.dtype('i8'))
1202
+
1203
+ assert_equal(np.promote_types('>i8', '>U16'), np.dtype('U21'))
1204
+ assert_equal(np.promote_types('<i8', '<U16'), np.dtype('U21'))
1205
+ assert_equal(np.promote_types('>U16', '>i8'), np.dtype('U21'))
1206
+ assert_equal(np.promote_types('<U16', '<i8'), np.dtype('U21'))
1207
+
1208
+ assert_equal(np.promote_types('<S5', '<U8'), np.dtype('U8'))
1209
+ assert_equal(np.promote_types('>S5', '>U8'), np.dtype('U8'))
1210
+ assert_equal(np.promote_types('<U8', '<S5'), np.dtype('U8'))
1211
+ assert_equal(np.promote_types('>U8', '>S5'), np.dtype('U8'))
1212
+ assert_equal(np.promote_types('<U5', '<U8'), np.dtype('U8'))
1213
+ assert_equal(np.promote_types('>U8', '>U5'), np.dtype('U8'))
1214
+
1215
+ assert_equal(np.promote_types('<M8', '<M8'), np.dtype('M8'))
1216
+ assert_equal(np.promote_types('>M8', '>M8'), np.dtype('M8'))
1217
+ assert_equal(np.promote_types('<m8', '<m8'), np.dtype('m8'))
1218
+ assert_equal(np.promote_types('>m8', '>m8'), np.dtype('m8'))
1219
+
1220
+ def test_can_cast_and_promote_usertypes(self):
1221
+ # The rational type defines safe casting for signed integers,
1222
+ # boolean. Rational itself *does* cast safely to double.
1223
+ # (rational does not actually cast to all signed integers, e.g.
1224
+ # int64 can be both long and longlong and it registers only the first)
1225
+ valid_types = ["int8", "int16", "int32", "int64", "bool"]
1226
+ invalid_types = "BHILQP" + "FDG" + "mM" + "f" + "V"
1227
+
1228
+ rational_dt = np.dtype(rational)
1229
+ for numpy_dtype in valid_types:
1230
+ numpy_dtype = np.dtype(numpy_dtype)
1231
+ assert np.can_cast(numpy_dtype, rational_dt)
1232
+ assert np.promote_types(numpy_dtype, rational_dt) is rational_dt
1233
+
1234
+ for numpy_dtype in invalid_types:
1235
+ numpy_dtype = np.dtype(numpy_dtype)
1236
+ assert not np.can_cast(numpy_dtype, rational_dt)
1237
+ with pytest.raises(TypeError):
1238
+ np.promote_types(numpy_dtype, rational_dt)
1239
+
1240
+ double_dt = np.dtype("double")
1241
+ assert np.can_cast(rational_dt, double_dt)
1242
+ assert np.promote_types(double_dt, rational_dt) is double_dt
1243
+
1244
+ @pytest.mark.parametrize("swap", ["", "swap"])
1245
+ @pytest.mark.parametrize("string_dtype", ["U", "S"])
1246
+ def test_promote_types_strings(self, swap, string_dtype):
1247
+ if swap == "swap":
1248
+ promote_types = lambda a, b: np.promote_types(b, a)
1249
+ else:
1250
+ promote_types = np.promote_types
1251
+
1252
+ S = string_dtype
1253
+
1254
+ # Promote numeric with unsized string:
1255
+ assert_equal(promote_types('bool', S), np.dtype(S + '5'))
1256
+ assert_equal(promote_types('b', S), np.dtype(S + '4'))
1257
+ assert_equal(promote_types('u1', S), np.dtype(S + '3'))
1258
+ assert_equal(promote_types('u2', S), np.dtype(S + '5'))
1259
+ assert_equal(promote_types('u4', S), np.dtype(S + '10'))
1260
+ assert_equal(promote_types('u8', S), np.dtype(S + '20'))
1261
+ assert_equal(promote_types('i1', S), np.dtype(S + '4'))
1262
+ assert_equal(promote_types('i2', S), np.dtype(S + '6'))
1263
+ assert_equal(promote_types('i4', S), np.dtype(S + '11'))
1264
+ assert_equal(promote_types('i8', S), np.dtype(S + '21'))
1265
+ # Promote numeric with sized string:
1266
+ assert_equal(promote_types('bool', S + '1'), np.dtype(S + '5'))
1267
+ assert_equal(promote_types('bool', S + '30'), np.dtype(S + '30'))
1268
+ assert_equal(promote_types('b', S + '1'), np.dtype(S + '4'))
1269
+ assert_equal(promote_types('b', S + '30'), np.dtype(S + '30'))
1270
+ assert_equal(promote_types('u1', S + '1'), np.dtype(S + '3'))
1271
+ assert_equal(promote_types('u1', S + '30'), np.dtype(S + '30'))
1272
+ assert_equal(promote_types('u2', S + '1'), np.dtype(S + '5'))
1273
+ assert_equal(promote_types('u2', S + '30'), np.dtype(S + '30'))
1274
+ assert_equal(promote_types('u4', S + '1'), np.dtype(S + '10'))
1275
+ assert_equal(promote_types('u4', S + '30'), np.dtype(S + '30'))
1276
+ assert_equal(promote_types('u8', S + '1'), np.dtype(S + '20'))
1277
+ assert_equal(promote_types('u8', S + '30'), np.dtype(S + '30'))
1278
+ # Promote with object:
1279
+ assert_equal(promote_types('O', S + '30'), np.dtype('O'))
1280
+
1281
+ @pytest.mark.parametrize(["dtype1", "dtype2"],
1282
+ [[np.dtype("V6"), np.dtype("V10")], # mismatch shape
1283
+ # Mismatching names:
1284
+ [np.dtype([("name1", "i8")]), np.dtype([("name2", "i8")])],
1285
+ ])
1286
+ def test_invalid_void_promotion(self, dtype1, dtype2):
1287
+ with pytest.raises(TypeError):
1288
+ np.promote_types(dtype1, dtype2)
1289
+
1290
+ @pytest.mark.parametrize(["dtype1", "dtype2"],
1291
+ [[np.dtype("V10"), np.dtype("V10")],
1292
+ [np.dtype([("name1", "i8")]),
1293
+ np.dtype([("name1", np.dtype("i8").newbyteorder())])],
1294
+ [np.dtype("i8,i8"), np.dtype("i8,>i8")],
1295
+ [np.dtype("i8,i8"), np.dtype("i4,i4")],
1296
+ ])
1297
+ def test_valid_void_promotion(self, dtype1, dtype2):
1298
+ assert np.promote_types(dtype1, dtype2) == dtype1
1299
+
1300
+ @pytest.mark.parametrize("dtype",
1301
+ list(np.typecodes["All"]) +
1302
+ ["i,i", "10i", "S3", "S100", "U3", "U100", rational])
1303
+ def test_promote_identical_types_metadata(self, dtype):
1304
+ # The same type passed in twice to promote types always
1305
+ # preserves metadata
1306
+ metadata = {1: 1}
1307
+ dtype = np.dtype(dtype, metadata=metadata)
1308
+
1309
+ res = np.promote_types(dtype, dtype)
1310
+ assert res.metadata == dtype.metadata
1311
+
1312
+ # byte-swapping preserves and makes the dtype native:
1313
+ dtype = dtype.newbyteorder()
1314
+ if dtype.isnative:
1315
+ # The type does not have byte swapping
1316
+ return
1317
+
1318
+ res = np.promote_types(dtype, dtype)
1319
+
1320
+ # Metadata is (currently) generally lost on byte-swapping (except for
1321
+ # unicode.
1322
+ if dtype.char != "U":
1323
+ assert res.metadata is None
1324
+ else:
1325
+ assert res.metadata == metadata
1326
+ assert res.isnative
1327
+
1328
+ @pytest.mark.slow
1329
+ @pytest.mark.filterwarnings('ignore:Promotion of numbers:FutureWarning')
1330
+ @pytest.mark.parametrize(["dtype1", "dtype2"],
1331
+ itertools.product(
1332
+ list(np.typecodes["All"]) +
1333
+ ["i,i", "S3", "S100", "U3", "U100", rational],
1334
+ repeat=2))
1335
+ def test_promote_types_metadata(self, dtype1, dtype2):
1336
+ """Metadata handling in promotion does not appear formalized
1337
+ right now in NumPy. This test should thus be considered to
1338
+ document behaviour, rather than test the correct definition of it.
1339
+
1340
+ This test is very ugly, it was useful for rewriting part of the
1341
+ promotion, but probably should eventually be replaced/deleted
1342
+ (i.e. when metadata handling in promotion is better defined).
1343
+ """
1344
+ metadata1 = {1: 1}
1345
+ metadata2 = {2: 2}
1346
+ dtype1 = np.dtype(dtype1, metadata=metadata1)
1347
+ dtype2 = np.dtype(dtype2, metadata=metadata2)
1348
+
1349
+ try:
1350
+ res = np.promote_types(dtype1, dtype2)
1351
+ except TypeError:
1352
+ # Promotion failed, this test only checks metadata
1353
+ return
1354
+
1355
+ if res.char not in "USV" or res.names is not None or res.shape != ():
1356
+ # All except string dtypes (and unstructured void) lose metadata
1357
+ # on promotion (unless both dtypes are identical).
1358
+ # At some point structured ones did not, but were restrictive.
1359
+ assert res.metadata is None
1360
+ elif res == dtype1:
1361
+ # If one result is the result, it is usually returned unchanged:
1362
+ assert res is dtype1
1363
+ elif res == dtype2:
1364
+ # dtype1 may have been cast to the same type/kind as dtype2.
1365
+ # If the resulting dtype is identical we currently pick the cast
1366
+ # version of dtype1, which lost the metadata:
1367
+ if np.promote_types(dtype1, dtype2.kind) == dtype2:
1368
+ res.metadata is None
1369
+ else:
1370
+ res.metadata == metadata2
1371
+ else:
1372
+ assert res.metadata is None
1373
+
1374
+ # Try again for byteswapped version
1375
+ dtype1 = dtype1.newbyteorder()
1376
+ assert dtype1.metadata == metadata1
1377
+ res_bs = np.promote_types(dtype1, dtype2)
1378
+ assert res_bs == res
1379
+ assert res_bs.metadata == res.metadata
1380
+
1381
+ def test_can_cast(self):
1382
+ assert_(np.can_cast(np.int32, np.int64))
1383
+ assert_(np.can_cast(np.float64, complex))
1384
+ assert_(not np.can_cast(complex, float))
1385
+
1386
+ assert_(np.can_cast('i8', 'f8'))
1387
+ assert_(not np.can_cast('i8', 'f4'))
1388
+ assert_(np.can_cast('i4', 'S11'))
1389
+
1390
+ assert_(np.can_cast('i8', 'i8', 'no'))
1391
+ assert_(not np.can_cast('<i8', '>i8', 'no'))
1392
+
1393
+ assert_(np.can_cast('<i8', '>i8', 'equiv'))
1394
+ assert_(not np.can_cast('<i4', '>i8', 'equiv'))
1395
+
1396
+ assert_(np.can_cast('<i4', '>i8', 'safe'))
1397
+ assert_(not np.can_cast('<i8', '>i4', 'safe'))
1398
+
1399
+ assert_(np.can_cast('<i8', '>i4', 'same_kind'))
1400
+ assert_(not np.can_cast('<i8', '>u4', 'same_kind'))
1401
+
1402
+ assert_(np.can_cast('<i8', '>u4', 'unsafe'))
1403
+
1404
+ assert_(np.can_cast('bool', 'S5'))
1405
+ assert_(not np.can_cast('bool', 'S4'))
1406
+
1407
+ assert_(np.can_cast('b', 'S4'))
1408
+ assert_(not np.can_cast('b', 'S3'))
1409
+
1410
+ assert_(np.can_cast('u1', 'S3'))
1411
+ assert_(not np.can_cast('u1', 'S2'))
1412
+ assert_(np.can_cast('u2', 'S5'))
1413
+ assert_(not np.can_cast('u2', 'S4'))
1414
+ assert_(np.can_cast('u4', 'S10'))
1415
+ assert_(not np.can_cast('u4', 'S9'))
1416
+ assert_(np.can_cast('u8', 'S20'))
1417
+ assert_(not np.can_cast('u8', 'S19'))
1418
+
1419
+ assert_(np.can_cast('i1', 'S4'))
1420
+ assert_(not np.can_cast('i1', 'S3'))
1421
+ assert_(np.can_cast('i2', 'S6'))
1422
+ assert_(not np.can_cast('i2', 'S5'))
1423
+ assert_(np.can_cast('i4', 'S11'))
1424
+ assert_(not np.can_cast('i4', 'S10'))
1425
+ assert_(np.can_cast('i8', 'S21'))
1426
+ assert_(not np.can_cast('i8', 'S20'))
1427
+
1428
+ assert_(np.can_cast('bool', 'S5'))
1429
+ assert_(not np.can_cast('bool', 'S4'))
1430
+
1431
+ assert_(np.can_cast('b', 'U4'))
1432
+ assert_(not np.can_cast('b', 'U3'))
1433
+
1434
+ assert_(np.can_cast('u1', 'U3'))
1435
+ assert_(not np.can_cast('u1', 'U2'))
1436
+ assert_(np.can_cast('u2', 'U5'))
1437
+ assert_(not np.can_cast('u2', 'U4'))
1438
+ assert_(np.can_cast('u4', 'U10'))
1439
+ assert_(not np.can_cast('u4', 'U9'))
1440
+ assert_(np.can_cast('u8', 'U20'))
1441
+ assert_(not np.can_cast('u8', 'U19'))
1442
+
1443
+ assert_(np.can_cast('i1', 'U4'))
1444
+ assert_(not np.can_cast('i1', 'U3'))
1445
+ assert_(np.can_cast('i2', 'U6'))
1446
+ assert_(not np.can_cast('i2', 'U5'))
1447
+ assert_(np.can_cast('i4', 'U11'))
1448
+ assert_(not np.can_cast('i4', 'U10'))
1449
+ assert_(np.can_cast('i8', 'U21'))
1450
+ assert_(not np.can_cast('i8', 'U20'))
1451
+
1452
+ assert_raises(TypeError, np.can_cast, 'i4', None)
1453
+ assert_raises(TypeError, np.can_cast, None, 'i4')
1454
+
1455
+ # Also test keyword arguments
1456
+ assert_(np.can_cast(from_=np.int32, to=np.int64))
1457
+
1458
+ def test_can_cast_simple_to_structured(self):
1459
+ # Non-structured can only be cast to structured in 'unsafe' mode.
1460
+ assert_(not np.can_cast('i4', 'i4,i4'))
1461
+ assert_(not np.can_cast('i4', 'i4,i2'))
1462
+ assert_(np.can_cast('i4', 'i4,i4', casting='unsafe'))
1463
+ assert_(np.can_cast('i4', 'i4,i2', casting='unsafe'))
1464
+ # Even if there is just a single field which is OK.
1465
+ assert_(not np.can_cast('i2', [('f1', 'i4')]))
1466
+ assert_(not np.can_cast('i2', [('f1', 'i4')], casting='same_kind'))
1467
+ assert_(np.can_cast('i2', [('f1', 'i4')], casting='unsafe'))
1468
+ # It should be the same for recursive structured or subarrays.
1469
+ assert_(not np.can_cast('i2', [('f1', 'i4,i4')]))
1470
+ assert_(np.can_cast('i2', [('f1', 'i4,i4')], casting='unsafe'))
1471
+ assert_(not np.can_cast('i2', [('f1', '(2,3)i4')]))
1472
+ assert_(np.can_cast('i2', [('f1', '(2,3)i4')], casting='unsafe'))
1473
+
1474
+ def test_can_cast_structured_to_simple(self):
1475
+ # Need unsafe casting for structured to simple.
1476
+ assert_(not np.can_cast([('f1', 'i4')], 'i4'))
1477
+ assert_(np.can_cast([('f1', 'i4')], 'i4', casting='unsafe'))
1478
+ assert_(np.can_cast([('f1', 'i4')], 'i2', casting='unsafe'))
1479
+ # Since it is unclear what is being cast, multiple fields to
1480
+ # single should not work even for unsafe casting.
1481
+ assert_(not np.can_cast('i4,i4', 'i4', casting='unsafe'))
1482
+ # But a single field inside a single field is OK.
1483
+ assert_(not np.can_cast([('f1', [('x', 'i4')])], 'i4'))
1484
+ assert_(np.can_cast([('f1', [('x', 'i4')])], 'i4', casting='unsafe'))
1485
+ # And a subarray is fine too - it will just take the first element
1486
+ # (arguably not very consistently; might also take the first field).
1487
+ assert_(not np.can_cast([('f0', '(3,)i4')], 'i4'))
1488
+ assert_(np.can_cast([('f0', '(3,)i4')], 'i4', casting='unsafe'))
1489
+ # But a structured subarray with multiple fields should fail.
1490
+ assert_(not np.can_cast([('f0', ('i4,i4'), (2,))], 'i4',
1491
+ casting='unsafe'))
1492
+
1493
+ def test_can_cast_values(self):
1494
+ # With NumPy 2 and NEP 50, can_cast errors on Python scalars. We could
1495
+ # define this as (usually safe) at some point, and already do so
1496
+ # in `copyto` and ufuncs (but there an error is raised if the integer
1497
+ # is out of bounds and a warning for out-of-bound floats).
1498
+ # Raises even for unsafe, previously checked within range (for floats
1499
+ # that was approximately whether it would overflow to inf).
1500
+ with pytest.raises(TypeError):
1501
+ np.can_cast(4, "int8", casting="unsafe")
1502
+
1503
+ with pytest.raises(TypeError):
1504
+ np.can_cast(4.0, "float64", casting="unsafe")
1505
+
1506
+ with pytest.raises(TypeError):
1507
+ np.can_cast(4j, "complex128", casting="unsafe")
1508
+
1509
+ @pytest.mark.parametrize("dtype",
1510
+ list("?bhilqBHILQefdgFDG") + [rational])
1511
+ def test_can_cast_scalars(self, dtype):
1512
+ # Basic test to ensure that scalars are supported in can-cast
1513
+ # (does not check behavior exhaustively).
1514
+ dtype = np.dtype(dtype)
1515
+ scalar = dtype.type(0)
1516
+
1517
+ assert np.can_cast(scalar, "int64") == np.can_cast(dtype, "int64")
1518
+ assert np.can_cast(scalar, "float32", casting="unsafe")
1519
+
1520
+
1521
+ # Custom exception class to test exception propagation in fromiter
1522
+ class NIterError(Exception):
1523
+ pass
1524
+
1525
+
1526
+ class TestFromiter:
1527
+ def makegen(self):
1528
+ return (x**2 for x in range(24))
1529
+
1530
+ def test_types(self):
1531
+ ai32 = np.fromiter(self.makegen(), np.int32)
1532
+ ai64 = np.fromiter(self.makegen(), np.int64)
1533
+ af = np.fromiter(self.makegen(), float)
1534
+ assert_(ai32.dtype == np.dtype(np.int32))
1535
+ assert_(ai64.dtype == np.dtype(np.int64))
1536
+ assert_(af.dtype == np.dtype(float))
1537
+
1538
+ def test_lengths(self):
1539
+ expected = np.array(list(self.makegen()))
1540
+ a = np.fromiter(self.makegen(), int)
1541
+ a20 = np.fromiter(self.makegen(), int, 20)
1542
+ assert_(len(a) == len(expected))
1543
+ assert_(len(a20) == 20)
1544
+ assert_raises(ValueError, np.fromiter,
1545
+ self.makegen(), int, len(expected) + 10)
1546
+
1547
+ def test_values(self):
1548
+ expected = np.array(list(self.makegen()))
1549
+ a = np.fromiter(self.makegen(), int)
1550
+ a20 = np.fromiter(self.makegen(), int, 20)
1551
+ assert_(np.all(a == expected, axis=0))
1552
+ assert_(np.all(a20 == expected[:20], axis=0))
1553
+
1554
+ def load_data(self, n, eindex):
1555
+ # Utility method for the issue 2592 tests.
1556
+ # Raise an exception at the desired index in the iterator.
1557
+ for e in range(n):
1558
+ if e == eindex:
1559
+ raise NIterError(f'error at index {eindex}')
1560
+ yield e
1561
+
1562
+ @pytest.mark.parametrize("dtype", [int, object])
1563
+ @pytest.mark.parametrize(["count", "error_index"], [(10, 5), (10, 9)])
1564
+ def test_2592(self, count, error_index, dtype):
1565
+ # Test iteration exceptions are correctly raised. The data/generator
1566
+ # has `count` elements but errors at `error_index`
1567
+ iterable = self.load_data(count, error_index)
1568
+ with pytest.raises(NIterError):
1569
+ np.fromiter(iterable, dtype=dtype, count=count)
1570
+
1571
+ @pytest.mark.parametrize("dtype", ["S", "S0", "V0", "U0"])
1572
+ def test_empty_not_structured(self, dtype):
1573
+ # Note, "S0" could be allowed at some point, so long "S" (without
1574
+ # any length) is rejected.
1575
+ with pytest.raises(ValueError, match="Must specify length"):
1576
+ np.fromiter([], dtype=dtype)
1577
+
1578
+ @pytest.mark.parametrize(["dtype", "data"],
1579
+ [("d", [1, 2, 3, 4, 5, 6, 7, 8, 9]),
1580
+ ("O", [1, 2, 3, 4, 5, 6, 7, 8, 9]),
1581
+ ("i,O", [(1, 2), (5, 4), (2, 3), (9, 8), (6, 7)]),
1582
+ # subarray dtypes (important because their dimensions end up
1583
+ # in the result arrays dimension:
1584
+ ("2i", [(1, 2), (5, 4), (2, 3), (9, 8), (6, 7)]),
1585
+ (np.dtype(("O", (2, 3))),
1586
+ [((1, 2, 3), (3, 4, 5)), ((3, 2, 1), (5, 4, 3))])])
1587
+ @pytest.mark.parametrize("length_hint", [0, 1])
1588
+ def test_growth_and_complicated_dtypes(self, dtype, data, length_hint):
1589
+ dtype = np.dtype(dtype)
1590
+
1591
+ data = data * 100 # make sure we realloc a bit
1592
+
1593
+ class MyIter:
1594
+ # Class/example from gh-15789
1595
+ def __length_hint__(self):
1596
+ # only required to be an estimate, this is legal
1597
+ return length_hint # 0 or 1
1598
+
1599
+ def __iter__(self):
1600
+ return iter(data)
1601
+
1602
+ res = np.fromiter(MyIter(), dtype=dtype)
1603
+ expected = np.array(data, dtype=dtype)
1604
+
1605
+ assert_array_equal(res, expected)
1606
+
1607
+ def test_empty_result(self):
1608
+ class MyIter:
1609
+ def __length_hint__(self):
1610
+ return 10
1611
+
1612
+ def __iter__(self):
1613
+ return iter([]) # actual iterator is empty.
1614
+
1615
+ res = np.fromiter(MyIter(), dtype="d")
1616
+ assert res.shape == (0,)
1617
+ assert res.dtype == "d"
1618
+
1619
+ def test_too_few_items(self):
1620
+ msg = "iterator too short: Expected 10 but iterator had only 3 items."
1621
+ with pytest.raises(ValueError, match=msg):
1622
+ np.fromiter([1, 2, 3], count=10, dtype=int)
1623
+
1624
+ def test_failed_itemsetting(self):
1625
+ with pytest.raises(TypeError):
1626
+ np.fromiter([1, None, 3], dtype=int)
1627
+
1628
+ # The following manages to hit somewhat trickier code paths:
1629
+ iterable = ((2, 3, 4) for i in range(5))
1630
+ with pytest.raises(ValueError):
1631
+ np.fromiter(iterable, dtype=np.dtype((int, 2)))
1632
+
1633
+
1634
+ class TestNonzero:
1635
+ def test_nonzero_trivial(self):
1636
+ assert_equal(np.count_nonzero(np.array([])), 0)
1637
+ assert_equal(np.count_nonzero(np.array([], dtype='?')), 0)
1638
+ assert_equal(np.nonzero(np.array([])), ([],))
1639
+
1640
+ assert_equal(np.count_nonzero(np.array([0])), 0)
1641
+ assert_equal(np.count_nonzero(np.array([0], dtype='?')), 0)
1642
+ assert_equal(np.nonzero(np.array([0])), ([],))
1643
+
1644
+ assert_equal(np.count_nonzero(np.array([1])), 1)
1645
+ assert_equal(np.count_nonzero(np.array([1], dtype='?')), 1)
1646
+ assert_equal(np.nonzero(np.array([1])), ([0],))
1647
+
1648
+ def test_nonzero_zerodim(self):
1649
+ err_msg = "Calling nonzero on 0d arrays is not allowed"
1650
+ with assert_raises_regex(ValueError, err_msg):
1651
+ np.nonzero(np.array(0))
1652
+ with assert_raises_regex(ValueError, err_msg):
1653
+ np.array(1).nonzero()
1654
+
1655
+ def test_nonzero_onedim(self):
1656
+ x = np.array([1, 0, 2, -1, 0, 0, 8])
1657
+ assert_equal(np.count_nonzero(x), 4)
1658
+ assert_equal(np.count_nonzero(x), 4)
1659
+ assert_equal(np.nonzero(x), ([0, 2, 3, 6],))
1660
+
1661
+ # x = np.array([(1, 2), (0, 0), (1, 1), (-1, 3), (0, 7)],
1662
+ # dtype=[('a', 'i4'), ('b', 'i2')])
1663
+ x = np.array(
1664
+ [(1, 2, -5, -3), (0, 0, 2, 7), (1, 1, 0, 1), (-1, 3, 1, 0), (0, 7, 0, 4)],
1665
+ dtype=[('a', 'i4'), ('b', 'i2'), ('c', 'i1'), ('d', 'i8')]
1666
+ )
1667
+ assert_equal(np.count_nonzero(x['a']), 3)
1668
+ assert_equal(np.count_nonzero(x['b']), 4)
1669
+ assert_equal(np.count_nonzero(x['c']), 3)
1670
+ assert_equal(np.count_nonzero(x['d']), 4)
1671
+ assert_equal(np.nonzero(x['a']), ([0, 2, 3],))
1672
+ assert_equal(np.nonzero(x['b']), ([0, 2, 3, 4],))
1673
+
1674
+ def test_nonzero_twodim(self):
1675
+ x = np.array([[0, 1, 0], [2, 0, 3]])
1676
+ assert_equal(np.count_nonzero(x.astype('i1')), 3)
1677
+ assert_equal(np.count_nonzero(x.astype('i2')), 3)
1678
+ assert_equal(np.count_nonzero(x.astype('i4')), 3)
1679
+ assert_equal(np.count_nonzero(x.astype('i8')), 3)
1680
+ assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2]))
1681
+
1682
+ x = np.eye(3)
1683
+ assert_equal(np.count_nonzero(x.astype('i1')), 3)
1684
+ assert_equal(np.count_nonzero(x.astype('i2')), 3)
1685
+ assert_equal(np.count_nonzero(x.astype('i4')), 3)
1686
+ assert_equal(np.count_nonzero(x.astype('i8')), 3)
1687
+ assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2]))
1688
+
1689
+ x = np.array([[(0, 1), (0, 0), (1, 11)],
1690
+ [(1, 1), (1, 0), (0, 0)],
1691
+ [(0, 0), (1, 5), (0, 1)]], dtype=[('a', 'f4'), ('b', 'u1')])
1692
+ assert_equal(np.count_nonzero(x['a']), 4)
1693
+ assert_equal(np.count_nonzero(x['b']), 5)
1694
+ assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1]))
1695
+ assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2]))
1696
+
1697
+ assert_(not x['a'].T.flags.aligned)
1698
+ assert_equal(np.count_nonzero(x['a'].T), 4)
1699
+ assert_equal(np.count_nonzero(x['b'].T), 5)
1700
+ assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0]))
1701
+ assert_equal(np.nonzero(x['b'].T), ([0, 0, 1, 2, 2], [0, 1, 2, 0, 2]))
1702
+
1703
+ def test_sparse(self):
1704
+ # test special sparse condition boolean code path
1705
+ for i in range(20):
1706
+ c = np.zeros(200, dtype=bool)
1707
+ c[i::20] = True
1708
+ assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20))
1709
+
1710
+ c = np.zeros(400, dtype=bool)
1711
+ c[10 + i:20 + i] = True
1712
+ c[20 + i * 2] = True
1713
+ assert_equal(np.nonzero(c)[0],
1714
+ np.concatenate((np.arange(10 + i, 20 + i), [20 + i * 2])))
1715
+
1716
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64])
1717
+ def test_nonzero_float_dtypes(self, dtype):
1718
+ rng = np.random.default_rng(seed=10)
1719
+ x = ((2**33) * rng.normal(size=100)).astype(dtype)
1720
+ x[rng.choice(50, size=100)] = 0
1721
+ idxs = np.nonzero(x)[0]
1722
+ assert_equal(np.array_equal(np.where(x != 0)[0], idxs), True)
1723
+
1724
+ @pytest.mark.parametrize('dtype', [bool, np.int8, np.int16, np.int32, np.int64,
1725
+ np.uint8, np.uint16, np.uint32, np.uint64])
1726
+ def test_nonzero_integer_dtypes(self, dtype):
1727
+ rng = np.random.default_rng(seed=10)
1728
+ x = rng.integers(0, 255, size=100).astype(dtype)
1729
+ x[rng.choice(50, size=100)] = 0
1730
+ idxs = np.nonzero(x)[0]
1731
+ assert_equal(np.array_equal(np.where(x != 0)[0], idxs), True)
1732
+
1733
+ def test_return_type(self):
1734
+ class C(np.ndarray):
1735
+ pass
1736
+
1737
+ for view in (C, np.ndarray):
1738
+ for nd in range(1, 4):
1739
+ shape = tuple(range(2, 2 + nd))
1740
+ x = np.arange(np.prod(shape)).reshape(shape).view(view)
1741
+ for nzx in (np.nonzero(x), x.nonzero()):
1742
+ for nzx_i in nzx:
1743
+ assert_(type(nzx_i) is np.ndarray)
1744
+ assert_(nzx_i.flags.writeable)
1745
+
1746
+ def test_count_nonzero_axis(self):
1747
+ # Basic check of functionality
1748
+ m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
1749
+
1750
+ expected = np.array([1, 1, 1, 1, 1])
1751
+ assert_equal(np.count_nonzero(m, axis=0), expected)
1752
+
1753
+ expected = np.array([2, 3])
1754
+ assert_equal(np.count_nonzero(m, axis=1), expected)
1755
+
1756
+ assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1))
1757
+ assert_raises(TypeError, np.count_nonzero, m, axis='foo')
1758
+ assert_raises(AxisError, np.count_nonzero, m, axis=3)
1759
+ assert_raises(TypeError, np.count_nonzero,
1760
+ m, axis=np.array([[1], [2]]))
1761
+
1762
+ def test_count_nonzero_axis_all_dtypes(self):
1763
+ # More thorough test that the axis argument is respected
1764
+ # for all dtypes and responds correctly when presented with
1765
+ # either integer or tuple arguments for axis
1766
+ msg = "Mismatch for dtype: %s"
1767
+
1768
+ def assert_equal_w_dt(a, b, err_msg):
1769
+ assert_equal(a.dtype, b.dtype, err_msg=err_msg)
1770
+ assert_equal(a, b, err_msg=err_msg)
1771
+
1772
+ for dt in np.typecodes['All']:
1773
+ err_msg = msg % (np.dtype(dt).name,)
1774
+
1775
+ if dt != 'V':
1776
+ if dt != 'M':
1777
+ m = np.zeros((3, 3), dtype=dt)
1778
+ n = np.ones(1, dtype=dt)
1779
+
1780
+ m[0, 0] = n[0]
1781
+ m[1, 0] = n[0]
1782
+
1783
+ else: # np.zeros doesn't work for np.datetime64
1784
+ m = np.array(['1970-01-01'] * 9)
1785
+ m = m.reshape((3, 3))
1786
+
1787
+ m[0, 0] = '1970-01-12'
1788
+ m[1, 0] = '1970-01-12'
1789
+ m = m.astype(dt)
1790
+
1791
+ expected = np.array([2, 0, 0], dtype=np.intp)
1792
+ assert_equal_w_dt(np.count_nonzero(m, axis=0),
1793
+ expected, err_msg=err_msg)
1794
+
1795
+ expected = np.array([1, 1, 0], dtype=np.intp)
1796
+ assert_equal_w_dt(np.count_nonzero(m, axis=1),
1797
+ expected, err_msg=err_msg)
1798
+
1799
+ expected = np.array(2)
1800
+ assert_equal(np.count_nonzero(m, axis=(0, 1)),
1801
+ expected, err_msg=err_msg)
1802
+ assert_equal(np.count_nonzero(m, axis=None),
1803
+ expected, err_msg=err_msg)
1804
+ assert_equal(np.count_nonzero(m),
1805
+ expected, err_msg=err_msg)
1806
+
1807
+ if dt == 'V':
1808
+ # There are no 'nonzero' objects for np.void, so the testing
1809
+ # setup is slightly different for this dtype
1810
+ m = np.array([np.void(1)] * 6).reshape((2, 3))
1811
+
1812
+ expected = np.array([0, 0, 0], dtype=np.intp)
1813
+ assert_equal_w_dt(np.count_nonzero(m, axis=0),
1814
+ expected, err_msg=err_msg)
1815
+
1816
+ expected = np.array([0, 0], dtype=np.intp)
1817
+ assert_equal_w_dt(np.count_nonzero(m, axis=1),
1818
+ expected, err_msg=err_msg)
1819
+
1820
+ expected = np.array(0)
1821
+ assert_equal(np.count_nonzero(m, axis=(0, 1)),
1822
+ expected, err_msg=err_msg)
1823
+ assert_equal(np.count_nonzero(m, axis=None),
1824
+ expected, err_msg=err_msg)
1825
+ assert_equal(np.count_nonzero(m),
1826
+ expected, err_msg=err_msg)
1827
+
1828
+ def test_count_nonzero_axis_consistent(self):
1829
+ # Check that the axis behaviour for valid axes in
1830
+ # non-special cases is consistent (and therefore
1831
+ # correct) by checking it against an integer array
1832
+ # that is then casted to the generic object dtype
1833
+ from itertools import combinations, permutations
1834
+
1835
+ axis = (0, 1, 2, 3)
1836
+ size = (5, 5, 5, 5)
1837
+ msg = "Mismatch for axis: %s"
1838
+
1839
+ rng = np.random.RandomState(1234)
1840
+ m = rng.randint(-100, 100, size=size)
1841
+ n = m.astype(object)
1842
+
1843
+ for length in range(len(axis)):
1844
+ for combo in combinations(axis, length):
1845
+ for perm in permutations(combo):
1846
+ assert_equal(
1847
+ np.count_nonzero(m, axis=perm),
1848
+ np.count_nonzero(n, axis=perm),
1849
+ err_msg=msg % (perm,))
1850
+
1851
+ def test_countnonzero_axis_empty(self):
1852
+ a = np.array([[0, 0, 1], [1, 0, 1]])
1853
+ assert_equal(np.count_nonzero(a, axis=()), a.astype(bool))
1854
+
1855
+ def test_countnonzero_keepdims(self):
1856
+ a = np.array([[0, 0, 1, 0],
1857
+ [0, 3, 5, 0],
1858
+ [7, 9, 2, 0]])
1859
+ assert_equal(np.count_nonzero(a, axis=0, keepdims=True),
1860
+ [[1, 2, 3, 0]])
1861
+ assert_equal(np.count_nonzero(a, axis=1, keepdims=True),
1862
+ [[1], [2], [3]])
1863
+ assert_equal(np.count_nonzero(a, keepdims=True),
1864
+ [[6]])
1865
+
1866
+ def test_array_method(self):
1867
+ # Tests that the array method
1868
+ # call to nonzero works
1869
+ m = np.array([[1, 0, 0], [4, 0, 6]])
1870
+ tgt = [[0, 1, 1], [0, 0, 2]]
1871
+
1872
+ assert_equal(m.nonzero(), tgt)
1873
+
1874
+ def test_nonzero_invalid_object(self):
1875
+ # gh-9295
1876
+ a = np.array([np.array([1, 2]), 3], dtype=object)
1877
+ assert_raises(ValueError, np.nonzero, a)
1878
+
1879
+ class BoolErrors:
1880
+ def __bool__(self):
1881
+ raise ValueError("Not allowed")
1882
+
1883
+ assert_raises(ValueError, np.nonzero, np.array([BoolErrors()]))
1884
+
1885
+ def test_nonzero_sideeffect_safety(self):
1886
+ # gh-13631
1887
+ class FalseThenTrue:
1888
+ _val = False
1889
+
1890
+ def __bool__(self):
1891
+ try:
1892
+ return self._val
1893
+ finally:
1894
+ self._val = True
1895
+
1896
+ class TrueThenFalse:
1897
+ _val = True
1898
+
1899
+ def __bool__(self):
1900
+ try:
1901
+ return self._val
1902
+ finally:
1903
+ self._val = False
1904
+
1905
+ # result grows on the second pass
1906
+ a = np.array([True, FalseThenTrue()])
1907
+ assert_raises(RuntimeError, np.nonzero, a)
1908
+
1909
+ a = np.array([[True], [FalseThenTrue()]])
1910
+ assert_raises(RuntimeError, np.nonzero, a)
1911
+
1912
+ # result shrinks on the second pass
1913
+ a = np.array([False, TrueThenFalse()])
1914
+ assert_raises(RuntimeError, np.nonzero, a)
1915
+
1916
+ a = np.array([[False], [TrueThenFalse()]])
1917
+ assert_raises(RuntimeError, np.nonzero, a)
1918
+
1919
+ def test_nonzero_sideffects_structured_void(self):
1920
+ # Checks that structured void does not mutate alignment flag of
1921
+ # original array.
1922
+ arr = np.zeros(5, dtype="i1,i8,i8") # `ones` may short-circuit
1923
+ assert arr.flags.aligned # structs are considered "aligned"
1924
+ assert not arr["f2"].flags.aligned
1925
+ # make sure that nonzero/count_nonzero do not flip the flag:
1926
+ np.nonzero(arr)
1927
+ assert arr.flags.aligned
1928
+ np.count_nonzero(arr)
1929
+ assert arr.flags.aligned
1930
+
1931
+ def test_nonzero_exception_safe(self):
1932
+ # gh-13930
1933
+
1934
+ class ThrowsAfter:
1935
+ def __init__(self, iters):
1936
+ self.iters_left = iters
1937
+
1938
+ def __bool__(self):
1939
+ if self.iters_left == 0:
1940
+ raise ValueError("called `iters` times")
1941
+
1942
+ self.iters_left -= 1
1943
+ return True
1944
+
1945
+ """
1946
+ Test that a ValueError is raised instead of a SystemError
1947
+
1948
+ If the __bool__ function is called after the error state is set,
1949
+ Python (cpython) will raise a SystemError.
1950
+ """
1951
+
1952
+ # assert that an exception in first pass is handled correctly
1953
+ a = np.array([ThrowsAfter(5)] * 10)
1954
+ assert_raises(ValueError, np.nonzero, a)
1955
+
1956
+ # raise exception in second pass for 1-dimensional loop
1957
+ a = np.array([ThrowsAfter(15)] * 10)
1958
+ assert_raises(ValueError, np.nonzero, a)
1959
+
1960
+ # raise exception in second pass for n-dimensional loop
1961
+ a = np.array([[ThrowsAfter(15)]] * 10)
1962
+ assert_raises(ValueError, np.nonzero, a)
1963
+
1964
+ def test_nonzero_byteorder(self):
1965
+ values = [0., -0., 1, float('nan'), 0, 1,
1966
+ np.float16(0), np.float16(12.3)]
1967
+ expected_values = [0, 0, 1, 1, 0, 1, 0, 1]
1968
+
1969
+ for value, expected in zip(values, expected_values):
1970
+ A = np.array([value])
1971
+ A_byteswapped = (A.view(A.dtype.newbyteorder()).byteswap()).copy()
1972
+
1973
+ assert np.count_nonzero(A) == expected
1974
+ assert np.count_nonzero(A_byteswapped) == expected
1975
+
1976
+ def test_count_nonzero_non_aligned_array(self):
1977
+ # gh-27523
1978
+ b = np.zeros(64 + 1, dtype=np.int8)[1:]
1979
+ b = b.view(int)
1980
+ b[:] = np.arange(b.size)
1981
+ b[::2] = 0
1982
+ assert b.flags.aligned is False
1983
+ assert np.count_nonzero(b) == b.size / 2
1984
+
1985
+ b = np.zeros(64 + 1, dtype=np.float16)[1:]
1986
+ b = b.view(float)
1987
+ b[:] = np.arange(b.size)
1988
+ b[::2] = 0
1989
+ assert b.flags.aligned is False
1990
+ assert np.count_nonzero(b) == b.size / 2
1991
+
1992
+
1993
+ class TestIndex:
1994
+ def test_boolean(self):
1995
+ a = rand(3, 5, 8)
1996
+ V = rand(5, 8)
1997
+ g1 = randint(0, 5, size=15)
1998
+ g2 = randint(0, 8, size=15)
1999
+ V[g1, g2] = -V[g1, g2]
2000
+ assert_(
2001
+ (np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all()
2002
+ )
2003
+
2004
+ def test_boolean_edgecase(self):
2005
+ a = np.array([], dtype='int32')
2006
+ b = np.array([], dtype='bool')
2007
+ c = a[b]
2008
+ assert_equal(c, [])
2009
+ assert_equal(c.dtype, np.dtype('int32'))
2010
+
2011
+
2012
+ class TestBinaryRepr:
2013
+ def test_zero(self):
2014
+ assert_equal(np.binary_repr(0), '0')
2015
+
2016
+ def test_positive(self):
2017
+ assert_equal(np.binary_repr(10), '1010')
2018
+ assert_equal(np.binary_repr(12522),
2019
+ '11000011101010')
2020
+ assert_equal(np.binary_repr(10736848),
2021
+ '101000111101010011010000')
2022
+
2023
+ def test_negative(self):
2024
+ assert_equal(np.binary_repr(-1), '-1')
2025
+ assert_equal(np.binary_repr(-10), '-1010')
2026
+ assert_equal(np.binary_repr(-12522),
2027
+ '-11000011101010')
2028
+ assert_equal(np.binary_repr(-10736848),
2029
+ '-101000111101010011010000')
2030
+
2031
+ def test_sufficient_width(self):
2032
+ assert_equal(np.binary_repr(0, width=5), '00000')
2033
+ assert_equal(np.binary_repr(10, width=7), '0001010')
2034
+ assert_equal(np.binary_repr(-5, width=7), '1111011')
2035
+
2036
+ def test_neg_width_boundaries(self):
2037
+ # see gh-8670
2038
+
2039
+ # Ensure that the example in the issue does not
2040
+ # break before proceeding to a more thorough test.
2041
+ assert_equal(np.binary_repr(-128, width=8), '10000000')
2042
+
2043
+ for width in range(1, 11):
2044
+ num = -2**(width - 1)
2045
+ exp = '1' + (width - 1) * '0'
2046
+ assert_equal(np.binary_repr(num, width=width), exp)
2047
+
2048
+ def test_large_neg_int64(self):
2049
+ # See gh-14289.
2050
+ assert_equal(np.binary_repr(np.int64(-2**62), width=64),
2051
+ '11' + '0' * 62)
2052
+
2053
+
2054
+ class TestBaseRepr:
2055
+ def test_base3(self):
2056
+ assert_equal(np.base_repr(3**5, 3), '100000')
2057
+
2058
+ def test_positive(self):
2059
+ assert_equal(np.base_repr(12, 10), '12')
2060
+ assert_equal(np.base_repr(12, 10, 4), '000012')
2061
+ assert_equal(np.base_repr(12, 4), '30')
2062
+ assert_equal(np.base_repr(3731624803700888, 36), '10QR0ROFCEW')
2063
+
2064
+ def test_negative(self):
2065
+ assert_equal(np.base_repr(-12, 10), '-12')
2066
+ assert_equal(np.base_repr(-12, 10, 4), '-000012')
2067
+ assert_equal(np.base_repr(-12, 4), '-30')
2068
+
2069
+ def test_base_range(self):
2070
+ with assert_raises(ValueError):
2071
+ np.base_repr(1, 1)
2072
+ with assert_raises(ValueError):
2073
+ np.base_repr(1, 37)
2074
+
2075
+ def test_minimal_signed_int(self):
2076
+ assert_equal(np.base_repr(np.int8(-128)), '-10000000')
2077
+
2078
+
2079
+ def _test_array_equal_parametrizations():
2080
+ """
2081
+ we pre-create arrays as we sometime want to pass the same instance
2082
+ and sometime not. Passing the same instances may not mean the array are
2083
+ equal, especially when containing None
2084
+ """
2085
+ # those are 0-d arrays, it used to be a special case
2086
+ # where (e0 == e0).all() would raise
2087
+ e0 = np.array(0, dtype="int")
2088
+ e1 = np.array(1, dtype="float")
2089
+ # x,y, nan_equal, expected_result
2090
+ yield (e0, e0.copy(), None, True)
2091
+ yield (e0, e0.copy(), False, True)
2092
+ yield (e0, e0.copy(), True, True)
2093
+
2094
+ #
2095
+ yield (e1, e1.copy(), None, True)
2096
+ yield (e1, e1.copy(), False, True)
2097
+ yield (e1, e1.copy(), True, True)
2098
+
2099
+ # Non-nanable - those cannot hold nans
2100
+ a12 = np.array([1, 2])
2101
+ a12b = a12.copy()
2102
+ a123 = np.array([1, 2, 3])
2103
+ a13 = np.array([1, 3])
2104
+ a34 = np.array([3, 4])
2105
+
2106
+ aS1 = np.array(["a"], dtype="S1")
2107
+ aS1b = aS1.copy()
2108
+ aS1u4 = np.array([("a", 1)], dtype="S1,u4")
2109
+ aS1u4b = aS1u4.copy()
2110
+
2111
+ yield (a12, a12b, None, True)
2112
+ yield (a12, a12, None, True)
2113
+ yield (a12, a123, None, False)
2114
+ yield (a12, a34, None, False)
2115
+ yield (a12, a13, None, False)
2116
+ yield (aS1, aS1b, None, True)
2117
+ yield (aS1, aS1, None, True)
2118
+
2119
+ # Non-float dtype - equal_nan should have no effect,
2120
+ yield (a123, a123, None, True)
2121
+ yield (a123, a123, False, True)
2122
+ yield (a123, a123, True, True)
2123
+ yield (a123, a123.copy(), None, True)
2124
+ yield (a123, a123.copy(), False, True)
2125
+ yield (a123, a123.copy(), True, True)
2126
+ yield (a123.astype("float"), a123.astype("float"), None, True)
2127
+ yield (a123.astype("float"), a123.astype("float"), False, True)
2128
+ yield (a123.astype("float"), a123.astype("float"), True, True)
2129
+
2130
+ # these can hold None
2131
+ b1 = np.array([1, 2, np.nan])
2132
+ b2 = np.array([1, np.nan, 2])
2133
+ b3 = np.array([1, 2, np.inf])
2134
+ b4 = np.array(np.nan)
2135
+
2136
+ # instances are the same
2137
+ yield (b1, b1, None, False)
2138
+ yield (b1, b1, False, False)
2139
+ yield (b1, b1, True, True)
2140
+
2141
+ # equal but not same instance
2142
+ yield (b1, b1.copy(), None, False)
2143
+ yield (b1, b1.copy(), False, False)
2144
+ yield (b1, b1.copy(), True, True)
2145
+
2146
+ # same once stripped of Nan
2147
+ yield (b1, b2, None, False)
2148
+ yield (b1, b2, False, False)
2149
+ yield (b1, b2, True, False)
2150
+
2151
+ # nan's not conflated with inf's
2152
+ yield (b1, b3, None, False)
2153
+ yield (b1, b3, False, False)
2154
+ yield (b1, b3, True, False)
2155
+
2156
+ # all Nan
2157
+ yield (b4, b4, None, False)
2158
+ yield (b4, b4, False, False)
2159
+ yield (b4, b4, True, True)
2160
+ yield (b4, b4.copy(), None, False)
2161
+ yield (b4, b4.copy(), False, False)
2162
+ yield (b4, b4.copy(), True, True)
2163
+
2164
+ t1 = b1.astype("timedelta64")
2165
+ t2 = b2.astype("timedelta64")
2166
+
2167
+ # Timedeltas are particular
2168
+ yield (t1, t1, None, False)
2169
+ yield (t1, t1, False, False)
2170
+ yield (t1, t1, True, True)
2171
+
2172
+ yield (t1, t1.copy(), None, False)
2173
+ yield (t1, t1.copy(), False, False)
2174
+ yield (t1, t1.copy(), True, True)
2175
+
2176
+ yield (t1, t2, None, False)
2177
+ yield (t1, t2, False, False)
2178
+ yield (t1, t2, True, False)
2179
+
2180
+ # Multi-dimensional array
2181
+ md1 = np.array([[0, 1], [np.nan, 1]])
2182
+
2183
+ yield (md1, md1, None, False)
2184
+ yield (md1, md1, False, False)
2185
+ yield (md1, md1, True, True)
2186
+ yield (md1, md1.copy(), None, False)
2187
+ yield (md1, md1.copy(), False, False)
2188
+ yield (md1, md1.copy(), True, True)
2189
+ # both complexes are nan+nan.j but the same instance
2190
+ cplx1, cplx2 = [np.array([np.nan + np.nan * 1j])] * 2
2191
+
2192
+ # only real or img are nan.
2193
+ cplx3, cplx4 = np.complex64(1, np.nan), np.complex64(np.nan, 1)
2194
+
2195
+ # Complex values
2196
+ yield (cplx1, cplx2, None, False)
2197
+ yield (cplx1, cplx2, False, False)
2198
+ yield (cplx1, cplx2, True, True)
2199
+
2200
+ # Complex values, 1+nan, nan+1j
2201
+ yield (cplx3, cplx4, None, False)
2202
+ yield (cplx3, cplx4, False, False)
2203
+ yield (cplx3, cplx4, True, True)
2204
+
2205
+
2206
+ class TestArrayComparisons:
2207
+ @pytest.mark.parametrize(
2208
+ "bx,by,equal_nan,expected", _test_array_equal_parametrizations()
2209
+ )
2210
+ def test_array_equal_equal_nan(self, bx, by, equal_nan, expected):
2211
+ """
2212
+ This test array_equal for a few combinations:
2213
+
2214
+ - are the two inputs the same object or not (same object may not
2215
+ be equal if contains NaNs)
2216
+ - Whether we should consider or not, NaNs, being equal.
2217
+
2218
+ """
2219
+ if equal_nan is None:
2220
+ res = np.array_equal(bx, by)
2221
+ else:
2222
+ res = np.array_equal(bx, by, equal_nan=equal_nan)
2223
+ assert_(res is expected)
2224
+ assert_(type(res) is bool)
2225
+
2226
+ def test_array_equal_different_scalar_types(self):
2227
+ # https://github.com/numpy/numpy/issues/27271
2228
+ a = np.array("foo")
2229
+ b = np.array(1)
2230
+ assert not np.array_equal(a, b)
2231
+ assert not np.array_equiv(a, b)
2232
+
2233
+ def test_none_compares_elementwise(self):
2234
+ a = np.array([None, 1, None], dtype=object)
2235
+ assert_equal(a == None, [True, False, True]) # noqa: E711
2236
+ assert_equal(a != None, [False, True, False]) # noqa: E711
2237
+
2238
+ a = np.ones(3)
2239
+ assert_equal(a == None, [False, False, False]) # noqa: E711
2240
+ assert_equal(a != None, [True, True, True]) # noqa: E711
2241
+
2242
+ def test_array_equiv(self):
2243
+ res = np.array_equiv(np.array([1, 2]), np.array([1, 2]))
2244
+ assert_(res)
2245
+ assert_(type(res) is bool)
2246
+ res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3]))
2247
+ assert_(not res)
2248
+ assert_(type(res) is bool)
2249
+ res = np.array_equiv(np.array([1, 2]), np.array([3, 4]))
2250
+ assert_(not res)
2251
+ assert_(type(res) is bool)
2252
+ res = np.array_equiv(np.array([1, 2]), np.array([1, 3]))
2253
+ assert_(not res)
2254
+ assert_(type(res) is bool)
2255
+
2256
+ res = np.array_equiv(np.array([1, 1]), np.array([1]))
2257
+ assert_(res)
2258
+ assert_(type(res) is bool)
2259
+ res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]]))
2260
+ assert_(res)
2261
+ assert_(type(res) is bool)
2262
+ res = np.array_equiv(np.array([1, 2]), np.array([2]))
2263
+ assert_(not res)
2264
+ assert_(type(res) is bool)
2265
+ res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]]))
2266
+ assert_(not res)
2267
+ assert_(type(res) is bool)
2268
+ res = np.array_equiv(
2269
+ np.array([1, 2]),
2270
+ np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
2271
+ )
2272
+ assert_(not res)
2273
+ assert_(type(res) is bool)
2274
+
2275
+ @pytest.mark.parametrize("dtype", ["V0", "V3", "V10"])
2276
+ def test_compare_unstructured_voids(self, dtype):
2277
+ zeros = np.zeros(3, dtype=dtype)
2278
+
2279
+ assert_array_equal(zeros, zeros)
2280
+ assert not (zeros != zeros).any()
2281
+
2282
+ if dtype == "V0":
2283
+ # Can't test != of actually different data
2284
+ return
2285
+
2286
+ nonzeros = np.array([b"1", b"2", b"3"], dtype=dtype)
2287
+
2288
+ assert not (zeros == nonzeros).any()
2289
+ assert (zeros != nonzeros).all()
2290
+
2291
+
2292
+ def assert_array_strict_equal(x, y):
2293
+ assert_array_equal(x, y)
2294
+ # Check flags, 32 bit arches typically don't provide 16 byte alignment
2295
+ if ((x.dtype.alignment <= 8 or
2296
+ np.intp().dtype.itemsize != 4) and
2297
+ sys.platform != 'win32'):
2298
+ assert_(x.flags == y.flags)
2299
+ else:
2300
+ assert_(x.flags.owndata == y.flags.owndata)
2301
+ assert_(x.flags.writeable == y.flags.writeable)
2302
+ assert_(x.flags.c_contiguous == y.flags.c_contiguous)
2303
+ assert_(x.flags.f_contiguous == y.flags.f_contiguous)
2304
+ assert_(x.flags.writebackifcopy == y.flags.writebackifcopy)
2305
+ # check endianness
2306
+ assert_(x.dtype.isnative == y.dtype.isnative)
2307
+
2308
+
2309
+ class TestClip:
2310
+ nr = 5
2311
+ nc = 3
2312
+
2313
+ def fastclip(self, a, m, M, out=None, **kwargs):
2314
+ return a.clip(m, M, out=out, **kwargs)
2315
+
2316
+ def clip(self, a, m, M, out=None):
2317
+ # use a.choose to verify fastclip result
2318
+ selector = np.less(a, m) + 2 * np.greater(a, M)
2319
+ return selector.choose((a, m, M), out=out)
2320
+
2321
+ # Handy functions
2322
+ def _generate_data(self, n, m):
2323
+ return randn(n, m)
2324
+
2325
+ def _generate_data_complex(self, n, m):
2326
+ return randn(n, m) + 1.j * rand(n, m)
2327
+
2328
+ def _generate_flt_data(self, n, m):
2329
+ return (randn(n, m)).astype(np.float32)
2330
+
2331
+ def _neg_byteorder(self, a):
2332
+ a = np.asarray(a)
2333
+ if sys.byteorder == 'little':
2334
+ a = a.astype(a.dtype.newbyteorder('>'))
2335
+ else:
2336
+ a = a.astype(a.dtype.newbyteorder('<'))
2337
+ return a
2338
+
2339
+ def _generate_non_native_data(self, n, m):
2340
+ data = randn(n, m)
2341
+ data = self._neg_byteorder(data)
2342
+ assert_(not data.dtype.isnative)
2343
+ return data
2344
+
2345
+ def _generate_int_data(self, n, m):
2346
+ return (10 * rand(n, m)).astype(np.int64)
2347
+
2348
+ def _generate_int32_data(self, n, m):
2349
+ return (10 * rand(n, m)).astype(np.int32)
2350
+
2351
+ # Now the real test cases
2352
+
2353
+ @pytest.mark.parametrize("dtype", '?bhilqpBHILQPefdgFDGO')
2354
+ def test_ones_pathological(self, dtype):
2355
+ # for preservation of behavior described in
2356
+ # gh-12519; amin > amax behavior may still change
2357
+ # in the future
2358
+ arr = np.ones(10, dtype=dtype)
2359
+ expected = np.zeros(10, dtype=dtype)
2360
+ actual = np.clip(arr, 1, 0)
2361
+ if dtype == 'O':
2362
+ assert actual.tolist() == expected.tolist()
2363
+ else:
2364
+ assert_equal(actual, expected)
2365
+
2366
+ def test_simple_double(self):
2367
+ # Test native double input with scalar min/max.
2368
+ a = self._generate_data(self.nr, self.nc)
2369
+ m = 0.1
2370
+ M = 0.6
2371
+ ac = self.fastclip(a, m, M)
2372
+ act = self.clip(a, m, M)
2373
+ assert_array_strict_equal(ac, act)
2374
+
2375
+ def test_simple_int(self):
2376
+ # Test native int input with scalar min/max.
2377
+ a = self._generate_int_data(self.nr, self.nc)
2378
+ a = a.astype(int)
2379
+ m = -2
2380
+ M = 4
2381
+ ac = self.fastclip(a, m, M)
2382
+ act = self.clip(a, m, M)
2383
+ assert_array_strict_equal(ac, act)
2384
+
2385
+ def test_array_double(self):
2386
+ # Test native double input with array min/max.
2387
+ a = self._generate_data(self.nr, self.nc)
2388
+ m = np.zeros(a.shape)
2389
+ M = m + 0.5
2390
+ ac = self.fastclip(a, m, M)
2391
+ act = self.clip(a, m, M)
2392
+ assert_array_strict_equal(ac, act)
2393
+
2394
+ def test_simple_nonnative(self):
2395
+ # Test non native double input with scalar min/max.
2396
+ # Test native double input with non native double scalar min/max.
2397
+ a = self._generate_non_native_data(self.nr, self.nc)
2398
+ m = -0.5
2399
+ M = 0.6
2400
+ ac = self.fastclip(a, m, M)
2401
+ act = self.clip(a, m, M)
2402
+ assert_array_equal(ac, act)
2403
+
2404
+ # Test native double input with non native double scalar min/max.
2405
+ a = self._generate_data(self.nr, self.nc)
2406
+ m = -0.5
2407
+ M = self._neg_byteorder(0.6)
2408
+ assert_(not M.dtype.isnative)
2409
+ ac = self.fastclip(a, m, M)
2410
+ act = self.clip(a, m, M)
2411
+ assert_array_equal(ac, act)
2412
+
2413
+ def test_simple_complex(self):
2414
+ # Test native complex input with native double scalar min/max.
2415
+ # Test native input with complex double scalar min/max.
2416
+ a = 3 * self._generate_data_complex(self.nr, self.nc)
2417
+ m = -0.5
2418
+ M = 1.
2419
+ ac = self.fastclip(a, m, M)
2420
+ act = self.clip(a, m, M)
2421
+ assert_array_strict_equal(ac, act)
2422
+
2423
+ # Test native input with complex double scalar min/max.
2424
+ a = 3 * self._generate_data(self.nr, self.nc)
2425
+ m = -0.5 + 1.j
2426
+ M = 1. + 2.j
2427
+ ac = self.fastclip(a, m, M)
2428
+ act = self.clip(a, m, M)
2429
+ assert_array_strict_equal(ac, act)
2430
+
2431
+ def test_clip_complex(self):
2432
+ # Address Issue gh-5354 for clipping complex arrays
2433
+ # Test native complex input without explicit min/max
2434
+ # ie, either min=None or max=None
2435
+ a = np.ones(10, dtype=complex)
2436
+ m = a.min()
2437
+ M = a.max()
2438
+ am = self.fastclip(a, m, None)
2439
+ aM = self.fastclip(a, None, M)
2440
+ assert_array_strict_equal(am, a)
2441
+ assert_array_strict_equal(aM, a)
2442
+
2443
+ def test_clip_non_contig(self):
2444
+ # Test clip for non contiguous native input and native scalar min/max.
2445
+ a = self._generate_data(self.nr * 2, self.nc * 3)
2446
+ a = a[::2, ::3]
2447
+ assert_(not a.flags['F_CONTIGUOUS'])
2448
+ assert_(not a.flags['C_CONTIGUOUS'])
2449
+ ac = self.fastclip(a, -1.6, 1.7)
2450
+ act = self.clip(a, -1.6, 1.7)
2451
+ assert_array_strict_equal(ac, act)
2452
+
2453
+ def test_simple_out(self):
2454
+ # Test native double input with scalar min/max.
2455
+ a = self._generate_data(self.nr, self.nc)
2456
+ m = -0.5
2457
+ M = 0.6
2458
+ ac = np.zeros(a.shape)
2459
+ act = np.zeros(a.shape)
2460
+ self.fastclip(a, m, M, ac)
2461
+ self.clip(a, m, M, act)
2462
+ assert_array_strict_equal(ac, act)
2463
+
2464
+ @pytest.mark.parametrize("casting", [None, "unsafe"])
2465
+ def test_simple_int32_inout(self, casting):
2466
+ # Test native int32 input with double min/max and int32 out.
2467
+ a = self._generate_int32_data(self.nr, self.nc)
2468
+ m = np.float64(0)
2469
+ M = np.float64(2)
2470
+ ac = np.zeros(a.shape, dtype=np.int32)
2471
+ act = ac.copy()
2472
+ if casting is None:
2473
+ with pytest.raises(TypeError):
2474
+ self.fastclip(a, m, M, ac, casting=casting)
2475
+ else:
2476
+ # explicitly passing "unsafe" will silence warning
2477
+ self.fastclip(a, m, M, ac, casting=casting)
2478
+ self.clip(a, m, M, act)
2479
+ assert_array_strict_equal(ac, act)
2480
+
2481
+ def test_simple_int64_out(self):
2482
+ # Test native int32 input with int32 scalar min/max and int64 out.
2483
+ a = self._generate_int32_data(self.nr, self.nc)
2484
+ m = np.int32(-1)
2485
+ M = np.int32(1)
2486
+ ac = np.zeros(a.shape, dtype=np.int64)
2487
+ act = ac.copy()
2488
+ self.fastclip(a, m, M, ac)
2489
+ self.clip(a, m, M, act)
2490
+ assert_array_strict_equal(ac, act)
2491
+
2492
+ def test_simple_int64_inout(self):
2493
+ # Test native int32 input with double array min/max and int32 out.
2494
+ a = self._generate_int32_data(self.nr, self.nc)
2495
+ m = np.zeros(a.shape, np.float64)
2496
+ M = np.float64(1)
2497
+ ac = np.zeros(a.shape, dtype=np.int32)
2498
+ act = ac.copy()
2499
+ self.fastclip(a, m, M, out=ac, casting="unsafe")
2500
+ self.clip(a, m, M, act)
2501
+ assert_array_strict_equal(ac, act)
2502
+
2503
+ def test_simple_int32_out(self):
2504
+ # Test native double input with scalar min/max and int out.
2505
+ a = self._generate_data(self.nr, self.nc)
2506
+ m = -1.0
2507
+ M = 2.0
2508
+ ac = np.zeros(a.shape, dtype=np.int32)
2509
+ act = ac.copy()
2510
+ self.fastclip(a, m, M, out=ac, casting="unsafe")
2511
+ self.clip(a, m, M, act)
2512
+ assert_array_strict_equal(ac, act)
2513
+
2514
+ def test_simple_inplace_01(self):
2515
+ # Test native double input with array min/max in-place.
2516
+ a = self._generate_data(self.nr, self.nc)
2517
+ ac = a.copy()
2518
+ m = np.zeros(a.shape)
2519
+ M = 1.0
2520
+ self.fastclip(a, m, M, a)
2521
+ self.clip(a, m, M, ac)
2522
+ assert_array_strict_equal(a, ac)
2523
+
2524
+ def test_simple_inplace_02(self):
2525
+ # Test native double input with scalar min/max in-place.
2526
+ a = self._generate_data(self.nr, self.nc)
2527
+ ac = a.copy()
2528
+ m = -0.5
2529
+ M = 0.6
2530
+ self.fastclip(a, m, M, a)
2531
+ self.clip(ac, m, M, ac)
2532
+ assert_array_strict_equal(a, ac)
2533
+
2534
+ def test_noncontig_inplace(self):
2535
+ # Test non contiguous double input with double scalar min/max in-place.
2536
+ a = self._generate_data(self.nr * 2, self.nc * 3)
2537
+ a = a[::2, ::3]
2538
+ assert_(not a.flags['F_CONTIGUOUS'])
2539
+ assert_(not a.flags['C_CONTIGUOUS'])
2540
+ ac = a.copy()
2541
+ m = -0.5
2542
+ M = 0.6
2543
+ self.fastclip(a, m, M, a)
2544
+ self.clip(ac, m, M, ac)
2545
+ assert_array_equal(a, ac)
2546
+
2547
+ def test_type_cast_01(self):
2548
+ # Test native double input with scalar min/max.
2549
+ a = self._generate_data(self.nr, self.nc)
2550
+ m = -0.5
2551
+ M = 0.6
2552
+ ac = self.fastclip(a, m, M)
2553
+ act = self.clip(a, m, M)
2554
+ assert_array_strict_equal(ac, act)
2555
+
2556
+ def test_type_cast_02(self):
2557
+ # Test native int32 input with int32 scalar min/max.
2558
+ a = self._generate_int_data(self.nr, self.nc)
2559
+ a = a.astype(np.int32)
2560
+ m = -2
2561
+ M = 4
2562
+ ac = self.fastclip(a, m, M)
2563
+ act = self.clip(a, m, M)
2564
+ assert_array_strict_equal(ac, act)
2565
+
2566
+ def test_type_cast_03(self):
2567
+ # Test native int32 input with float64 scalar min/max.
2568
+ a = self._generate_int32_data(self.nr, self.nc)
2569
+ m = -2
2570
+ M = 4
2571
+ ac = self.fastclip(a, np.float64(m), np.float64(M))
2572
+ act = self.clip(a, np.float64(m), np.float64(M))
2573
+ assert_array_strict_equal(ac, act)
2574
+
2575
+ def test_type_cast_04(self):
2576
+ # Test native int32 input with float32 scalar min/max.
2577
+ a = self._generate_int32_data(self.nr, self.nc)
2578
+ m = np.float32(-2)
2579
+ M = np.float32(4)
2580
+ act = self.fastclip(a, m, M)
2581
+ ac = self.clip(a, m, M)
2582
+ assert_array_strict_equal(ac, act)
2583
+
2584
+ def test_type_cast_05(self):
2585
+ # Test native int32 with double arrays min/max.
2586
+ a = self._generate_int_data(self.nr, self.nc)
2587
+ m = -0.5
2588
+ M = 1.
2589
+ ac = self.fastclip(a, m * np.zeros(a.shape), M)
2590
+ act = self.clip(a, m * np.zeros(a.shape), M)
2591
+ assert_array_strict_equal(ac, act)
2592
+
2593
+ def test_type_cast_06(self):
2594
+ # Test native with NON native scalar min/max.
2595
+ a = self._generate_data(self.nr, self.nc)
2596
+ m = 0.5
2597
+ m_s = self._neg_byteorder(m)
2598
+ M = 1.
2599
+ act = self.clip(a, m_s, M)
2600
+ ac = self.fastclip(a, m_s, M)
2601
+ assert_array_strict_equal(ac, act)
2602
+
2603
+ def test_type_cast_07(self):
2604
+ # Test NON native with native array min/max.
2605
+ a = self._generate_data(self.nr, self.nc)
2606
+ m = -0.5 * np.ones(a.shape)
2607
+ M = 1.
2608
+ a_s = self._neg_byteorder(a)
2609
+ assert_(not a_s.dtype.isnative)
2610
+ act = a_s.clip(m, M)
2611
+ ac = self.fastclip(a_s, m, M)
2612
+ assert_array_strict_equal(ac, act)
2613
+
2614
+ def test_type_cast_08(self):
2615
+ # Test NON native with native scalar min/max.
2616
+ a = self._generate_data(self.nr, self.nc)
2617
+ m = -0.5
2618
+ M = 1.
2619
+ a_s = self._neg_byteorder(a)
2620
+ assert_(not a_s.dtype.isnative)
2621
+ ac = self.fastclip(a_s, m, M)
2622
+ act = a_s.clip(m, M)
2623
+ assert_array_strict_equal(ac, act)
2624
+
2625
+ def test_type_cast_09(self):
2626
+ # Test native with NON native array min/max.
2627
+ a = self._generate_data(self.nr, self.nc)
2628
+ m = -0.5 * np.ones(a.shape)
2629
+ M = 1.
2630
+ m_s = self._neg_byteorder(m)
2631
+ assert_(not m_s.dtype.isnative)
2632
+ ac = self.fastclip(a, m_s, M)
2633
+ act = self.clip(a, m_s, M)
2634
+ assert_array_strict_equal(ac, act)
2635
+
2636
+ def test_type_cast_10(self):
2637
+ # Test native int32 with float min/max and float out for output argument.
2638
+ a = self._generate_int_data(self.nr, self.nc)
2639
+ b = np.zeros(a.shape, dtype=np.float32)
2640
+ m = np.float32(-0.5)
2641
+ M = np.float32(1)
2642
+ act = self.clip(a, m, M, out=b)
2643
+ ac = self.fastclip(a, m, M, out=b)
2644
+ assert_array_strict_equal(ac, act)
2645
+
2646
+ def test_type_cast_11(self):
2647
+ # Test non native with native scalar, min/max, out non native
2648
+ a = self._generate_non_native_data(self.nr, self.nc)
2649
+ b = a.copy()
2650
+ b = b.astype(b.dtype.newbyteorder('>'))
2651
+ bt = b.copy()
2652
+ m = -0.5
2653
+ M = 1.
2654
+ self.fastclip(a, m, M, out=b)
2655
+ self.clip(a, m, M, out=bt)
2656
+ assert_array_strict_equal(b, bt)
2657
+
2658
+ def test_type_cast_12(self):
2659
+ # Test native int32 input and min/max and float out
2660
+ a = self._generate_int_data(self.nr, self.nc)
2661
+ b = np.zeros(a.shape, dtype=np.float32)
2662
+ m = np.int32(0)
2663
+ M = np.int32(1)
2664
+ act = self.clip(a, m, M, out=b)
2665
+ ac = self.fastclip(a, m, M, out=b)
2666
+ assert_array_strict_equal(ac, act)
2667
+
2668
+ def test_clip_with_out_simple(self):
2669
+ # Test native double input with scalar min/max
2670
+ a = self._generate_data(self.nr, self.nc)
2671
+ m = -0.5
2672
+ M = 0.6
2673
+ ac = np.zeros(a.shape)
2674
+ act = np.zeros(a.shape)
2675
+ self.fastclip(a, m, M, ac)
2676
+ self.clip(a, m, M, act)
2677
+ assert_array_strict_equal(ac, act)
2678
+
2679
+ def test_clip_with_out_simple2(self):
2680
+ # Test native int32 input with double min/max and int32 out
2681
+ a = self._generate_int32_data(self.nr, self.nc)
2682
+ m = np.float64(0)
2683
+ M = np.float64(2)
2684
+ ac = np.zeros(a.shape, dtype=np.int32)
2685
+ act = ac.copy()
2686
+ self.fastclip(a, m, M, out=ac, casting="unsafe")
2687
+ self.clip(a, m, M, act)
2688
+ assert_array_strict_equal(ac, act)
2689
+
2690
+ def test_clip_with_out_simple_int32(self):
2691
+ # Test native int32 input with int32 scalar min/max and int64 out
2692
+ a = self._generate_int32_data(self.nr, self.nc)
2693
+ m = np.int32(-1)
2694
+ M = np.int32(1)
2695
+ ac = np.zeros(a.shape, dtype=np.int64)
2696
+ act = ac.copy()
2697
+ self.fastclip(a, m, M, ac)
2698
+ self.clip(a, m, M, act)
2699
+ assert_array_strict_equal(ac, act)
2700
+
2701
+ def test_clip_with_out_array_int32(self):
2702
+ # Test native int32 input with double array min/max and int32 out
2703
+ a = self._generate_int32_data(self.nr, self.nc)
2704
+ m = np.zeros(a.shape, np.float64)
2705
+ M = np.float64(1)
2706
+ ac = np.zeros(a.shape, dtype=np.int32)
2707
+ act = ac.copy()
2708
+ self.fastclip(a, m, M, out=ac, casting="unsafe")
2709
+ self.clip(a, m, M, act)
2710
+ assert_array_strict_equal(ac, act)
2711
+
2712
+ def test_clip_with_out_array_outint32(self):
2713
+ # Test native double input with scalar min/max and int out
2714
+ a = self._generate_data(self.nr, self.nc)
2715
+ m = -1.0
2716
+ M = 2.0
2717
+ ac = np.zeros(a.shape, dtype=np.int32)
2718
+ act = ac.copy()
2719
+ self.fastclip(a, m, M, out=ac, casting="unsafe")
2720
+ self.clip(a, m, M, act)
2721
+ assert_array_strict_equal(ac, act)
2722
+
2723
+ def test_clip_with_out_transposed(self):
2724
+ # Test that the out argument works when transposed
2725
+ a = np.arange(16).reshape(4, 4)
2726
+ out = np.empty_like(a).T
2727
+ a.clip(4, 10, out=out)
2728
+ expected = self.clip(a, 4, 10)
2729
+ assert_array_equal(out, expected)
2730
+
2731
+ def test_clip_with_out_memory_overlap(self):
2732
+ # Test that the out argument works when it has memory overlap
2733
+ a = np.arange(16).reshape(4, 4)
2734
+ ac = a.copy()
2735
+ a[:-1].clip(4, 10, out=a[1:])
2736
+ expected = self.clip(ac[:-1], 4, 10)
2737
+ assert_array_equal(a[1:], expected)
2738
+
2739
+ def test_clip_inplace_array(self):
2740
+ # Test native double input with array min/max
2741
+ a = self._generate_data(self.nr, self.nc)
2742
+ ac = a.copy()
2743
+ m = np.zeros(a.shape)
2744
+ M = 1.0
2745
+ self.fastclip(a, m, M, a)
2746
+ self.clip(a, m, M, ac)
2747
+ assert_array_strict_equal(a, ac)
2748
+
2749
+ def test_clip_inplace_simple(self):
2750
+ # Test native double input with scalar min/max
2751
+ a = self._generate_data(self.nr, self.nc)
2752
+ ac = a.copy()
2753
+ m = -0.5
2754
+ M = 0.6
2755
+ self.fastclip(a, m, M, a)
2756
+ self.clip(a, m, M, ac)
2757
+ assert_array_strict_equal(a, ac)
2758
+
2759
+ def test_clip_func_takes_out(self):
2760
+ # Ensure that the clip() function takes an out=argument.
2761
+ a = self._generate_data(self.nr, self.nc)
2762
+ ac = a.copy()
2763
+ m = -0.5
2764
+ M = 0.6
2765
+ a2 = np.clip(a, m, M, out=a)
2766
+ self.clip(a, m, M, ac)
2767
+ assert_array_strict_equal(a2, ac)
2768
+ assert_(a2 is a)
2769
+
2770
+ def test_clip_nan(self):
2771
+ d = np.arange(7.)
2772
+ assert_equal(d.clip(min=np.nan), np.nan)
2773
+ assert_equal(d.clip(max=np.nan), np.nan)
2774
+ assert_equal(d.clip(min=np.nan, max=np.nan), np.nan)
2775
+ assert_equal(d.clip(min=-2, max=np.nan), np.nan)
2776
+ assert_equal(d.clip(min=np.nan, max=10), np.nan)
2777
+
2778
+ def test_object_clip(self):
2779
+ a = np.arange(10, dtype=object)
2780
+ actual = np.clip(a, 1, 5)
2781
+ expected = np.array([1, 1, 2, 3, 4, 5, 5, 5, 5, 5])
2782
+ assert actual.tolist() == expected.tolist()
2783
+
2784
+ def test_clip_all_none(self):
2785
+ arr = np.arange(10, dtype=object)
2786
+ assert_equal(np.clip(arr, None, None), arr)
2787
+ assert_equal(np.clip(arr), arr)
2788
+
2789
+ def test_clip_invalid_casting(self):
2790
+ a = np.arange(10, dtype=object)
2791
+ with assert_raises_regex(ValueError,
2792
+ 'casting must be one of'):
2793
+ self.fastclip(a, 1, 8, casting="garbage")
2794
+
2795
+ @pytest.mark.parametrize("amin, amax", [
2796
+ # two scalars
2797
+ (1, 0),
2798
+ # mix scalar and array
2799
+ (1, np.zeros(10)),
2800
+ # two arrays
2801
+ (np.ones(10), np.zeros(10)),
2802
+ ])
2803
+ def test_clip_value_min_max_flip(self, amin, amax):
2804
+ a = np.arange(10, dtype=np.int64)
2805
+ # requirement from ufunc_docstrings.py
2806
+ expected = np.minimum(np.maximum(a, amin), amax)
2807
+ actual = np.clip(a, amin, amax)
2808
+ assert_equal(actual, expected)
2809
+
2810
+ @pytest.mark.parametrize("arr, amin, amax, exp", [
2811
+ # for a bug in npy_ObjectClip, based on a
2812
+ # case produced by hypothesis
2813
+ (np.zeros(10, dtype=object),
2814
+ 0,
2815
+ -2**64 + 1,
2816
+ np.full(10, -2**64 + 1, dtype=object)),
2817
+ # for bugs in NPY_TIMEDELTA_MAX, based on a case
2818
+ # produced by hypothesis
2819
+ (np.zeros(10, dtype='m8') - 1,
2820
+ 0,
2821
+ 0,
2822
+ np.zeros(10, dtype='m8')),
2823
+ ])
2824
+ def test_clip_problem_cases(self, arr, amin, amax, exp):
2825
+ actual = np.clip(arr, amin, amax)
2826
+ assert_equal(actual, exp)
2827
+
2828
+ @pytest.mark.parametrize("arr, amin, amax", [
2829
+ # problematic scalar nan case from hypothesis
2830
+ (np.zeros(10, dtype=np.int64),
2831
+ np.array(np.nan),
2832
+ np.zeros(10, dtype=np.int32)),
2833
+ ])
2834
+ def test_clip_scalar_nan_propagation(self, arr, amin, amax):
2835
+ # enforcement of scalar nan propagation for comparisons
2836
+ # called through clip()
2837
+ expected = np.minimum(np.maximum(arr, amin), amax)
2838
+ actual = np.clip(arr, amin, amax)
2839
+ assert_equal(actual, expected)
2840
+
2841
+ @pytest.mark.parametrize("arr, amin, amax", [
2842
+ (np.array([1] * 10, dtype='m8'),
2843
+ np.timedelta64('NaT'),
2844
+ np.zeros(10, dtype=np.int32)),
2845
+ ])
2846
+ def test_NaT_propagation(self, arr, amin, amax):
2847
+ expected = np.minimum(np.maximum(arr, amin), amax)
2848
+ actual = np.clip(arr, amin, amax)
2849
+ assert_equal(actual, expected)
2850
+
2851
+ @given(
2852
+ data=st.data(),
2853
+ arr=hynp.arrays(
2854
+ dtype=hynp.integer_dtypes() | hynp.floating_dtypes(),
2855
+ shape=hynp.array_shapes()
2856
+ )
2857
+ )
2858
+ def test_clip_property(self, data, arr):
2859
+ """A property-based test using Hypothesis.
2860
+
2861
+ This aims for maximum generality: it could in principle generate *any*
2862
+ valid inputs to np.clip, and in practice generates much more varied
2863
+ inputs than human testers come up with.
2864
+
2865
+ Because many of the inputs have tricky dependencies - compatible dtypes
2866
+ and mutually-broadcastable shapes - we use `st.data()` strategy draw
2867
+ values *inside* the test function, from strategies we construct based
2868
+ on previous values. An alternative would be to define a custom strategy
2869
+ with `@st.composite`, but until we have duplicated code inline is fine.
2870
+
2871
+ That accounts for most of the function; the actual test is just three
2872
+ lines to calculate and compare actual vs expected results!
2873
+ """
2874
+ numeric_dtypes = hynp.integer_dtypes() | hynp.floating_dtypes()
2875
+ # Generate shapes for the bounds which can be broadcast with each other
2876
+ # and with the base shape. Below, we might decide to use scalar bounds,
2877
+ # but it's clearer to generate these shapes unconditionally in advance.
2878
+ in_shapes, result_shape = data.draw(
2879
+ hynp.mutually_broadcastable_shapes(
2880
+ num_shapes=2, base_shape=arr.shape
2881
+ )
2882
+ )
2883
+ # Scalar `nan` is deprecated due to the differing behaviour it shows.
2884
+ s = numeric_dtypes.flatmap(
2885
+ lambda x: hynp.from_dtype(x, allow_nan=False))
2886
+ amin = data.draw(s | hynp.arrays(dtype=numeric_dtypes,
2887
+ shape=in_shapes[0], elements={"allow_nan": False}))
2888
+ amax = data.draw(s | hynp.arrays(dtype=numeric_dtypes,
2889
+ shape=in_shapes[1], elements={"allow_nan": False}))
2890
+
2891
+ # Then calculate our result and expected result and check that they're
2892
+ # equal! See gh-12519 and gh-19457 for discussion deciding on this
2893
+ # property and the result_type argument.
2894
+ result = np.clip(arr, amin, amax)
2895
+ t = np.result_type(arr, amin, amax)
2896
+ expected = np.minimum(amax, np.maximum(arr, amin, dtype=t), dtype=t)
2897
+ assert result.dtype == t
2898
+ assert_array_equal(result, expected)
2899
+
2900
+ def test_clip_min_max_args(self):
2901
+ arr = np.arange(5)
2902
+
2903
+ assert_array_equal(np.clip(arr), arr)
2904
+ assert_array_equal(np.clip(arr, min=2, max=3), np.clip(arr, 2, 3))
2905
+ assert_array_equal(np.clip(arr, min=None, max=2),
2906
+ np.clip(arr, None, 2))
2907
+
2908
+ with assert_raises_regex(TypeError, "missing 1 required positional "
2909
+ "argument: 'a_max'"):
2910
+ np.clip(arr, 2)
2911
+ with assert_raises_regex(TypeError, "missing 1 required positional "
2912
+ "argument: 'a_min'"):
2913
+ np.clip(arr, a_max=2)
2914
+ msg = ("Passing `min` or `max` keyword argument when `a_min` and "
2915
+ "`a_max` are provided is forbidden.")
2916
+ with assert_raises_regex(ValueError, msg):
2917
+ np.clip(arr, 2, 3, max=3)
2918
+ with assert_raises_regex(ValueError, msg):
2919
+ np.clip(arr, 2, 3, min=2)
2920
+
2921
+ @pytest.mark.parametrize("dtype,min,max", [
2922
+ ("int32", -2**32 - 1, 2**32),
2923
+ ("int32", -2**320, None),
2924
+ ("int32", None, 2**300),
2925
+ ("int32", -1000, 2**32),
2926
+ ("int32", -2**32 - 1, 1000),
2927
+ ("uint8", -1, 129),
2928
+ ])
2929
+ def test_out_of_bound_pyints(self, dtype, min, max):
2930
+ a = np.arange(10000).astype(dtype)
2931
+ # Check min only
2932
+ c = np.clip(a, min=min, max=max)
2933
+ assert not np.may_share_memory(a, c)
2934
+ assert c.dtype == a.dtype
2935
+ if min is not None:
2936
+ assert (c >= min).all()
2937
+ if max is not None:
2938
+ assert (c <= max).all()
2939
+
2940
+
2941
+ class TestAllclose:
2942
+ rtol = 1e-5
2943
+ atol = 1e-8
2944
+
2945
+ def setup_method(self):
2946
+ self.olderr = np.seterr(invalid='ignore')
2947
+
2948
+ def teardown_method(self):
2949
+ np.seterr(**self.olderr)
2950
+
2951
+ def tst_allclose(self, x, y):
2952
+ assert_(np.allclose(x, y), f"{x} and {y} not close")
2953
+
2954
+ def tst_not_allclose(self, x, y):
2955
+ assert_(not np.allclose(x, y), f"{x} and {y} shouldn't be close")
2956
+
2957
+ def test_ip_allclose(self):
2958
+ # Parametric test factory.
2959
+ arr = np.array([100, 1000])
2960
+ aran = np.arange(125).reshape((5, 5, 5))
2961
+
2962
+ atol = self.atol
2963
+ rtol = self.rtol
2964
+
2965
+ data = [([1, 0], [1, 0]),
2966
+ ([atol], [0]),
2967
+ ([1], [1 + rtol + atol]),
2968
+ (arr, arr + arr * rtol),
2969
+ (arr, arr + arr * rtol + atol * 2),
2970
+ (aran, aran + aran * rtol),
2971
+ (np.inf, np.inf),
2972
+ (np.inf, [np.inf])]
2973
+
2974
+ for (x, y) in data:
2975
+ self.tst_allclose(x, y)
2976
+
2977
+ def test_ip_not_allclose(self):
2978
+ # Parametric test factory.
2979
+ aran = np.arange(125).reshape((5, 5, 5))
2980
+
2981
+ atol = self.atol
2982
+ rtol = self.rtol
2983
+
2984
+ data = [([np.inf, 0], [1, np.inf]),
2985
+ ([np.inf, 0], [1, 0]),
2986
+ ([np.inf, np.inf], [1, np.inf]),
2987
+ ([np.inf, np.inf], [1, 0]),
2988
+ ([-np.inf, 0], [np.inf, 0]),
2989
+ ([np.nan, 0], [np.nan, 0]),
2990
+ ([atol * 2], [0]),
2991
+ ([1], [1 + rtol + atol * 2]),
2992
+ (aran, aran + aran * atol + atol * 2),
2993
+ (np.array([np.inf, 1]), np.array([0, np.inf]))]
2994
+
2995
+ for (x, y) in data:
2996
+ self.tst_not_allclose(x, y)
2997
+
2998
+ def test_no_parameter_modification(self):
2999
+ x = np.array([np.inf, 1])
3000
+ y = np.array([0, np.inf])
3001
+ np.allclose(x, y)
3002
+ assert_array_equal(x, np.array([np.inf, 1]))
3003
+ assert_array_equal(y, np.array([0, np.inf]))
3004
+
3005
+ def test_min_int(self):
3006
+ # Could make problems because of abs(min_int) == min_int
3007
+ min_int = np.iinfo(np.int_).min
3008
+ a = np.array([min_int], dtype=np.int_)
3009
+ assert_(np.allclose(a, a))
3010
+
3011
+ def test_equalnan(self):
3012
+ x = np.array([1.0, np.nan])
3013
+ assert_(np.allclose(x, x, equal_nan=True))
3014
+
3015
+ def test_return_class_is_ndarray(self):
3016
+ # Issue gh-6475
3017
+ # Check that allclose does not preserve subtypes
3018
+ class Foo(np.ndarray):
3019
+ def __new__(cls, *args, **kwargs):
3020
+ return np.array(*args, **kwargs).view(cls)
3021
+
3022
+ a = Foo([1])
3023
+ assert_(type(np.allclose(a, a)) is bool)
3024
+
3025
+
3026
+ class TestIsclose:
3027
+ rtol = 1e-5
3028
+ atol = 1e-8
3029
+
3030
+ def _setup(self):
3031
+ atol = self.atol
3032
+ rtol = self.rtol
3033
+ arr = np.array([100, 1000])
3034
+ aran = np.arange(125).reshape((5, 5, 5))
3035
+
3036
+ self.all_close_tests = [
3037
+ ([1, 0], [1, 0]),
3038
+ ([atol], [0]),
3039
+ ([1], [1 + rtol + atol]),
3040
+ (arr, arr + arr * rtol),
3041
+ (arr, arr + arr * rtol + atol),
3042
+ (aran, aran + aran * rtol),
3043
+ (np.inf, np.inf),
3044
+ (np.inf, [np.inf]),
3045
+ ([np.inf, -np.inf], [np.inf, -np.inf]),
3046
+ ]
3047
+ self.none_close_tests = [
3048
+ ([np.inf, 0], [1, np.inf]),
3049
+ ([np.inf, -np.inf], [1, 0]),
3050
+ ([np.inf, np.inf], [1, -np.inf]),
3051
+ ([np.inf, np.inf], [1, 0]),
3052
+ ([np.nan, 0], [np.nan, -np.inf]),
3053
+ ([atol * 2], [0]),
3054
+ ([1], [1 + rtol + atol * 2]),
3055
+ (aran, aran + rtol * 1.1 * aran + atol * 1.1),
3056
+ (np.array([np.inf, 1]), np.array([0, np.inf])),
3057
+ ]
3058
+ self.some_close_tests = [
3059
+ ([np.inf, 0], [np.inf, atol * 2]),
3060
+ ([atol, 1, 1e6 * (1 + 2 * rtol) + atol], [0, np.nan, 1e6]),
3061
+ (np.arange(3), [0, 1, 2.1]),
3062
+ (np.nan, [np.nan, np.nan, np.nan]),
3063
+ ([0], [atol, np.inf, -np.inf, np.nan]),
3064
+ (0, [atol, np.inf, -np.inf, np.nan]),
3065
+ ]
3066
+ self.some_close_results = [
3067
+ [True, False],
3068
+ [True, False, False],
3069
+ [True, True, False],
3070
+ [False, False, False],
3071
+ [True, False, False, False],
3072
+ [True, False, False, False],
3073
+ ]
3074
+
3075
+ def test_ip_isclose(self):
3076
+ self._setup()
3077
+ tests = self.some_close_tests
3078
+ results = self.some_close_results
3079
+ for (x, y), result in zip(tests, results):
3080
+ assert_array_equal(np.isclose(x, y), result)
3081
+
3082
+ x = np.array([2.1, 2.1, 2.1, 2.1, 5, np.nan])
3083
+ y = np.array([2, 2, 2, 2, np.nan, 5])
3084
+ atol = [0.11, 0.09, 1e-8, 1e-8, 1, 1]
3085
+ rtol = [1e-8, 1e-8, 0.06, 0.04, 1, 1]
3086
+ expected = np.array([True, False, True, False, False, False])
3087
+ assert_array_equal(np.isclose(x, y, rtol=rtol, atol=atol), expected)
3088
+
3089
+ message = "operands could not be broadcast together..."
3090
+ atol = np.array([1e-8, 1e-8])
3091
+ with assert_raises(ValueError, msg=message):
3092
+ np.isclose(x, y, atol=atol)
3093
+
3094
+ rtol = np.array([1e-5, 1e-5])
3095
+ with assert_raises(ValueError, msg=message):
3096
+ np.isclose(x, y, rtol=rtol)
3097
+
3098
+ def test_nep50_isclose(self):
3099
+ below_one = float(1. - np.finfo('f8').eps)
3100
+ f32 = np.array(below_one, 'f4') # This is just 1 at float32 precision
3101
+ assert f32 > np.array(below_one)
3102
+ # NEP 50 broadcasting of python scalars
3103
+ assert f32 == below_one
3104
+ # Test that it works for isclose arguments too (and that those fail if
3105
+ # one uses a numpy float64).
3106
+ assert np.isclose(f32, below_one, atol=0, rtol=0)
3107
+ assert np.isclose(f32, np.float32(0), atol=below_one)
3108
+ assert np.isclose(f32, 2, atol=0, rtol=below_one / 2)
3109
+ assert not np.isclose(f32, np.float64(below_one), atol=0, rtol=0)
3110
+ assert not np.isclose(f32, np.float32(0), atol=np.float64(below_one))
3111
+ assert not np.isclose(f32, 2, atol=0, rtol=np.float64(below_one / 2))
3112
+
3113
+ def tst_all_isclose(self, x, y):
3114
+ assert_(np.all(np.isclose(x, y)), f"{x} and {y} not close")
3115
+
3116
+ def tst_none_isclose(self, x, y):
3117
+ msg = "%s and %s shouldn't be close"
3118
+ assert_(not np.any(np.isclose(x, y)), msg % (x, y))
3119
+
3120
+ def tst_isclose_allclose(self, x, y):
3121
+ msg = "isclose.all() and allclose aren't same for %s and %s"
3122
+ msg2 = "isclose and allclose aren't same for %s and %s"
3123
+ if np.isscalar(x) and np.isscalar(y):
3124
+ assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y))
3125
+ else:
3126
+ assert_array_equal(
3127
+ np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y)
3128
+ )
3129
+
3130
+ def test_ip_all_isclose(self):
3131
+ self._setup()
3132
+ for (x, y) in self.all_close_tests:
3133
+ self.tst_all_isclose(x, y)
3134
+
3135
+ x = np.array([2.3, 3.6, 4.4, np.nan])
3136
+ y = np.array([2, 3, 4, np.nan])
3137
+ atol = [0.31, 0, 0, 1]
3138
+ rtol = [0, 0.21, 0.11, 1]
3139
+ assert np.allclose(x, y, atol=atol, rtol=rtol, equal_nan=True)
3140
+ assert not np.allclose(x, y, atol=0.1, rtol=0.1, equal_nan=True)
3141
+
3142
+ # Show that gh-14330 is resolved
3143
+ assert np.allclose([1, 2, float('nan')], [1, 2, float('nan')],
3144
+ atol=[1, 1, 1], equal_nan=True)
3145
+
3146
+ def test_ip_none_isclose(self):
3147
+ self._setup()
3148
+ for (x, y) in self.none_close_tests:
3149
+ self.tst_none_isclose(x, y)
3150
+
3151
+ def test_ip_isclose_allclose(self):
3152
+ self._setup()
3153
+ tests = (self.all_close_tests + self.none_close_tests +
3154
+ self.some_close_tests)
3155
+ for (x, y) in tests:
3156
+ self.tst_isclose_allclose(x, y)
3157
+
3158
+ def test_equal_nan(self):
3159
+ assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True])
3160
+ arr = np.array([1.0, np.nan])
3161
+ assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True])
3162
+
3163
+ def test_masked_arrays(self):
3164
+ # Make sure to test the output type when arguments are interchanged.
3165
+
3166
+ x = np.ma.masked_where([True, True, False], np.arange(3))
3167
+ assert_(type(x) is type(np.isclose(2, x)))
3168
+ assert_(type(x) is type(np.isclose(x, 2)))
3169
+
3170
+ x = np.ma.masked_where([True, True, False], [np.nan, np.inf, np.nan])
3171
+ assert_(type(x) is type(np.isclose(np.inf, x)))
3172
+ assert_(type(x) is type(np.isclose(x, np.inf)))
3173
+
3174
+ x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])
3175
+ y = np.isclose(np.nan, x, equal_nan=True)
3176
+ assert_(type(x) is type(y))
3177
+ # Ensure that the mask isn't modified...
3178
+ assert_array_equal([True, True, False], y.mask)
3179
+ y = np.isclose(x, np.nan, equal_nan=True)
3180
+ assert_(type(x) is type(y))
3181
+ # Ensure that the mask isn't modified...
3182
+ assert_array_equal([True, True, False], y.mask)
3183
+
3184
+ x = np.ma.masked_where([True, True, False], [np.nan, np.nan, np.nan])
3185
+ y = np.isclose(x, x, equal_nan=True)
3186
+ assert_(type(x) is type(y))
3187
+ # Ensure that the mask isn't modified...
3188
+ assert_array_equal([True, True, False], y.mask)
3189
+
3190
+ def test_scalar_return(self):
3191
+ assert_(np.isscalar(np.isclose(1, 1)))
3192
+
3193
+ def test_no_parameter_modification(self):
3194
+ x = np.array([np.inf, 1])
3195
+ y = np.array([0, np.inf])
3196
+ np.isclose(x, y)
3197
+ assert_array_equal(x, np.array([np.inf, 1]))
3198
+ assert_array_equal(y, np.array([0, np.inf]))
3199
+
3200
+ def test_non_finite_scalar(self):
3201
+ # GH7014, when two scalars are compared the output should also be a
3202
+ # scalar
3203
+ assert_(np.isclose(np.inf, -np.inf) is np.False_)
3204
+ assert_(np.isclose(0, np.inf) is np.False_)
3205
+ assert_(type(np.isclose(0, np.inf)) is np.bool)
3206
+
3207
+ def test_timedelta(self):
3208
+ # Allclose currently works for timedelta64 as long as `atol` is
3209
+ # an integer or also a timedelta64
3210
+ a = np.array([[1, 2, 3, "NaT"]], dtype="m8[ns]")
3211
+ assert np.isclose(a, a, atol=0, equal_nan=True).all()
3212
+ assert np.isclose(a, a, atol=np.timedelta64(1, "ns"), equal_nan=True).all()
3213
+ assert np.allclose(a, a, atol=0, equal_nan=True)
3214
+ assert np.allclose(a, a, atol=np.timedelta64(1, "ns"), equal_nan=True)
3215
+
3216
+ def test_tol_warnings(self):
3217
+ a = np.array([1, 2, 3])
3218
+ b = np.array([np.inf, np.nan, 1])
3219
+
3220
+ for i in b:
3221
+ for j in b:
3222
+ # Making sure that i and j are not both numbers,
3223
+ # because that won't create a warning
3224
+ if (i == 1) and (j == 1):
3225
+ continue
3226
+
3227
+ with warnings.catch_warnings(record=True) as w:
3228
+
3229
+ warnings.simplefilter("always")
3230
+ c = np.isclose(a, a, atol=i, rtol=j)
3231
+ assert len(w) == 1
3232
+ assert issubclass(w[-1].category, RuntimeWarning)
3233
+ expected = f"One of rtol or atol is not valid, atol: {i}, rtol: {j}"
3234
+ assert expected in str(w[-1].message)
3235
+
3236
+
3237
+ class TestStdVar:
3238
+ def _create_data(self):
3239
+ A = np.array([1, -1, 1, -1])
3240
+ real_var = 1
3241
+ return A, real_var
3242
+
3243
+ def test_basic(self):
3244
+ A, real_var = self._create_data()
3245
+ assert_almost_equal(np.var(A), real_var)
3246
+ assert_almost_equal(np.std(A)**2, real_var)
3247
+
3248
+ def test_scalars(self):
3249
+ assert_equal(np.var(1), 0)
3250
+ assert_equal(np.std(1), 0)
3251
+
3252
+ def test_ddof1(self):
3253
+ A, real_var = self._create_data()
3254
+ assert_almost_equal(np.var(A, ddof=1),
3255
+ real_var * len(A) / (len(A) - 1))
3256
+ assert_almost_equal(np.std(A, ddof=1)**2,
3257
+ real_var * len(A) / (len(A) - 1))
3258
+
3259
+ def test_ddof2(self):
3260
+ A, real_var = self._create_data()
3261
+ assert_almost_equal(np.var(A, ddof=2),
3262
+ real_var * len(A) / (len(A) - 2))
3263
+ assert_almost_equal(np.std(A, ddof=2)**2,
3264
+ real_var * len(A) / (len(A) - 2))
3265
+
3266
+ def test_correction(self):
3267
+ A, _ = self._create_data()
3268
+ assert_almost_equal(
3269
+ np.var(A, correction=1), np.var(A, ddof=1)
3270
+ )
3271
+ assert_almost_equal(
3272
+ np.std(A, correction=1), np.std(A, ddof=1)
3273
+ )
3274
+
3275
+ err_msg = "ddof and correction can't be provided simultaneously."
3276
+
3277
+ with assert_raises_regex(ValueError, err_msg):
3278
+ np.var(A, ddof=1, correction=0)
3279
+
3280
+ with assert_raises_regex(ValueError, err_msg):
3281
+ np.std(A, ddof=1, correction=1)
3282
+
3283
+ def test_out_scalar(self):
3284
+ d = np.arange(10)
3285
+ out = np.array(0.)
3286
+ r = np.std(d, out=out)
3287
+ assert_(r is out)
3288
+ assert_array_equal(r, out)
3289
+ r = np.var(d, out=out)
3290
+ assert_(r is out)
3291
+ assert_array_equal(r, out)
3292
+ r = np.mean(d, out=out)
3293
+ assert_(r is out)
3294
+ assert_array_equal(r, out)
3295
+
3296
+
3297
+ class TestStdVarComplex:
3298
+ def test_basic(self):
3299
+ A = np.array([1, 1.j, -1, -1.j])
3300
+ real_var = 1
3301
+ assert_almost_equal(np.var(A), real_var)
3302
+ assert_almost_equal(np.std(A)**2, real_var)
3303
+
3304
+ def test_scalars(self):
3305
+ assert_equal(np.var(1j), 0)
3306
+ assert_equal(np.std(1j), 0)
3307
+
3308
+
3309
+ class TestCreationFuncs:
3310
+ def check_function(self, func, fill_value=None):
3311
+ dtypes_info = {np.dtype(tp) for tp in itertools.chain(*sctypes.values())}
3312
+ keyfunc = lambda dtype: dtype.str
3313
+ variable_sized = {tp for tp in dtypes_info if tp.str.endswith('0')}
3314
+ dtypes = sorted(dtypes_info - variable_sized |
3315
+ {np.dtype(tp.str.replace("0", str(i)))
3316
+ for tp in variable_sized for i in range(1, 10)},
3317
+ key=keyfunc)
3318
+ dtypes += [type(dt) for dt in sorted(dtypes_info, key=keyfunc)]
3319
+ orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}
3320
+ ndims = 10
3321
+
3322
+ par = ((0, 1, 2),
3323
+ range(ndims),
3324
+ orders,
3325
+ dtypes)
3326
+ fill_kwarg = {}
3327
+ if fill_value is not None:
3328
+ fill_kwarg = {'fill_value': fill_value}
3329
+
3330
+ for size, ndims, order, dtype in itertools.product(*par):
3331
+ shape = ndims * [size]
3332
+
3333
+ is_void = dtype is np.dtypes.VoidDType or (
3334
+ isinstance(dtype, np.dtype) and dtype.str.startswith('|V'))
3335
+
3336
+ # do not fill void type
3337
+ if fill_kwarg and is_void:
3338
+ continue
3339
+
3340
+ arr = func(shape, order=order, dtype=dtype,
3341
+ **fill_kwarg)
3342
+
3343
+ if isinstance(dtype, np.dtype):
3344
+ assert_equal(arr.dtype, dtype)
3345
+ elif isinstance(dtype, type(np.dtype)):
3346
+ if dtype in (np.dtypes.StrDType, np.dtypes.BytesDType):
3347
+ dtype_str = np.dtype(dtype.type).str.replace('0', '1')
3348
+ assert_equal(arr.dtype, np.dtype(dtype_str))
3349
+ else:
3350
+ assert_equal(arr.dtype, np.dtype(dtype.type))
3351
+ assert_(getattr(arr.flags, orders[order]))
3352
+
3353
+ if fill_value is not None:
3354
+ if arr.dtype.str.startswith('|S'):
3355
+ val = str(fill_value)
3356
+ else:
3357
+ val = fill_value
3358
+ assert_equal(arr, dtype.type(val))
3359
+
3360
+ def test_zeros(self):
3361
+ self.check_function(np.zeros)
3362
+
3363
+ def test_ones(self):
3364
+ self.check_function(np.ones)
3365
+
3366
+ def test_empty(self):
3367
+ self.check_function(np.empty)
3368
+
3369
+ def test_full(self):
3370
+ self.check_function(np.full, 0)
3371
+ self.check_function(np.full, 1)
3372
+
3373
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
3374
+ def test_for_reference_leak(self):
3375
+ # Make sure we have an object for reference
3376
+ dim = 1
3377
+ beg = sys.getrefcount(dim)
3378
+ np.zeros([dim] * 10)
3379
+ assert_(sys.getrefcount(dim) == beg)
3380
+ np.ones([dim] * 10)
3381
+ assert_(sys.getrefcount(dim) == beg)
3382
+ np.empty([dim] * 10)
3383
+ assert_(sys.getrefcount(dim) == beg)
3384
+ np.full([dim] * 10, 0)
3385
+ assert_(sys.getrefcount(dim) == beg)
3386
+
3387
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
3388
+ @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc")
3389
+ @pytest.mark.parametrize("func", [np.empty, np.zeros, np.ones, np.full])
3390
+ def test_signatures(self, func):
3391
+ sig = inspect.signature(func)
3392
+ params = sig.parameters
3393
+
3394
+ assert len(params) in {5, 6}
3395
+
3396
+ assert 'shape' in params
3397
+ assert params["shape"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
3398
+ assert params["shape"].default is inspect.Parameter.empty
3399
+
3400
+ assert 'dtype' in params
3401
+ assert params["dtype"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
3402
+ assert params["dtype"].default is None
3403
+
3404
+ assert 'order' in params
3405
+ assert params["order"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
3406
+ assert params["order"].default == "C"
3407
+
3408
+ assert 'device' in params
3409
+ assert params["device"].kind is inspect.Parameter.KEYWORD_ONLY
3410
+ assert params["device"].default is None
3411
+
3412
+ assert 'like' in params
3413
+ assert params["like"].kind is inspect.Parameter.KEYWORD_ONLY
3414
+ assert params["like"].default is None
3415
+
3416
+
3417
+ class TestLikeFuncs:
3418
+ '''Test ones_like, zeros_like, empty_like and full_like'''
3419
+
3420
+ def compare_array_value(self, dz, value, fill_value):
3421
+ if value is not None:
3422
+ if fill_value:
3423
+ # Conversion is close to what np.full_like uses
3424
+ # but we may want to convert directly in the future
3425
+ # which may result in errors (where this does not).
3426
+ z = np.array(value).astype(dz.dtype)
3427
+ assert_(np.all(dz == z))
3428
+ else:
3429
+ assert_(np.all(dz == value))
3430
+
3431
+ def check_like_function(self, like_function, value, fill_value=False):
3432
+ data = [
3433
+ # Array scalars
3434
+ (np.array(3.), None),
3435
+ (np.array(3), 'f8'),
3436
+ # 1D arrays
3437
+ (np.arange(6, dtype='f4'), None),
3438
+ (np.arange(6), 'c16'),
3439
+ # 2D C-layout arrays
3440
+ (np.arange(6).reshape(2, 3), None),
3441
+ (np.arange(6).reshape(3, 2), 'i1'),
3442
+ # 2D F-layout arrays
3443
+ (np.arange(6).reshape((2, 3), order='F'), None),
3444
+ (np.arange(6).reshape((3, 2), order='F'), 'i1'),
3445
+ # 3D C-layout arrays
3446
+ (np.arange(24).reshape(2, 3, 4), None),
3447
+ (np.arange(24).reshape(4, 3, 2), 'f4'),
3448
+ # 3D F-layout arrays
3449
+ (np.arange(24).reshape((2, 3, 4), order='F'), None),
3450
+ (np.arange(24).reshape((4, 3, 2), order='F'), 'f4'),
3451
+ # 3D non-C/F-layout arrays
3452
+ (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),
3453
+ (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), '?'),
3454
+ ]
3455
+ shapes = [(), (5,), (5, 6,), (5, 6, 7,)]
3456
+
3457
+ if fill_value:
3458
+ fill_kwarg = {'fill_value': value}
3459
+ else:
3460
+ fill_kwarg = {}
3461
+ for d, dtype in data:
3462
+ # default (K) order, dtype
3463
+ dz = like_function(d, dtype=dtype, **fill_kwarg)
3464
+ assert_equal(dz.shape, d.shape)
3465
+ assert_equal(np.array(dz.strides) * d.dtype.itemsize,
3466
+ np.array(d.strides) * dz.dtype.itemsize)
3467
+ assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous)
3468
+ assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous)
3469
+ if dtype is None:
3470
+ assert_equal(dz.dtype, d.dtype)
3471
+ else:
3472
+ assert_equal(dz.dtype, np.dtype(dtype))
3473
+ self.compare_array_value(dz, value, fill_value)
3474
+
3475
+ # C order, default dtype
3476
+ dz = like_function(d, order='C', dtype=dtype, **fill_kwarg)
3477
+ assert_equal(dz.shape, d.shape)
3478
+ assert_(dz.flags.c_contiguous)
3479
+ if dtype is None:
3480
+ assert_equal(dz.dtype, d.dtype)
3481
+ else:
3482
+ assert_equal(dz.dtype, np.dtype(dtype))
3483
+ self.compare_array_value(dz, value, fill_value)
3484
+
3485
+ # F order, default dtype
3486
+ dz = like_function(d, order='F', dtype=dtype, **fill_kwarg)
3487
+ assert_equal(dz.shape, d.shape)
3488
+ assert_(dz.flags.f_contiguous)
3489
+ if dtype is None:
3490
+ assert_equal(dz.dtype, d.dtype)
3491
+ else:
3492
+ assert_equal(dz.dtype, np.dtype(dtype))
3493
+ self.compare_array_value(dz, value, fill_value)
3494
+
3495
+ # A order
3496
+ dz = like_function(d, order='A', dtype=dtype, **fill_kwarg)
3497
+ assert_equal(dz.shape, d.shape)
3498
+ if d.flags.f_contiguous:
3499
+ assert_(dz.flags.f_contiguous)
3500
+ else:
3501
+ assert_(dz.flags.c_contiguous)
3502
+ if dtype is None:
3503
+ assert_equal(dz.dtype, d.dtype)
3504
+ else:
3505
+ assert_equal(dz.dtype, np.dtype(dtype))
3506
+ self.compare_array_value(dz, value, fill_value)
3507
+
3508
+ # Test the 'shape' parameter
3509
+ for s in shapes:
3510
+ for o in 'CFA':
3511
+ sz = like_function(d, dtype=dtype, shape=s, order=o,
3512
+ **fill_kwarg)
3513
+ assert_equal(sz.shape, s)
3514
+ if dtype is None:
3515
+ assert_equal(sz.dtype, d.dtype)
3516
+ else:
3517
+ assert_equal(sz.dtype, np.dtype(dtype))
3518
+ if o == 'C' or (o == 'A' and d.flags.c_contiguous):
3519
+ assert_(sz.flags.c_contiguous)
3520
+ elif o == 'F' or (o == 'A' and d.flags.f_contiguous):
3521
+ assert_(sz.flags.f_contiguous)
3522
+ self.compare_array_value(sz, value, fill_value)
3523
+
3524
+ if (d.ndim != len(s)):
3525
+ assert_equal(np.argsort(like_function(d, dtype=dtype,
3526
+ shape=s, order='K',
3527
+ **fill_kwarg).strides),
3528
+ np.argsort(np.empty(s, dtype=dtype,
3529
+ order='C').strides))
3530
+ else:
3531
+ assert_equal(np.argsort(like_function(d, dtype=dtype,
3532
+ shape=s, order='K',
3533
+ **fill_kwarg).strides),
3534
+ np.argsort(d.strides))
3535
+
3536
+ # Test the 'subok' parameter
3537
+ class MyNDArray(np.ndarray):
3538
+ pass
3539
+
3540
+ a = np.array([[1, 2], [3, 4]]).view(MyNDArray)
3541
+
3542
+ b = like_function(a, **fill_kwarg)
3543
+ assert_(type(b) is MyNDArray)
3544
+
3545
+ b = like_function(a, subok=False, **fill_kwarg)
3546
+ assert_(type(b) is not MyNDArray)
3547
+
3548
+ # Test invalid dtype
3549
+ with assert_raises(TypeError):
3550
+ a = np.array(b"abc")
3551
+ like_function(a, dtype="S-1", **fill_kwarg)
3552
+
3553
+ def test_ones_like(self):
3554
+ self.check_like_function(np.ones_like, 1)
3555
+
3556
+ def test_zeros_like(self):
3557
+ self.check_like_function(np.zeros_like, 0)
3558
+
3559
+ def test_empty_like(self):
3560
+ self.check_like_function(np.empty_like, None)
3561
+
3562
+ def test_filled_like(self):
3563
+ self.check_like_function(np.full_like, 0, True)
3564
+ self.check_like_function(np.full_like, 1, True)
3565
+ # Large integers may overflow, but using int64 is OK (casts)
3566
+ # see also gh-27075
3567
+ with pytest.raises(OverflowError):
3568
+ np.full_like(np.ones(3, dtype=np.int8), 1000)
3569
+ self.check_like_function(np.full_like, np.int64(1000), True)
3570
+ self.check_like_function(np.full_like, 123.456, True)
3571
+ # Inf to integer casts cause invalid-value errors: ignore them.
3572
+ with np.errstate(invalid="ignore"):
3573
+ self.check_like_function(np.full_like, np.inf, True)
3574
+
3575
+ @pytest.mark.parametrize('likefunc', [np.empty_like, np.full_like,
3576
+ np.zeros_like, np.ones_like])
3577
+ @pytest.mark.parametrize('dtype', [str, bytes])
3578
+ def test_dtype_str_bytes(self, likefunc, dtype):
3579
+ # Regression test for gh-19860
3580
+ a = np.arange(16).reshape(2, 8)
3581
+ b = a[:, ::2] # Ensure b is not contiguous.
3582
+ kwargs = {'fill_value': ''} if likefunc == np.full_like else {}
3583
+ result = likefunc(b, dtype=dtype, **kwargs)
3584
+ if dtype == str:
3585
+ assert result.strides == (16, 4)
3586
+ else:
3587
+ # dtype is bytes
3588
+ assert result.strides == (4, 1)
3589
+
3590
+
3591
+ class TestCorrelate:
3592
+ def _setup(self, dt):
3593
+ self.x = np.array([1, 2, 3, 4, 5], dtype=dt)
3594
+ self.xs = np.arange(1, 20)[::3]
3595
+ self.y = np.array([-1, -2, -3], dtype=dt)
3596
+ self.z1 = np.array([-3., -8., -14., -20., -26., -14., -5.], dtype=dt)
3597
+ self.z1_4 = np.array([-2., -5., -8., -11., -14., -5.], dtype=dt)
3598
+ self.z1r = np.array([-15., -22., -22., -16., -10., -4., -1.], dtype=dt)
3599
+ self.z2 = np.array([-5., -14., -26., -20., -14., -8., -3.], dtype=dt)
3600
+ self.z2r = np.array([-1., -4., -10., -16., -22., -22., -15.], dtype=dt)
3601
+ self.zs = np.array([-3., -14., -30., -48., -66., -84.,
3602
+ -102., -54., -19.], dtype=dt)
3603
+
3604
+ def test_float(self):
3605
+ self._setup(float)
3606
+ z = np.correlate(self.x, self.y, 'full')
3607
+ assert_array_almost_equal(z, self.z1)
3608
+ z = np.correlate(self.x, self.y[:-1], 'full')
3609
+ assert_array_almost_equal(z, self.z1_4)
3610
+ z = np.correlate(self.y, self.x, 'full')
3611
+ assert_array_almost_equal(z, self.z2)
3612
+ z = np.correlate(self.x[::-1], self.y, 'full')
3613
+ assert_array_almost_equal(z, self.z1r)
3614
+ z = np.correlate(self.y, self.x[::-1], 'full')
3615
+ assert_array_almost_equal(z, self.z2r)
3616
+ z = np.correlate(self.xs, self.y, 'full')
3617
+ assert_array_almost_equal(z, self.zs)
3618
+
3619
+ def test_object(self):
3620
+ self._setup(Decimal)
3621
+ z = np.correlate(self.x, self.y, 'full')
3622
+ assert_array_almost_equal(z, self.z1)
3623
+ z = np.correlate(self.y, self.x, 'full')
3624
+ assert_array_almost_equal(z, self.z2)
3625
+
3626
+ def test_no_overwrite(self):
3627
+ d = np.ones(100)
3628
+ k = np.ones(3)
3629
+ np.correlate(d, k)
3630
+ assert_array_equal(d, np.ones(100))
3631
+ assert_array_equal(k, np.ones(3))
3632
+
3633
+ def test_complex(self):
3634
+ x = np.array([1, 2, 3, 4 + 1j], dtype=complex)
3635
+ y = np.array([-1, -2j, 3 + 1j], dtype=complex)
3636
+ r_z = np.array([3 - 1j, 6, 8 + 1j, 11 + 5j, -5 + 8j, -4 - 1j], dtype=complex)
3637
+ r_z = r_z[::-1].conjugate()
3638
+ z = np.correlate(y, x, mode='full')
3639
+ assert_array_almost_equal(z, r_z)
3640
+
3641
+ def test_zero_size(self):
3642
+ with pytest.raises(ValueError):
3643
+ np.correlate(np.array([]), np.ones(1000), mode='full')
3644
+ with pytest.raises(ValueError):
3645
+ np.correlate(np.ones(1000), np.array([]), mode='full')
3646
+
3647
+ def test_mode(self):
3648
+ d = np.ones(100)
3649
+ k = np.ones(3)
3650
+ default_mode = np.correlate(d, k, mode='valid')
3651
+ with assert_raises(ValueError):
3652
+ np.correlate(d, k, mode='v')
3653
+ # integer mode
3654
+ with assert_raises(ValueError):
3655
+ np.correlate(d, k, mode=-1)
3656
+ # assert_array_equal(np.correlate(d, k, mode=), default_mode)
3657
+ # illegal arguments
3658
+ with assert_raises(TypeError):
3659
+ np.correlate(d, k, mode=None)
3660
+
3661
+
3662
+ class TestConvolve:
3663
+ def test_object(self):
3664
+ d = [1.] * 100
3665
+ k = [1.] * 3
3666
+ assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))
3667
+
3668
+ def test_no_overwrite(self):
3669
+ d = np.ones(100)
3670
+ k = np.ones(3)
3671
+ np.convolve(d, k)
3672
+ assert_array_equal(d, np.ones(100))
3673
+ assert_array_equal(k, np.ones(3))
3674
+
3675
+ def test_mode(self):
3676
+ d = np.ones(100)
3677
+ k = np.ones(3)
3678
+ default_mode = np.convolve(d, k, mode='full')
3679
+ with assert_raises(ValueError):
3680
+ np.convolve(d, k, mode='f')
3681
+ # integer mode
3682
+ with assert_raises(ValueError):
3683
+ np.convolve(d, k, mode=-1)
3684
+ assert_array_equal(np.convolve(d, k, mode=2), default_mode)
3685
+ # illegal arguments
3686
+ with assert_raises(TypeError):
3687
+ np.convolve(d, k, mode=None)
3688
+
3689
+ def test_convolve_empty_input_error_message(self):
3690
+ """
3691
+ Test that convolve raises the correct error message when inputs are empty.
3692
+ Regression test for gh-30272 (variable swapping bug).
3693
+ """
3694
+ with pytest.raises(ValueError, match="a cannot be empty"):
3695
+ np.convolve(np.array([]), np.array([1, 2]))
3696
+
3697
+ with pytest.raises(ValueError, match="v cannot be empty"):
3698
+ np.convolve(np.array([1, 2]), np.array([]))
3699
+
3700
+ class TestArgwhere:
3701
+
3702
+ @pytest.mark.parametrize('nd', [0, 1, 2])
3703
+ def test_nd(self, nd):
3704
+ # get an nd array with multiple elements in every dimension
3705
+ x = np.empty((2,) * nd, bool)
3706
+
3707
+ # none
3708
+ x[...] = False
3709
+ assert_equal(np.argwhere(x).shape, (0, nd))
3710
+
3711
+ # only one
3712
+ x[...] = False
3713
+ x.flat[0] = True
3714
+ assert_equal(np.argwhere(x).shape, (1, nd))
3715
+
3716
+ # all but one
3717
+ x[...] = True
3718
+ x.flat[0] = False
3719
+ assert_equal(np.argwhere(x).shape, (x.size - 1, nd))
3720
+
3721
+ # all
3722
+ x[...] = True
3723
+ assert_equal(np.argwhere(x).shape, (x.size, nd))
3724
+
3725
+ def test_2D(self):
3726
+ x = np.arange(6).reshape((2, 3))
3727
+ assert_array_equal(np.argwhere(x > 1),
3728
+ [[0, 2],
3729
+ [1, 0],
3730
+ [1, 1],
3731
+ [1, 2]])
3732
+
3733
+ def test_list(self):
3734
+ assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]])
3735
+
3736
+
3737
+ class TestRoll:
3738
+ def test_roll1d(self):
3739
+ x = np.arange(10)
3740
+ xr = np.roll(x, 2)
3741
+ assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]))
3742
+
3743
+ def test_roll2d(self):
3744
+ x2 = np.reshape(np.arange(10), (2, 5))
3745
+ x2r = np.roll(x2, 1)
3746
+ assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]))
3747
+
3748
+ x2r = np.roll(x2, 1, axis=0)
3749
+ assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
3750
+
3751
+ x2r = np.roll(x2, 1, axis=1)
3752
+ assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
3753
+
3754
+ # Roll multiple axes at once.
3755
+ x2r = np.roll(x2, 1, axis=(0, 1))
3756
+ assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
3757
+
3758
+ x2r = np.roll(x2, (1, 0), axis=(0, 1))
3759
+ assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
3760
+
3761
+ x2r = np.roll(x2, (-1, 0), axis=(0, 1))
3762
+ assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
3763
+
3764
+ x2r = np.roll(x2, (0, 1), axis=(0, 1))
3765
+ assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
3766
+
3767
+ x2r = np.roll(x2, (0, -1), axis=(0, 1))
3768
+ assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]))
3769
+
3770
+ x2r = np.roll(x2, (1, 1), axis=(0, 1))
3771
+ assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
3772
+
3773
+ x2r = np.roll(x2, (-1, -1), axis=(0, 1))
3774
+ assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]]))
3775
+
3776
+ # Roll the same axis multiple times.
3777
+ x2r = np.roll(x2, 1, axis=(0, 0))
3778
+ assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]))
3779
+
3780
+ x2r = np.roll(x2, 1, axis=(1, 1))
3781
+ assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]))
3782
+
3783
+ # Roll more than one turn in either direction.
3784
+ x2r = np.roll(x2, 6, axis=1)
3785
+ assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
3786
+
3787
+ x2r = np.roll(x2, -4, axis=1)
3788
+ assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
3789
+
3790
+ def test_roll_empty(self):
3791
+ x = np.array([])
3792
+ assert_equal(np.roll(x, 1), np.array([]))
3793
+
3794
+ def test_roll_unsigned_shift(self):
3795
+ x = np.arange(4)
3796
+ shift = np.uint16(2)
3797
+ assert_equal(np.roll(x, shift), np.roll(x, 2))
3798
+
3799
+ shift = np.uint64(2**63 + 2)
3800
+ assert_equal(np.roll(x, shift), np.roll(x, 2))
3801
+
3802
+ def test_roll_big_int(self):
3803
+ x = np.arange(4)
3804
+ assert_equal(np.roll(x, 2**100), x)
3805
+
3806
+
3807
+ class TestRollaxis:
3808
+
3809
+ # expected shape indexed by (axis, start) for array of
3810
+ # shape (1, 2, 3, 4)
3811
+ tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4),
3812
+ (0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4),
3813
+ (0, 4): (2, 3, 4, 1),
3814
+ (1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4),
3815
+ (1, 2): (1, 2, 3, 4), (1, 3): (1, 3, 2, 4),
3816
+ (1, 4): (1, 3, 4, 2),
3817
+ (2, 0): (3, 1, 2, 4), (2, 1): (1, 3, 2, 4),
3818
+ (2, 2): (1, 2, 3, 4), (2, 3): (1, 2, 3, 4),
3819
+ (2, 4): (1, 2, 4, 3),
3820
+ (3, 0): (4, 1, 2, 3), (3, 1): (1, 4, 2, 3),
3821
+ (3, 2): (1, 2, 4, 3), (3, 3): (1, 2, 3, 4),
3822
+ (3, 4): (1, 2, 3, 4)}
3823
+
3824
+ def test_exceptions(self):
3825
+ a = np.arange(1 * 2 * 3 * 4).reshape(1, 2, 3, 4)
3826
+ assert_raises(AxisError, np.rollaxis, a, -5, 0)
3827
+ assert_raises(AxisError, np.rollaxis, a, 0, -5)
3828
+ assert_raises(AxisError, np.rollaxis, a, 4, 0)
3829
+ assert_raises(AxisError, np.rollaxis, a, 0, 5)
3830
+
3831
+ def test_results(self):
3832
+ a = np.arange(1 * 2 * 3 * 4).reshape(1, 2, 3, 4).copy()
3833
+ aind = np.indices(a.shape)
3834
+ assert_(a.flags['OWNDATA'])
3835
+ for (i, j) in self.tgtshape:
3836
+ # positive axis, positive start
3837
+ res = np.rollaxis(a, axis=i, start=j)
3838
+ i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
3839
+ assert_(np.all(res[i0, i1, i2, i3] == a))
3840
+ assert_(res.shape == self.tgtshape[(i, j)], str((i, j)))
3841
+ assert_(not res.flags['OWNDATA'])
3842
+
3843
+ # negative axis, positive start
3844
+ ip = i + 1
3845
+ res = np.rollaxis(a, axis=-ip, start=j)
3846
+ i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
3847
+ assert_(np.all(res[i0, i1, i2, i3] == a))
3848
+ assert_(res.shape == self.tgtshape[(4 - ip, j)])
3849
+ assert_(not res.flags['OWNDATA'])
3850
+
3851
+ # positive axis, negative start
3852
+ jp = j + 1 if j < 4 else j
3853
+ res = np.rollaxis(a, axis=i, start=-jp)
3854
+ i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
3855
+ assert_(np.all(res[i0, i1, i2, i3] == a))
3856
+ assert_(res.shape == self.tgtshape[(i, 4 - jp)])
3857
+ assert_(not res.flags['OWNDATA'])
3858
+
3859
+ # negative axis, negative start
3860
+ ip = i + 1
3861
+ jp = j + 1 if j < 4 else j
3862
+ res = np.rollaxis(a, axis=-ip, start=-jp)
3863
+ i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
3864
+ assert_(np.all(res[i0, i1, i2, i3] == a))
3865
+ assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)])
3866
+ assert_(not res.flags['OWNDATA'])
3867
+
3868
+
3869
+ class TestMoveaxis:
3870
+ def test_move_to_end(self):
3871
+ x = np.random.randn(5, 6, 7)
3872
+ for source, expected in [(0, (6, 7, 5)),
3873
+ (1, (5, 7, 6)),
3874
+ (2, (5, 6, 7)),
3875
+ (-1, (5, 6, 7))]:
3876
+ actual = np.moveaxis(x, source, -1).shape
3877
+ assert_(actual, expected)
3878
+
3879
+ def test_move_new_position(self):
3880
+ x = np.random.randn(1, 2, 3, 4)
3881
+ for source, destination, expected in [
3882
+ (0, 1, (2, 1, 3, 4)),
3883
+ (1, 2, (1, 3, 2, 4)),
3884
+ (1, -1, (1, 3, 4, 2)),
3885
+ ]:
3886
+ actual = np.moveaxis(x, source, destination).shape
3887
+ assert_(actual, expected)
3888
+
3889
+ def test_preserve_order(self):
3890
+ x = np.zeros((1, 2, 3, 4))
3891
+ for source, destination in [
3892
+ (0, 0),
3893
+ (3, -1),
3894
+ (-1, 3),
3895
+ ([0, -1], [0, -1]),
3896
+ ([2, 0], [2, 0]),
3897
+ (range(4), range(4)),
3898
+ ]:
3899
+ actual = np.moveaxis(x, source, destination).shape
3900
+ assert_(actual, (1, 2, 3, 4))
3901
+
3902
+ def test_move_multiples(self):
3903
+ x = np.zeros((0, 1, 2, 3))
3904
+ for source, destination, expected in [
3905
+ ([0, 1], [2, 3], (2, 3, 0, 1)),
3906
+ ([2, 3], [0, 1], (2, 3, 0, 1)),
3907
+ ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)),
3908
+ ([3, 0], [1, 0], (0, 3, 1, 2)),
3909
+ ([0, 3], [0, 1], (0, 3, 1, 2)),
3910
+ ]:
3911
+ actual = np.moveaxis(x, source, destination).shape
3912
+ assert_(actual, expected)
3913
+
3914
+ def test_errors(self):
3915
+ x = np.random.randn(1, 2, 3)
3916
+ assert_raises_regex(AxisError, 'source.*out of bounds',
3917
+ np.moveaxis, x, 3, 0)
3918
+ assert_raises_regex(AxisError, 'source.*out of bounds',
3919
+ np.moveaxis, x, -4, 0)
3920
+ assert_raises_regex(AxisError, 'destination.*out of bounds',
3921
+ np.moveaxis, x, 0, 5)
3922
+ assert_raises_regex(ValueError, 'repeated axis in `source`',
3923
+ np.moveaxis, x, [0, 0], [0, 1])
3924
+ assert_raises_regex(ValueError, 'repeated axis in `destination`',
3925
+ np.moveaxis, x, [0, 1], [1, 1])
3926
+ assert_raises_regex(ValueError, 'must have the same number',
3927
+ np.moveaxis, x, 0, [0, 1])
3928
+ assert_raises_regex(ValueError, 'must have the same number',
3929
+ np.moveaxis, x, [0, 1], [0])
3930
+
3931
+ def test_array_likes(self):
3932
+ x = np.ma.zeros((1, 2, 3))
3933
+ result = np.moveaxis(x, 0, 0)
3934
+ assert_(x.shape, result.shape)
3935
+ assert_(isinstance(result, np.ma.MaskedArray))
3936
+
3937
+ x = [1, 2, 3]
3938
+ result = np.moveaxis(x, 0, 0)
3939
+ assert_(x, list(result))
3940
+ assert_(isinstance(result, np.ndarray))
3941
+
3942
+
3943
+ class TestCross:
3944
+ @pytest.mark.filterwarnings(
3945
+ "ignore:.*2-dimensional vectors.*:DeprecationWarning"
3946
+ )
3947
+ def test_2x2(self):
3948
+ u = [1, 2]
3949
+ v = [3, 4]
3950
+ z = -2
3951
+ cp = np.cross(u, v)
3952
+ assert_equal(cp, z)
3953
+ cp = np.cross(v, u)
3954
+ assert_equal(cp, -z)
3955
+
3956
+ @pytest.mark.filterwarnings(
3957
+ "ignore:.*2-dimensional vectors.*:DeprecationWarning"
3958
+ )
3959
+ def test_2x3(self):
3960
+ u = [1, 2]
3961
+ v = [3, 4, 5]
3962
+ z = np.array([10, -5, -2])
3963
+ cp = np.cross(u, v)
3964
+ assert_equal(cp, z)
3965
+ cp = np.cross(v, u)
3966
+ assert_equal(cp, -z)
3967
+
3968
+ def test_3x3(self):
3969
+ u = [1, 2, 3]
3970
+ v = [4, 5, 6]
3971
+ z = np.array([-3, 6, -3])
3972
+ cp = np.cross(u, v)
3973
+ assert_equal(cp, z)
3974
+ cp = np.cross(v, u)
3975
+ assert_equal(cp, -z)
3976
+
3977
+ @pytest.mark.filterwarnings(
3978
+ "ignore:.*2-dimensional vectors.*:DeprecationWarning"
3979
+ )
3980
+ def test_broadcasting(self):
3981
+ # Ticket #2624 (Trac #2032)
3982
+ u = np.tile([1, 2], (11, 1))
3983
+ v = np.tile([3, 4], (11, 1))
3984
+ z = -2
3985
+ assert_equal(np.cross(u, v), z)
3986
+ assert_equal(np.cross(v, u), -z)
3987
+ assert_equal(np.cross(u, u), 0)
3988
+
3989
+ u = np.tile([1, 2], (11, 1)).T
3990
+ v = np.tile([3, 4, 5], (11, 1))
3991
+ z = np.tile([10, -5, -2], (11, 1))
3992
+ assert_equal(np.cross(u, v, axisa=0), z)
3993
+ assert_equal(np.cross(v, u.T), -z)
3994
+ assert_equal(np.cross(v, v), 0)
3995
+
3996
+ u = np.tile([1, 2, 3], (11, 1)).T
3997
+ v = np.tile([3, 4], (11, 1)).T
3998
+ z = np.tile([-12, 9, -2], (11, 1))
3999
+ assert_equal(np.cross(u, v, axisa=0, axisb=0), z)
4000
+ assert_equal(np.cross(v.T, u.T), -z)
4001
+ assert_equal(np.cross(u.T, u.T), 0)
4002
+
4003
+ u = np.tile([1, 2, 3], (5, 1))
4004
+ v = np.tile([4, 5, 6], (5, 1)).T
4005
+ z = np.tile([-3, 6, -3], (5, 1))
4006
+ assert_equal(np.cross(u, v, axisb=0), z)
4007
+ assert_equal(np.cross(v.T, u), -z)
4008
+ assert_equal(np.cross(u, u), 0)
4009
+
4010
+ @pytest.mark.filterwarnings(
4011
+ "ignore:.*2-dimensional vectors.*:DeprecationWarning"
4012
+ )
4013
+ def test_broadcasting_shapes(self):
4014
+ u = np.ones((2, 1, 3))
4015
+ v = np.ones((5, 3))
4016
+ assert_equal(np.cross(u, v).shape, (2, 5, 3))
4017
+ u = np.ones((10, 3, 5))
4018
+ v = np.ones((2, 5))
4019
+ assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3))
4020
+ assert_raises(AxisError, np.cross, u, v, axisa=1, axisb=2)
4021
+ assert_raises(AxisError, np.cross, u, v, axisa=3, axisb=0)
4022
+ u = np.ones((10, 3, 5, 7))
4023
+ v = np.ones((5, 7, 2))
4024
+ assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7))
4025
+ assert_raises(AxisError, np.cross, u, v, axisa=-5, axisb=2)
4026
+ assert_raises(AxisError, np.cross, u, v, axisa=1, axisb=-4)
4027
+ # gh-5885
4028
+ u = np.ones((3, 4, 2))
4029
+ for axisc in range(-2, 2):
4030
+ assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4))
4031
+
4032
+ def test_uint8_int32_mixed_dtypes(self):
4033
+ # regression test for gh-19138
4034
+ u = np.array([[195, 8, 9]], np.uint8)
4035
+ v = np.array([250, 166, 68], np.int32)
4036
+ z = np.array([[950, 11010, -30370]], dtype=np.int32)
4037
+ assert_equal(np.cross(v, u), z)
4038
+ assert_equal(np.cross(u, v), -z)
4039
+
4040
+ @pytest.mark.parametrize("a, b", [(0, [1, 2]), ([1, 2], 3)])
4041
+ def test_zero_dimension(self, a, b):
4042
+ with pytest.raises(ValueError) as exc:
4043
+ np.cross(a, b)
4044
+ assert "At least one array has zero dimension" in str(exc.value)
4045
+
4046
+
4047
+ def test_outer_out_param():
4048
+ arr1 = np.ones((5,))
4049
+ arr2 = np.ones((2,))
4050
+ arr3 = np.linspace(-2, 2, 5)
4051
+ out1 = np.ndarray(shape=(5, 5))
4052
+ out2 = np.ndarray(shape=(2, 5))
4053
+ res1 = np.outer(arr1, arr3, out1)
4054
+ assert_equal(res1, out1)
4055
+ assert_equal(np.outer(arr2, arr3, out2), out2)
4056
+
4057
+
4058
+ class TestIndices:
4059
+
4060
+ def test_simple(self):
4061
+ [x, y] = np.indices((4, 3))
4062
+ assert_array_equal(x, np.array([[0, 0, 0],
4063
+ [1, 1, 1],
4064
+ [2, 2, 2],
4065
+ [3, 3, 3]]))
4066
+ assert_array_equal(y, np.array([[0, 1, 2],
4067
+ [0, 1, 2],
4068
+ [0, 1, 2],
4069
+ [0, 1, 2]]))
4070
+
4071
+ def test_single_input(self):
4072
+ [x] = np.indices((4,))
4073
+ assert_array_equal(x, np.array([0, 1, 2, 3]))
4074
+
4075
+ [x] = np.indices((4,), sparse=True)
4076
+ assert_array_equal(x, np.array([0, 1, 2, 3]))
4077
+
4078
+ def test_scalar_input(self):
4079
+ assert_array_equal([], np.indices(()))
4080
+ assert_array_equal([], np.indices((), sparse=True))
4081
+ assert_array_equal([[]], np.indices((0,)))
4082
+ assert_array_equal([[]], np.indices((0,), sparse=True))
4083
+
4084
+ def test_sparse(self):
4085
+ [x, y] = np.indices((4, 3), sparse=True)
4086
+ assert_array_equal(x, np.array([[0], [1], [2], [3]]))
4087
+ assert_array_equal(y, np.array([[0, 1, 2]]))
4088
+
4089
+ @pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64])
4090
+ @pytest.mark.parametrize("dims", [(), (0,), (4, 3)])
4091
+ def test_return_type(self, dtype, dims):
4092
+ inds = np.indices(dims, dtype=dtype)
4093
+ assert_(inds.dtype == dtype)
4094
+
4095
+ for arr in np.indices(dims, dtype=dtype, sparse=True):
4096
+ assert_(arr.dtype == dtype)
4097
+
4098
+
4099
+ class TestRequire:
4100
+ flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS',
4101
+ 'F', 'F_CONTIGUOUS', 'FORTRAN',
4102
+ 'A', 'ALIGNED',
4103
+ 'W', 'WRITEABLE',
4104
+ 'O', 'OWNDATA']
4105
+
4106
+ def generate_all_false(self, dtype):
4107
+ arr = np.zeros((2, 2), [('junk', 'i1'), ('a', dtype)])
4108
+ arr.setflags(write=False)
4109
+ a = arr['a']
4110
+ assert_(not a.flags['C'])
4111
+ assert_(not a.flags['F'])
4112
+ assert_(not a.flags['O'])
4113
+ assert_(not a.flags['W'])
4114
+ assert_(not a.flags['A'])
4115
+ return a
4116
+
4117
+ def set_and_check_flag(self, flag, dtype, arr):
4118
+ if dtype is None:
4119
+ dtype = arr.dtype
4120
+ b = np.require(arr, dtype, [flag])
4121
+ assert_(b.flags[flag])
4122
+ assert_(b.dtype == dtype)
4123
+
4124
+ # a further call to np.require ought to return the same array
4125
+ # unless OWNDATA is specified.
4126
+ c = np.require(b, None, [flag])
4127
+ if flag[0] != 'O':
4128
+ assert_(c is b)
4129
+ else:
4130
+ assert_(c.flags[flag])
4131
+
4132
+ def test_require_each(self):
4133
+
4134
+ id = ['f8', 'i4']
4135
+ fd = [None, 'f8', 'c16']
4136
+ for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names):
4137
+ a = self.generate_all_false(idtype)
4138
+ self.set_and_check_flag(flag, fdtype, a)
4139
+
4140
+ def test_unknown_requirement(self):
4141
+ a = self.generate_all_false('f8')
4142
+ assert_raises(KeyError, np.require, a, None, 'Q')
4143
+
4144
+ def test_non_array_input(self):
4145
+ a = np.require([1, 2, 3, 4], 'i4', ['C', 'A', 'O'])
4146
+ assert_(a.flags['O'])
4147
+ assert_(a.flags['C'])
4148
+ assert_(a.flags['A'])
4149
+ assert_(a.dtype == 'i4')
4150
+ assert_equal(a, [1, 2, 3, 4])
4151
+
4152
+ def test_C_and_F_simul(self):
4153
+ a = self.generate_all_false('f8')
4154
+ assert_raises(ValueError, np.require, a, None, ['C', 'F'])
4155
+
4156
+ def test_ensure_array(self):
4157
+ class ArraySubclass(np.ndarray):
4158
+ pass
4159
+
4160
+ a = ArraySubclass((2, 2))
4161
+ b = np.require(a, None, ['E'])
4162
+ assert_(type(b) is np.ndarray)
4163
+
4164
+ def test_preserve_subtype(self):
4165
+ class ArraySubclass(np.ndarray):
4166
+ pass
4167
+
4168
+ for flag in self.flag_names:
4169
+ a = ArraySubclass((2, 2))
4170
+ self.set_and_check_flag(flag, None, a)
4171
+
4172
+
4173
+ class TestBroadcast:
4174
+ def test_broadcast_in_args(self):
4175
+ # gh-5881
4176
+ arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)),
4177
+ np.empty((5, 1, 7))]
4178
+ mits = [np.broadcast(*arrs),
4179
+ np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])),
4180
+ np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])),
4181
+ np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])),
4182
+ np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])]
4183
+ for mit in mits:
4184
+ assert_equal(mit.shape, (5, 6, 7))
4185
+ assert_equal(mit.ndim, 3)
4186
+ assert_equal(mit.nd, 3)
4187
+ assert_equal(mit.numiter, 4)
4188
+ for a, ia in zip(arrs, mit.iters):
4189
+ assert_(a is ia.base)
4190
+
4191
+ def test_broadcast_single_arg(self):
4192
+ # gh-6899
4193
+ arrs = [np.empty((5, 6, 7))]
4194
+ mit = np.broadcast(*arrs)
4195
+ assert_equal(mit.shape, (5, 6, 7))
4196
+ assert_equal(mit.ndim, 3)
4197
+ assert_equal(mit.nd, 3)
4198
+ assert_equal(mit.numiter, 1)
4199
+ assert_(arrs[0] is mit.iters[0].base)
4200
+
4201
+ def test_number_of_arguments(self):
4202
+ arr = np.empty((5,))
4203
+ for j in range(70):
4204
+ arrs = [arr] * j
4205
+ if j > 64:
4206
+ assert_raises(ValueError, np.broadcast, *arrs)
4207
+ else:
4208
+ mit = np.broadcast(*arrs)
4209
+ assert_equal(mit.numiter, j)
4210
+
4211
+ def test_broadcast_error_kwargs(self):
4212
+ # gh-13455
4213
+ arrs = [np.empty((5, 6, 7))]
4214
+ mit = np.broadcast(*arrs)
4215
+ mit2 = np.broadcast(*arrs, **{}) # noqa: PIE804
4216
+ assert_equal(mit.shape, mit2.shape)
4217
+ assert_equal(mit.ndim, mit2.ndim)
4218
+ assert_equal(mit.nd, mit2.nd)
4219
+ assert_equal(mit.numiter, mit2.numiter)
4220
+ assert_(mit.iters[0].base is mit2.iters[0].base)
4221
+
4222
+ assert_raises(ValueError, np.broadcast, 1, x=1)
4223
+
4224
+ def test_shape_mismatch_error_message(self):
4225
+ with pytest.raises(ValueError, match=r"arg 0 with shape \(1, 3\) and "
4226
+ r"arg 2 with shape \(2,\)"):
4227
+ np.broadcast([[1, 2, 3]], [[4], [5]], [6, 7])
4228
+
4229
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
4230
+ @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc")
4231
+ def test_signatures(self):
4232
+ sig_new = inspect.signature(np.broadcast)
4233
+ assert len(sig_new.parameters) == 1
4234
+ assert "arrays" in sig_new.parameters
4235
+ assert sig_new.parameters["arrays"].kind == inspect.Parameter.VAR_POSITIONAL
4236
+
4237
+ sig_reset = inspect.signature(np.broadcast.reset)
4238
+ assert len(sig_reset.parameters) == 1
4239
+ assert "self" in sig_reset.parameters
4240
+ assert sig_reset.parameters["self"].kind == inspect.Parameter.POSITIONAL_ONLY
4241
+
4242
+
4243
+ class TestKeepdims:
4244
+
4245
+ class sub_array(np.ndarray):
4246
+ def sum(self, axis=None, dtype=None, out=None):
4247
+ return np.ndarray.sum(self, axis, dtype, out, keepdims=True)
4248
+
4249
+ def test_raise(self):
4250
+ sub_class = self.sub_array
4251
+ x = np.arange(30).view(sub_class)
4252
+ assert_raises(TypeError, np.sum, x, keepdims=True)
4253
+
4254
+
4255
+ class TestTensordot:
4256
+
4257
+ def test_zero_dimension(self):
4258
+ # Test resolution to issue #5663
4259
+ a = np.ndarray((3, 0))
4260
+ b = np.ndarray((0, 4))
4261
+ td = np.tensordot(a, b, (1, 0))
4262
+ assert_array_equal(td, np.dot(a, b))
4263
+ assert_array_equal(td, np.einsum('ij,jk', a, b))
4264
+
4265
+ def test_zero_dimensional(self):
4266
+ # gh-12130
4267
+ arr_0d = np.array(1)
4268
+ # contracting no axes is well defined
4269
+ ret = np.tensordot(arr_0d, arr_0d, ([], []))
4270
+ assert_array_equal(ret, arr_0d)
4271
+
4272
+
4273
+ class TestAsType:
4274
+
4275
+ def test_astype(self):
4276
+ data = [[1, 2], [3, 4]]
4277
+ actual = np.astype(
4278
+ np.array(data, dtype=np.int64), np.uint32
4279
+ )
4280
+ expected = np.array(data, dtype=np.uint32)
4281
+
4282
+ assert_array_equal(actual, expected)
4283
+ assert_equal(actual.dtype, expected.dtype)
4284
+
4285
+ assert np.shares_memory(
4286
+ actual, np.astype(actual, actual.dtype, copy=False)
4287
+ )
4288
+
4289
+ actual = np.astype(np.int64(10), np.float64)
4290
+ expected = np.float64(10)
4291
+ assert_equal(actual, expected)
4292
+ assert_equal(actual.dtype, expected.dtype)
4293
+
4294
+ with pytest.raises(TypeError, match="Input should be a NumPy array"):
4295
+ np.astype(data, np.float64)