numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

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