numpy 2.5.2__cp315-cp315-win32.whl

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