numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,2670 @@
1
+ import copy
2
+ import gc
3
+ import pickle
4
+ import sys
5
+ import tempfile
6
+ from io import BytesIO
7
+ from itertools import chain
8
+ from os import path
9
+
10
+ import pytest
11
+
12
+ import numpy as np
13
+ from numpy._utils import asbytes, asunicode
14
+ from numpy.exceptions import AxisError, ComplexWarning
15
+ from numpy.testing import (
16
+ HAS_REFCOUNT,
17
+ IS_64BIT,
18
+ IS_PYPY,
19
+ IS_PYSTON,
20
+ IS_WASM,
21
+ _assert_valid_refcount,
22
+ assert_,
23
+ assert_almost_equal,
24
+ assert_array_almost_equal,
25
+ assert_array_equal,
26
+ assert_equal,
27
+ assert_raises,
28
+ assert_raises_regex,
29
+ assert_warns,
30
+ suppress_warnings,
31
+ )
32
+ from numpy.testing._private.utils import _no_tracing, requires_memory
33
+
34
+
35
+ class TestRegression:
36
+ def test_invalid_round(self):
37
+ # Ticket #3
38
+ v = 4.7599999999999998
39
+ assert_array_equal(np.array([v]), np.array(v))
40
+
41
+ def test_mem_empty(self):
42
+ # Ticket #7
43
+ np.empty((1,), dtype=[('x', np.int64)])
44
+
45
+ def test_pickle_transposed(self):
46
+ # Ticket #16
47
+ a = np.transpose(np.array([[2, 9], [7, 0], [3, 8]]))
48
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
49
+ with BytesIO() as f:
50
+ pickle.dump(a, f, protocol=proto)
51
+ f.seek(0)
52
+ b = pickle.load(f)
53
+ assert_array_equal(a, b)
54
+
55
+ def test_dtype_names(self):
56
+ # Ticket #35
57
+ # Should succeed
58
+ np.dtype([(('name', 'label'), np.int32, 3)])
59
+
60
+ def test_reduce(self):
61
+ # Ticket #40
62
+ assert_almost_equal(np.add.reduce([1., .5], dtype=None), 1.5)
63
+
64
+ def test_zeros_order(self):
65
+ # Ticket #43
66
+ np.zeros([3], int, 'C')
67
+ np.zeros([3], order='C')
68
+ np.zeros([3], int, order='C')
69
+
70
+ def test_asarray_with_order(self):
71
+ # Check that nothing is done when order='F' and array C/F-contiguous
72
+ a = np.ones(2)
73
+ assert_(a is np.asarray(a, order='F'))
74
+
75
+ def test_ravel_with_order(self):
76
+ # Check that ravel works when order='F' and array C/F-contiguous
77
+ a = np.ones(2)
78
+ assert_(not a.ravel('F').flags.owndata)
79
+
80
+ def test_sort_bigendian(self):
81
+ # Ticket #47
82
+ a = np.linspace(0, 10, 11)
83
+ c = a.astype(np.dtype('<f8'))
84
+ c.sort()
85
+ assert_array_almost_equal(c, a)
86
+
87
+ def test_negative_nd_indexing(self):
88
+ # Ticket #49
89
+ c = np.arange(125).reshape((5, 5, 5))
90
+ origidx = np.array([-1, 0, 1])
91
+ idx = np.array(origidx)
92
+ c[idx]
93
+ assert_array_equal(idx, origidx)
94
+
95
+ def test_char_dump(self):
96
+ # Ticket #50
97
+ ca = np.char.array(np.arange(1000, 1010), itemsize=4)
98
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
99
+ with BytesIO() as f:
100
+ pickle.dump(ca, f, protocol=proto)
101
+ f.seek(0)
102
+ ca = np.load(f, allow_pickle=True)
103
+
104
+ def test_noncontiguous_fill(self):
105
+ # Ticket #58.
106
+ a = np.zeros((5, 3))
107
+ b = a[:, :2,]
108
+
109
+ def rs():
110
+ b.shape = (10,)
111
+
112
+ assert_raises(AttributeError, rs)
113
+
114
+ def test_bool(self):
115
+ # Ticket #60
116
+ np.bool(1) # Should succeed
117
+
118
+ def test_indexing1(self):
119
+ # Ticket #64
120
+ descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
121
+ buffer = ((([6j, 4j],),),)
122
+ h = np.array(buffer, dtype=descr)
123
+ h['x']['y']['z']
124
+
125
+ def test_indexing2(self):
126
+ # Ticket #65
127
+ descr = [('x', 'i4', (2,))]
128
+ buffer = ([3, 2],)
129
+ h = np.array(buffer, dtype=descr)
130
+ h['x']
131
+
132
+ def test_round(self):
133
+ # Ticket #67
134
+ x = np.array([1 + 2j])
135
+ assert_almost_equal(x**(-1), [1 / (1 + 2j)])
136
+
137
+ def test_scalar_compare(self):
138
+ # Trac Ticket #72
139
+ # https://github.com/numpy/numpy/issues/565
140
+ a = np.array(['test', 'auto'])
141
+ assert_array_equal(a == 'auto', np.array([False, True]))
142
+ assert_(a[1] == 'auto')
143
+ assert_(a[0] != 'auto')
144
+ b = np.linspace(0, 10, 11)
145
+ assert_array_equal(b != 'auto', np.ones(11, dtype=bool))
146
+ assert_(b[0] != 'auto')
147
+
148
+ def test_unicode_swapping(self):
149
+ # Ticket #79
150
+ ulen = 1
151
+ ucs_value = '\U0010FFFF'
152
+ ua = np.array([[[ucs_value * ulen] * 2] * 3] * 4, dtype=f'U{ulen}')
153
+ ua.view(ua.dtype.newbyteorder()) # Should succeed.
154
+
155
+ def test_object_array_fill(self):
156
+ # Ticket #86
157
+ x = np.zeros(1, 'O')
158
+ x.fill([])
159
+
160
+ def test_mem_dtype_align(self):
161
+ # Ticket #93
162
+ assert_raises(TypeError, np.dtype,
163
+ {'names': ['a'], 'formats': ['foo']}, align=1)
164
+
165
+ def test_endian_bool_indexing(self):
166
+ # Ticket #105
167
+ a = np.arange(10., dtype='>f8')
168
+ b = np.arange(10., dtype='<f8')
169
+ xa = np.where((a > 2) & (a < 6))
170
+ xb = np.where((b > 2) & (b < 6))
171
+ ya = ((a > 2) & (a < 6))
172
+ yb = ((b > 2) & (b < 6))
173
+ assert_array_almost_equal(xa, ya.nonzero())
174
+ assert_array_almost_equal(xb, yb.nonzero())
175
+ assert_(np.all(a[ya] > 0.5))
176
+ assert_(np.all(b[yb] > 0.5))
177
+
178
+ def test_endian_where(self):
179
+ # GitHub issue #369
180
+ net = np.zeros(3, dtype='>f4')
181
+ net[1] = 0.00458849
182
+ net[2] = 0.605202
183
+ max_net = net.max()
184
+ test = np.where(net <= 0., max_net, net)
185
+ correct = np.array([0.60520202, 0.00458849, 0.60520202])
186
+ assert_array_almost_equal(test, correct)
187
+
188
+ def test_endian_recarray(self):
189
+ # Ticket #2185
190
+ dt = np.dtype([
191
+ ('head', '>u4'),
192
+ ('data', '>u4', 2),
193
+ ])
194
+ buf = np.recarray(1, dtype=dt)
195
+ buf[0]['head'] = 1
196
+ buf[0]['data'][:] = [1, 1]
197
+
198
+ h = buf[0]['head']
199
+ d = buf[0]['data'][0]
200
+ buf[0]['head'] = h
201
+ buf[0]['data'][0] = d
202
+ assert_(buf[0]['head'] == 1)
203
+
204
+ def test_mem_dot(self):
205
+ # Ticket #106
206
+ x = np.random.randn(0, 1)
207
+ y = np.random.randn(10, 1)
208
+ # Dummy array to detect bad memory access:
209
+ _z = np.ones(10)
210
+ _dummy = np.empty((0, 10))
211
+ z = np.lib.stride_tricks.as_strided(_z, _dummy.shape, _dummy.strides)
212
+ np.dot(x, np.transpose(y), out=z)
213
+ assert_equal(_z, np.ones(10))
214
+ # Do the same for the built-in dot:
215
+ np._core.multiarray.dot(x, np.transpose(y), out=z)
216
+ assert_equal(_z, np.ones(10))
217
+
218
+ def test_arange_endian(self):
219
+ # Ticket #111
220
+ ref = np.arange(10)
221
+ x = np.arange(10, dtype='<f8')
222
+ assert_array_equal(ref, x)
223
+ x = np.arange(10, dtype='>f8')
224
+ assert_array_equal(ref, x)
225
+
226
+ def test_arange_inf_step(self):
227
+ ref = np.arange(0, 1, 10)
228
+ x = np.arange(0, 1, np.inf)
229
+ assert_array_equal(ref, x)
230
+
231
+ ref = np.arange(0, 1, -10)
232
+ x = np.arange(0, 1, -np.inf)
233
+ assert_array_equal(ref, x)
234
+
235
+ ref = np.arange(0, -1, -10)
236
+ x = np.arange(0, -1, -np.inf)
237
+ assert_array_equal(ref, x)
238
+
239
+ ref = np.arange(0, -1, 10)
240
+ x = np.arange(0, -1, np.inf)
241
+ assert_array_equal(ref, x)
242
+
243
+ def test_arange_underflow_stop_and_step(self):
244
+ finfo = np.finfo(np.float64)
245
+
246
+ ref = np.arange(0, finfo.eps, 2 * finfo.eps)
247
+ x = np.arange(0, finfo.eps, finfo.max)
248
+ assert_array_equal(ref, x)
249
+
250
+ ref = np.arange(0, finfo.eps, -2 * finfo.eps)
251
+ x = np.arange(0, finfo.eps, -finfo.max)
252
+ assert_array_equal(ref, x)
253
+
254
+ ref = np.arange(0, -finfo.eps, -2 * finfo.eps)
255
+ x = np.arange(0, -finfo.eps, -finfo.max)
256
+ assert_array_equal(ref, x)
257
+
258
+ ref = np.arange(0, -finfo.eps, 2 * finfo.eps)
259
+ x = np.arange(0, -finfo.eps, finfo.max)
260
+ assert_array_equal(ref, x)
261
+
262
+ def test_argmax(self):
263
+ # Ticket #119
264
+ a = np.random.normal(0, 1, (4, 5, 6, 7, 8))
265
+ for i in range(a.ndim):
266
+ a.argmax(i) # Should succeed
267
+
268
+ def test_mem_divmod(self):
269
+ # Ticket #126
270
+ for i in range(10):
271
+ divmod(np.array([i])[0], 10)
272
+
273
+ def test_hstack_invalid_dims(self):
274
+ # Ticket #128
275
+ x = np.arange(9).reshape((3, 3))
276
+ y = np.array([0, 0, 0])
277
+ assert_raises(ValueError, np.hstack, (x, y))
278
+
279
+ def test_squeeze_type(self):
280
+ # Ticket #133
281
+ a = np.array([3])
282
+ b = np.array(3)
283
+ assert_(type(a.squeeze()) is np.ndarray)
284
+ assert_(type(b.squeeze()) is np.ndarray)
285
+
286
+ def test_add_identity(self):
287
+ # Ticket #143
288
+ assert_equal(0, np.add.identity)
289
+
290
+ def test_numpy_float_python_long_addition(self):
291
+ # Check that numpy float and python longs can be added correctly.
292
+ a = np.float64(23.) + 2**135
293
+ assert_equal(a, 23. + 2**135)
294
+
295
+ def test_binary_repr_0(self):
296
+ # Ticket #151
297
+ assert_equal('0', np.binary_repr(0))
298
+
299
+ def test_rec_iterate(self):
300
+ # Ticket #160
301
+ descr = np.dtype([('i', int), ('f', float), ('s', '|S3')])
302
+ x = np.rec.array([(1, 1.1, '1.0'),
303
+ (2, 2.2, '2.0')], dtype=descr)
304
+ x[0].tolist()
305
+ list(x[0])
306
+
307
+ def test_unicode_string_comparison(self):
308
+ # Ticket #190
309
+ a = np.array('hello', np.str_)
310
+ b = np.array('world')
311
+ a == b
312
+
313
+ def test_tobytes_FORTRANORDER_discontiguous(self):
314
+ # Fix in r2836
315
+ # Create non-contiguous Fortran ordered array
316
+ x = np.array(np.random.rand(3, 3), order='F')[:, :2]
317
+ assert_array_almost_equal(x.ravel(), np.frombuffer(x.tobytes()))
318
+
319
+ def test_flat_assignment(self):
320
+ # Correct behaviour of ticket #194
321
+ x = np.empty((3, 1))
322
+ x.flat = np.arange(3)
323
+ assert_array_almost_equal(x, [[0], [1], [2]])
324
+ x.flat = np.arange(3, dtype=float)
325
+ assert_array_almost_equal(x, [[0], [1], [2]])
326
+
327
+ def test_broadcast_flat_assignment(self):
328
+ # Ticket #194
329
+ x = np.empty((3, 1))
330
+
331
+ def bfa():
332
+ x[:] = np.arange(3)
333
+
334
+ def bfb():
335
+ x[:] = np.arange(3, dtype=float)
336
+
337
+ assert_raises(ValueError, bfa)
338
+ assert_raises(ValueError, bfb)
339
+
340
+ @pytest.mark.xfail(IS_WASM, reason="not sure why")
341
+ @pytest.mark.parametrize("index",
342
+ [np.ones(10, dtype=bool), np.arange(10)],
343
+ ids=["boolean-arr-index", "integer-arr-index"])
344
+ def test_nonarray_assignment(self, index):
345
+ # See also Issue gh-2870, test for non-array assignment
346
+ # and equivalent unsafe casted array assignment
347
+ a = np.arange(10)
348
+
349
+ with pytest.raises(ValueError):
350
+ a[index] = np.nan
351
+
352
+ with np.errstate(invalid="warn"):
353
+ with pytest.warns(RuntimeWarning, match="invalid value"):
354
+ a[index] = np.array(np.nan) # Only warns
355
+
356
+ def test_unpickle_dtype_with_object(self):
357
+ # Implemented in r2840
358
+ dt = np.dtype([('x', int), ('y', np.object_), ('z', 'O')])
359
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
360
+ with BytesIO() as f:
361
+ pickle.dump(dt, f, protocol=proto)
362
+ f.seek(0)
363
+ dt_ = pickle.load(f)
364
+ assert_equal(dt, dt_)
365
+
366
+ def test_mem_array_creation_invalid_specification(self):
367
+ # Ticket #196
368
+ dt = np.dtype([('x', int), ('y', np.object_)])
369
+ # Wrong way
370
+ assert_raises(ValueError, np.array, [1, 'object'], dt)
371
+ # Correct way
372
+ np.array([(1, 'object')], dt)
373
+
374
+ def test_recarray_single_element(self):
375
+ # Ticket #202
376
+ a = np.array([1, 2, 3], dtype=np.int32)
377
+ b = a.copy()
378
+ r = np.rec.array(a, shape=1, formats=['3i4'], names=['d'])
379
+ assert_array_equal(a, b)
380
+ assert_equal(a, r[0][0])
381
+
382
+ def test_zero_sized_array_indexing(self):
383
+ # Ticket #205
384
+ tmp = np.array([])
385
+
386
+ def index_tmp():
387
+ tmp[np.array(10)]
388
+
389
+ assert_raises(IndexError, index_tmp)
390
+
391
+ def test_chararray_rstrip(self):
392
+ # Ticket #222
393
+ x = np.char.chararray((1,), 5)
394
+ x[0] = b'a '
395
+ x = x.rstrip()
396
+ assert_equal(x[0], b'a')
397
+
398
+ def test_object_array_shape(self):
399
+ # Ticket #239
400
+ assert_equal(np.array([[1, 2], 3, 4], dtype=object).shape, (3,))
401
+ assert_equal(np.array([[1, 2], [3, 4]], dtype=object).shape, (2, 2))
402
+ assert_equal(np.array([(1, 2), (3, 4)], dtype=object).shape, (2, 2))
403
+ assert_equal(np.array([], dtype=object).shape, (0,))
404
+ assert_equal(np.array([[], [], []], dtype=object).shape, (3, 0))
405
+ assert_equal(np.array([[3, 4], [5, 6], None], dtype=object).shape, (3,))
406
+
407
+ def test_mem_around(self):
408
+ # Ticket #243
409
+ x = np.zeros((1,))
410
+ y = [0]
411
+ decimal = 6
412
+ np.around(abs(x - y), decimal) <= 10.0**(-decimal)
413
+
414
+ def test_character_array_strip(self):
415
+ # Ticket #246
416
+ x = np.char.array(("x", "x ", "x "))
417
+ for c in x:
418
+ assert_equal(c, "x")
419
+
420
+ def test_lexsort(self):
421
+ # Lexsort memory error
422
+ v = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
423
+ assert_equal(np.lexsort(v), 0)
424
+
425
+ def test_lexsort_invalid_sequence(self):
426
+ # Issue gh-4123
427
+ class BuggySequence:
428
+ def __len__(self):
429
+ return 4
430
+
431
+ def __getitem__(self, key):
432
+ raise KeyError
433
+
434
+ assert_raises(KeyError, np.lexsort, BuggySequence())
435
+
436
+ def test_lexsort_zerolen_custom_strides(self):
437
+ # Ticket #14228
438
+ xs = np.array([], dtype='i8')
439
+ assert np.lexsort((xs,)).shape[0] == 0 # Works
440
+
441
+ xs.strides = (16,)
442
+ assert np.lexsort((xs,)).shape[0] == 0 # Was: MemoryError
443
+
444
+ def test_lexsort_zerolen_custom_strides_2d(self):
445
+ xs = np.array([], dtype='i8')
446
+
447
+ xs.shape = (0, 2)
448
+ xs.strides = (16, 16)
449
+ assert np.lexsort((xs,), axis=0).shape[0] == 0
450
+
451
+ xs.shape = (2, 0)
452
+ xs.strides = (16, 16)
453
+ assert np.lexsort((xs,), axis=0).shape[0] == 2
454
+
455
+ def test_lexsort_invalid_axis(self):
456
+ assert_raises(AxisError, np.lexsort, (np.arange(1),), axis=2)
457
+ assert_raises(AxisError, np.lexsort, (np.array([]),), axis=1)
458
+ assert_raises(AxisError, np.lexsort, (np.array(1),), axis=10)
459
+
460
+ def test_lexsort_zerolen_element(self):
461
+ dt = np.dtype([]) # a void dtype with no fields
462
+ xs = np.empty(4, dt)
463
+
464
+ assert np.lexsort((xs,)).shape[0] == xs.shape[0]
465
+
466
+ def test_pickle_py2_bytes_encoding(self):
467
+ # Check that arrays and scalars pickled on Py2 are
468
+ # unpickleable on Py3 using encoding='bytes'
469
+
470
+ test_data = [
471
+ # (original, py2_pickle)
472
+ (
473
+ np.str_('\u6f2c'),
474
+ b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\nI0\ntp6\nbS',o\\x00\\x00'\np7\ntp8\nRp9\n."
475
+ ),
476
+
477
+ (
478
+ np.array([9e123], dtype=np.float64),
479
+ b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'f8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np13\ntp14\nb."
480
+ ),
481
+
482
+ (
483
+ np.array([(9e123,)], dtype=[('name', float)]),
484
+ b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'V8'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nN(S'name'\np12\ntp13\n(dp14\ng12\n(g7\n(S'f8'\np15\nI0\nI1\ntp16\nRp17\n(I3\nS'<'\np18\nNNNI-1\nI-1\nI0\ntp19\nbI0\ntp20\nsI8\nI1\nI0\ntp21\nbI00\nS'O\\x81\\xb7Z\\xaa:\\xabY'\np22\ntp23\nb."
485
+ ),
486
+ ]
487
+
488
+ for original, data in test_data:
489
+ result = pickle.loads(data, encoding='bytes')
490
+ assert_equal(result, original)
491
+
492
+ if isinstance(result, np.ndarray) and result.dtype.names is not None:
493
+ for name in result.dtype.names:
494
+ assert_(isinstance(name, str))
495
+
496
+ def test_pickle_dtype(self):
497
+ # Ticket #251
498
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
499
+ pickle.dumps(float, protocol=proto)
500
+
501
+ def test_swap_real(self):
502
+ # Ticket #265
503
+ assert_equal(np.arange(4, dtype='>c8').imag.max(), 0.0)
504
+ assert_equal(np.arange(4, dtype='<c8').imag.max(), 0.0)
505
+ assert_equal(np.arange(4, dtype='>c8').real.max(), 3.0)
506
+ assert_equal(np.arange(4, dtype='<c8').real.max(), 3.0)
507
+
508
+ def test_object_array_from_list(self):
509
+ # Ticket #270 (gh-868)
510
+ assert_(np.array([1, None, 'A']).shape == (3,))
511
+
512
+ def test_multiple_assign(self):
513
+ # Ticket #273
514
+ a = np.zeros((3, 1), int)
515
+ a[[1, 2]] = 1
516
+
517
+ def test_empty_array_type(self):
518
+ assert_equal(np.array([]).dtype, np.zeros(0).dtype)
519
+
520
+ def test_void_copyswap(self):
521
+ dt = np.dtype([('one', '<i4'), ('two', '<i4')])
522
+ x = np.array((1, 2), dtype=dt)
523
+ x = x.byteswap()
524
+ assert_(x['one'] > 1 and x['two'] > 2)
525
+
526
+ def test_method_args(self):
527
+ # Make sure methods and functions have same default axis
528
+ # keyword and arguments
529
+ funcs1 = ['argmax', 'argmin', 'sum', 'any', 'all', 'cumsum',
530
+ 'cumprod', 'prod', 'std', 'var', 'mean',
531
+ 'round', 'min', 'max', 'argsort', 'sort']
532
+ funcs2 = ['compress', 'take', 'repeat']
533
+
534
+ for func in funcs1:
535
+ arr = np.random.rand(8, 7)
536
+ arr2 = arr.copy()
537
+ res1 = getattr(arr, func)()
538
+ res2 = getattr(np, func)(arr2)
539
+ if res1 is None:
540
+ res1 = arr
541
+
542
+ if res1.dtype.kind in 'uib':
543
+ assert_((res1 == res2).all(), func)
544
+ else:
545
+ assert_(abs(res1 - res2).max() < 1e-8, func)
546
+
547
+ for func in funcs2:
548
+ arr1 = np.random.rand(8, 7)
549
+ arr2 = np.random.rand(8, 7)
550
+ res1 = None
551
+ if func == 'compress':
552
+ arr1 = arr1.ravel()
553
+ res1 = getattr(arr2, func)(arr1)
554
+ else:
555
+ arr2 = (15 * arr2).astype(int).ravel()
556
+ if res1 is None:
557
+ res1 = getattr(arr1, func)(arr2)
558
+ res2 = getattr(np, func)(arr1, arr2)
559
+ assert_(abs(res1 - res2).max() < 1e-8, func)
560
+
561
+ def test_mem_lexsort_strings(self):
562
+ # Ticket #298
563
+ lst = ['abc', 'cde', 'fgh']
564
+ np.lexsort((lst,))
565
+
566
+ def test_fancy_index(self):
567
+ # Ticket #302
568
+ x = np.array([1, 2])[np.array([0])]
569
+ assert_equal(x.shape, (1,))
570
+
571
+ def test_recarray_copy(self):
572
+ # Ticket #312
573
+ dt = [('x', np.int16), ('y', np.float64)]
574
+ ra = np.array([(1, 2.3)], dtype=dt)
575
+ rb = np.rec.array(ra, dtype=dt)
576
+ rb['x'] = 2.
577
+ assert_(ra['x'] != rb['x'])
578
+
579
+ def test_rec_fromarray(self):
580
+ # Ticket #322
581
+ x1 = np.array([[1, 2], [3, 4], [5, 6]])
582
+ x2 = np.array(['a', 'dd', 'xyz'])
583
+ x3 = np.array([1.1, 2, 3])
584
+ np.rec.fromarrays([x1, x2, x3], formats="(2,)i4,S3,f8")
585
+
586
+ def test_object_array_assign(self):
587
+ x = np.empty((2, 2), object)
588
+ x.flat[2] = (1, 2, 3)
589
+ assert_equal(x.flat[2], (1, 2, 3))
590
+
591
+ def test_ndmin_float64(self):
592
+ # Ticket #324
593
+ x = np.array([1, 2, 3], dtype=np.float64)
594
+ assert_equal(np.array(x, dtype=np.float32, ndmin=2).ndim, 2)
595
+ assert_equal(np.array(x, dtype=np.float64, ndmin=2).ndim, 2)
596
+
597
+ def test_ndmin_order(self):
598
+ # Issue #465 and related checks
599
+ assert_(np.array([1, 2], order='C', ndmin=3).flags.c_contiguous)
600
+ assert_(np.array([1, 2], order='F', ndmin=3).flags.f_contiguous)
601
+ assert_(np.array(np.ones((2, 2), order='F'), ndmin=3).flags.f_contiguous)
602
+ assert_(np.array(np.ones((2, 2), order='C'), ndmin=3).flags.c_contiguous)
603
+
604
+ def test_mem_axis_minimization(self):
605
+ # Ticket #327
606
+ data = np.arange(5)
607
+ data = np.add.outer(data, data)
608
+
609
+ def test_mem_float_imag(self):
610
+ # Ticket #330
611
+ np.float64(1.0).imag
612
+
613
+ def test_dtype_tuple(self):
614
+ # Ticket #334
615
+ assert_(np.dtype('i4') == np.dtype(('i4', ())))
616
+
617
+ def test_dtype_posttuple(self):
618
+ # Ticket #335
619
+ np.dtype([('col1', '()i4')])
620
+
621
+ def test_numeric_carray_compare(self):
622
+ # Ticket #341
623
+ assert_equal(np.array(['X'], 'c'), b'X')
624
+
625
+ def test_string_array_size(self):
626
+ # Ticket #342
627
+ assert_raises(ValueError,
628
+ np.array, [['X'], ['X', 'X', 'X']], '|S1')
629
+
630
+ def test_dtype_repr(self):
631
+ # Ticket #344
632
+ dt1 = np.dtype(('uint32', 2))
633
+ dt2 = np.dtype(('uint32', (2,)))
634
+ assert_equal(dt1.__repr__(), dt2.__repr__())
635
+
636
+ def test_reshape_order(self):
637
+ # Make sure reshape order works.
638
+ a = np.arange(6).reshape(2, 3, order='F')
639
+ assert_equal(a, [[0, 2, 4], [1, 3, 5]])
640
+ a = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
641
+ b = a[:, 1]
642
+ assert_equal(b.reshape(2, 2, order='F'), [[2, 6], [4, 8]])
643
+
644
+ def test_reshape_zero_strides(self):
645
+ # Issue #380, test reshaping of zero strided arrays
646
+ a = np.ones(1)
647
+ a = np.lib.stride_tricks.as_strided(a, shape=(5,), strides=(0,))
648
+ assert_(a.reshape(5, 1).strides[0] == 0)
649
+
650
+ def test_reshape_zero_size(self):
651
+ # GitHub Issue #2700, setting shape failed for 0-sized arrays
652
+ a = np.ones((0, 2))
653
+ a.shape = (-1, 2)
654
+
655
+ def test_reshape_trailing_ones_strides(self):
656
+ # GitHub issue gh-2949, bad strides for trailing ones of new shape
657
+ a = np.zeros(12, dtype=np.int32)[::2] # not contiguous
658
+ strides_c = (16, 8, 8, 8)
659
+ strides_f = (8, 24, 48, 48)
660
+ assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c)
661
+ assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f)
662
+ assert_equal(np.array(0, dtype=np.int32).reshape(1, 1).strides, (4, 4))
663
+
664
+ def test_repeat_discont(self):
665
+ # Ticket #352
666
+ a = np.arange(12).reshape(4, 3)[:, 2]
667
+ assert_equal(a.repeat(3), [2, 2, 2, 5, 5, 5, 8, 8, 8, 11, 11, 11])
668
+
669
+ def test_array_index(self):
670
+ # Make sure optimization is not called in this case.
671
+ a = np.array([1, 2, 3])
672
+ a2 = np.array([[1, 2, 3]])
673
+ assert_equal(a[np.where(a == 3)], a2[np.where(a2 == 3)])
674
+
675
+ def test_object_argmax(self):
676
+ a = np.array([1, 2, 3], dtype=object)
677
+ assert_(a.argmax() == 2)
678
+
679
+ def test_recarray_fields(self):
680
+ # Ticket #372
681
+ dt0 = np.dtype([('f0', 'i4'), ('f1', 'i4')])
682
+ dt1 = np.dtype([('f0', 'i8'), ('f1', 'i8')])
683
+ for a in [np.array([(1, 2), (3, 4)], "i4,i4"),
684
+ np.rec.array([(1, 2), (3, 4)], "i4,i4"),
685
+ np.rec.array([(1, 2), (3, 4)]),
686
+ np.rec.fromarrays([(1, 2), (3, 4)], "i4,i4"),
687
+ np.rec.fromarrays([(1, 2), (3, 4)])]:
688
+ assert_(a.dtype in [dt0, dt1])
689
+
690
+ def test_random_shuffle(self):
691
+ # Ticket #374
692
+ a = np.arange(5).reshape((5, 1))
693
+ b = a.copy()
694
+ np.random.shuffle(b)
695
+ assert_equal(np.sort(b, axis=0), a)
696
+
697
+ def test_refcount_vdot(self):
698
+ # Changeset #3443
699
+ _assert_valid_refcount(np.vdot)
700
+
701
+ def test_startswith(self):
702
+ ca = np.char.array(['Hi', 'There'])
703
+ assert_equal(ca.startswith('H'), [True, False])
704
+
705
+ def test_noncommutative_reduce_accumulate(self):
706
+ # Ticket #413
707
+ tosubtract = np.arange(5)
708
+ todivide = np.array([2.0, 0.5, 0.25])
709
+ assert_equal(np.subtract.reduce(tosubtract), -10)
710
+ assert_equal(np.divide.reduce(todivide), 16.0)
711
+ assert_array_equal(np.subtract.accumulate(tosubtract),
712
+ np.array([0, -1, -3, -6, -10]))
713
+ assert_array_equal(np.divide.accumulate(todivide),
714
+ np.array([2., 4., 16.]))
715
+
716
+ def test_convolve_empty(self):
717
+ # Convolve should raise an error for empty input array.
718
+ assert_raises(ValueError, np.convolve, [], [1])
719
+ assert_raises(ValueError, np.convolve, [1], [])
720
+
721
+ def test_multidim_byteswap(self):
722
+ # Ticket #449
723
+ r = np.array([(1, (0, 1, 2))], dtype="i2,3i2")
724
+ assert_array_equal(r.byteswap(),
725
+ np.array([(256, (0, 256, 512))], r.dtype))
726
+
727
+ def test_string_NULL(self):
728
+ # Changeset 3557
729
+ assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
730
+ 'a\x00\x0b\x0c')
731
+
732
+ def test_junk_in_string_fields_of_recarray(self):
733
+ # Ticket #483
734
+ r = np.array([[b'abc']], dtype=[('var1', '|S20')])
735
+ assert_(asbytes(r['var1'][0][0]) == b'abc')
736
+
737
+ def test_take_output(self):
738
+ # Ensure that 'take' honours output parameter.
739
+ x = np.arange(12).reshape((3, 4))
740
+ a = np.take(x, [0, 2], axis=1)
741
+ b = np.zeros_like(a)
742
+ np.take(x, [0, 2], axis=1, out=b)
743
+ assert_array_equal(a, b)
744
+
745
+ def test_take_object_fail(self):
746
+ # Issue gh-3001
747
+ d = 123.
748
+ a = np.array([d, 1], dtype=object)
749
+ if HAS_REFCOUNT:
750
+ ref_d = sys.getrefcount(d)
751
+ try:
752
+ a.take([0, 100])
753
+ except IndexError:
754
+ pass
755
+ if HAS_REFCOUNT:
756
+ assert_(ref_d == sys.getrefcount(d))
757
+
758
+ def test_array_str_64bit(self):
759
+ # Ticket #501
760
+ s = np.array([1, np.nan], dtype=np.float64)
761
+ with np.errstate(all='raise'):
762
+ np.array_str(s) # Should succeed
763
+
764
+ def test_frompyfunc_endian(self):
765
+ # Ticket #503
766
+ from math import radians
767
+ uradians = np.frompyfunc(radians, 1, 1)
768
+ big_endian = np.array([83.4, 83.5], dtype='>f8')
769
+ little_endian = np.array([83.4, 83.5], dtype='<f8')
770
+ assert_almost_equal(uradians(big_endian).astype(float),
771
+ uradians(little_endian).astype(float))
772
+
773
+ def test_mem_string_arr(self):
774
+ # Ticket #514
775
+ s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
776
+ t = []
777
+ np.hstack((t, s))
778
+
779
+ def test_arr_transpose(self):
780
+ # Ticket #516
781
+ x = np.random.rand(*(2,) * 16)
782
+ x.transpose(list(range(16))) # Should succeed
783
+
784
+ def test_string_mergesort(self):
785
+ # Ticket #540
786
+ x = np.array(['a'] * 32)
787
+ assert_array_equal(x.argsort(kind='m'), np.arange(32))
788
+
789
+ def test_argmax_byteorder(self):
790
+ # Ticket #546
791
+ a = np.arange(3, dtype='>f')
792
+ assert_(a[a.argmax()] == a.max())
793
+
794
+ def test_rand_seed(self):
795
+ # Ticket #555
796
+ for l in np.arange(4):
797
+ np.random.seed(l)
798
+
799
+ def test_mem_deallocation_leak(self):
800
+ # Ticket #562
801
+ a = np.zeros(5, dtype=float)
802
+ b = np.array(a, dtype=float)
803
+ del a, b
804
+
805
+ def test_mem_on_invalid_dtype(self):
806
+ "Ticket #583"
807
+ assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str)
808
+
809
+ def test_dot_negative_stride(self):
810
+ # Ticket #588
811
+ x = np.array([[1, 5, 25, 125., 625]])
812
+ y = np.array([[20.], [160.], [640.], [1280.], [1024.]])
813
+ z = y[::-1].copy()
814
+ y2 = y[::-1]
815
+ assert_equal(np.dot(x, z), np.dot(x, y2))
816
+
817
+ def test_object_casting(self):
818
+ # This used to trigger the object-type version of
819
+ # the bitwise_or operation, because float64 -> object
820
+ # casting succeeds
821
+ def rs():
822
+ x = np.ones([484, 286])
823
+ y = np.zeros([484, 286])
824
+ x |= y
825
+
826
+ assert_raises(TypeError, rs)
827
+
828
+ def test_unicode_scalar(self):
829
+ # Ticket #600
830
+ x = np.array(["DROND", "DROND1"], dtype="U6")
831
+ el = x[1]
832
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
833
+ new = pickle.loads(pickle.dumps(el, protocol=proto))
834
+ assert_equal(new, el)
835
+
836
+ def test_arange_non_native_dtype(self):
837
+ # Ticket #616
838
+ for T in ('>f4', '<f4'):
839
+ dt = np.dtype(T)
840
+ assert_equal(np.arange(0, dtype=dt).dtype, dt)
841
+ assert_equal(np.arange(0.5, dtype=dt).dtype, dt)
842
+ assert_equal(np.arange(5, dtype=dt).dtype, dt)
843
+
844
+ def test_bool_flat_indexing_invalid_nr_elements(self):
845
+ s = np.ones(10, dtype=float)
846
+ x = np.array((15,), dtype=float)
847
+
848
+ def ia(x, s, v):
849
+ x[(s > 0)] = v
850
+
851
+ assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float))
852
+ assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float))
853
+
854
+ # Old special case (different code path):
855
+ assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float))
856
+ assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float))
857
+
858
+ def test_mem_scalar_indexing(self):
859
+ # Ticket #603
860
+ x = np.array([0], dtype=float)
861
+ index = np.array(0, dtype=np.int32)
862
+ x[index]
863
+
864
+ def test_binary_repr_0_width(self):
865
+ assert_equal(np.binary_repr(0, width=3), '000')
866
+
867
+ def test_fromstring(self):
868
+ assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
869
+ [12, 9, 9])
870
+
871
+ def test_searchsorted_variable_length(self):
872
+ x = np.array(['a', 'aa', 'b'])
873
+ y = np.array(['d', 'e'])
874
+ assert_equal(x.searchsorted(y), [3, 3])
875
+
876
+ def test_string_argsort_with_zeros(self):
877
+ # Check argsort for strings containing zeros.
878
+ x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
879
+ assert_array_equal(x.argsort(kind='m'), np.array([1, 0]))
880
+ assert_array_equal(x.argsort(kind='q'), np.array([1, 0]))
881
+
882
+ def test_string_sort_with_zeros(self):
883
+ # Check sort for strings containing zeros.
884
+ x = np.frombuffer(b"\x00\x02\x00\x01", dtype="|S2")
885
+ y = np.frombuffer(b"\x00\x01\x00\x02", dtype="|S2")
886
+ assert_array_equal(np.sort(x, kind="q"), y)
887
+
888
+ def test_copy_detection_zero_dim(self):
889
+ # Ticket #658
890
+ np.indices((0, 3, 4)).T.reshape(-1, 3)
891
+
892
+ def test_flat_byteorder(self):
893
+ # Ticket #657
894
+ x = np.arange(10)
895
+ assert_array_equal(x.astype('>i4'), x.astype('<i4').flat[:])
896
+ assert_array_equal(x.astype('>i4').flat[:], x.astype('<i4'))
897
+
898
+ def test_sign_bit(self):
899
+ x = np.array([0, -0.0, 0])
900
+ assert_equal(str(np.abs(x)), '[0. 0. 0.]')
901
+
902
+ def test_flat_index_byteswap(self):
903
+ for dt in (np.dtype('<i4'), np.dtype('>i4')):
904
+ x = np.array([-1, 0, 1], dtype=dt)
905
+ assert_equal(x.flat[0].dtype, x[0].dtype)
906
+
907
+ def test_copy_detection_corner_case(self):
908
+ # Ticket #658
909
+ np.indices((0, 3, 4)).T.reshape(-1, 3)
910
+
911
+ def test_object_array_refcounting(self):
912
+ # Ticket #633
913
+ if not hasattr(sys, 'getrefcount'):
914
+ return
915
+
916
+ # NB. this is probably CPython-specific
917
+
918
+ cnt = sys.getrefcount
919
+
920
+ a = object()
921
+ b = object()
922
+ c = object()
923
+
924
+ cnt0_a = cnt(a)
925
+ cnt0_b = cnt(b)
926
+ cnt0_c = cnt(c)
927
+
928
+ # -- 0d -> 1-d broadcast slice assignment
929
+
930
+ arr = np.zeros(5, dtype=np.object_)
931
+
932
+ arr[:] = a
933
+ assert_equal(cnt(a), cnt0_a + 5)
934
+
935
+ arr[:] = b
936
+ assert_equal(cnt(a), cnt0_a)
937
+ assert_equal(cnt(b), cnt0_b + 5)
938
+
939
+ arr[:2] = c
940
+ assert_equal(cnt(b), cnt0_b + 3)
941
+ assert_equal(cnt(c), cnt0_c + 2)
942
+
943
+ del arr
944
+
945
+ # -- 1-d -> 2-d broadcast slice assignment
946
+
947
+ arr = np.zeros((5, 2), dtype=np.object_)
948
+ arr0 = np.zeros(2, dtype=np.object_)
949
+
950
+ arr0[0] = a
951
+ assert_(cnt(a) == cnt0_a + 1)
952
+ arr0[1] = b
953
+ assert_(cnt(b) == cnt0_b + 1)
954
+
955
+ arr[:, :] = arr0
956
+ assert_(cnt(a) == cnt0_a + 6)
957
+ assert_(cnt(b) == cnt0_b + 6)
958
+
959
+ arr[:, 0] = None
960
+ assert_(cnt(a) == cnt0_a + 1)
961
+
962
+ del arr, arr0
963
+
964
+ # -- 2-d copying + flattening
965
+
966
+ arr = np.zeros((5, 2), dtype=np.object_)
967
+
968
+ arr[:, 0] = a
969
+ arr[:, 1] = b
970
+ assert_(cnt(a) == cnt0_a + 5)
971
+ assert_(cnt(b) == cnt0_b + 5)
972
+
973
+ arr2 = arr.copy()
974
+ assert_(cnt(a) == cnt0_a + 10)
975
+ assert_(cnt(b) == cnt0_b + 10)
976
+
977
+ arr2 = arr[:, 0].copy()
978
+ assert_(cnt(a) == cnt0_a + 10)
979
+ assert_(cnt(b) == cnt0_b + 5)
980
+
981
+ arr2 = arr.flatten()
982
+ assert_(cnt(a) == cnt0_a + 10)
983
+ assert_(cnt(b) == cnt0_b + 10)
984
+
985
+ del arr, arr2
986
+
987
+ # -- concatenate, repeat, take, choose
988
+
989
+ arr1 = np.zeros((5, 1), dtype=np.object_)
990
+ arr2 = np.zeros((5, 1), dtype=np.object_)
991
+
992
+ arr1[...] = a
993
+ arr2[...] = b
994
+ assert_(cnt(a) == cnt0_a + 5)
995
+ assert_(cnt(b) == cnt0_b + 5)
996
+
997
+ tmp = np.concatenate((arr1, arr2))
998
+ assert_(cnt(a) == cnt0_a + 5 + 5)
999
+ assert_(cnt(b) == cnt0_b + 5 + 5)
1000
+
1001
+ tmp = arr1.repeat(3, axis=0)
1002
+ assert_(cnt(a) == cnt0_a + 5 + 3 * 5)
1003
+
1004
+ tmp = arr1.take([1, 2, 3], axis=0)
1005
+ assert_(cnt(a) == cnt0_a + 5 + 3)
1006
+
1007
+ x = np.array([[0], [1], [0], [1], [1]], int)
1008
+ tmp = x.choose(arr1, arr2)
1009
+ assert_(cnt(a) == cnt0_a + 5 + 2)
1010
+ assert_(cnt(b) == cnt0_b + 5 + 3)
1011
+
1012
+ def test_mem_custom_float_to_array(self):
1013
+ # Ticket 702
1014
+ class MyFloat:
1015
+ def __float__(self):
1016
+ return 1.0
1017
+
1018
+ tmp = np.atleast_1d([MyFloat()])
1019
+ tmp.astype(float) # Should succeed
1020
+
1021
+ def test_object_array_refcount_self_assign(self):
1022
+ # Ticket #711
1023
+ class VictimObject:
1024
+ deleted = False
1025
+
1026
+ def __del__(self):
1027
+ self.deleted = True
1028
+
1029
+ d = VictimObject()
1030
+ arr = np.zeros(5, dtype=np.object_)
1031
+ arr[:] = d
1032
+ del d
1033
+ arr[:] = arr # refcount of 'd' might hit zero here
1034
+ assert_(not arr[0].deleted)
1035
+ arr[:] = arr # trying to induce a segfault by doing it again...
1036
+ assert_(not arr[0].deleted)
1037
+
1038
+ def test_mem_fromiter_invalid_dtype_string(self):
1039
+ x = [1, 2, 3]
1040
+ assert_raises(ValueError,
1041
+ np.fromiter, list(x), dtype='S')
1042
+
1043
+ def test_reduce_big_object_array(self):
1044
+ # Ticket #713
1045
+ oldsize = np.setbufsize(10 * 16)
1046
+ a = np.array([None] * 161, object)
1047
+ assert_(not np.any(a))
1048
+ np.setbufsize(oldsize)
1049
+
1050
+ def test_mem_0d_array_index(self):
1051
+ # Ticket #714
1052
+ np.zeros(10)[np.array(0)]
1053
+
1054
+ def test_nonnative_endian_fill(self):
1055
+ # Non-native endian arrays were incorrectly filled with scalars
1056
+ # before r5034.
1057
+ if sys.byteorder == 'little':
1058
+ dtype = np.dtype('>i4')
1059
+ else:
1060
+ dtype = np.dtype('<i4')
1061
+ x = np.empty([1], dtype=dtype)
1062
+ x.fill(1)
1063
+ assert_equal(x, np.array([1], dtype=dtype))
1064
+
1065
+ def test_dot_alignment_sse2(self):
1066
+ # Test for ticket #551, changeset r5140
1067
+ x = np.zeros((30, 40))
1068
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
1069
+ y = pickle.loads(pickle.dumps(x, protocol=proto))
1070
+ # y is now typically not aligned on a 8-byte boundary
1071
+ z = np.ones((1, y.shape[0]))
1072
+ # This shouldn't cause a segmentation fault:
1073
+ np.dot(z, y)
1074
+
1075
+ def test_astype_copy(self):
1076
+ # Ticket #788, changeset r5155
1077
+ # The test data file was generated by scipy.io.savemat.
1078
+ # The dtype is float64, but the isbuiltin attribute is 0.
1079
+ data_dir = path.join(path.dirname(__file__), 'data')
1080
+ filename = path.join(data_dir, "astype_copy.pkl")
1081
+ with open(filename, 'rb') as f:
1082
+ xp = pickle.load(f, encoding='latin1')
1083
+ xpd = xp.astype(np.float64)
1084
+ assert_(xp.__array_interface__['data'][0] !=
1085
+ xpd.__array_interface__['data'][0])
1086
+
1087
+ def test_compress_small_type(self):
1088
+ # Ticket #789, changeset 5217.
1089
+ # compress with out argument segfaulted if cannot cast safely
1090
+ import numpy as np
1091
+ a = np.array([[1, 2], [3, 4]])
1092
+ b = np.zeros((2, 1), dtype=np.single)
1093
+ try:
1094
+ a.compress([True, False], axis=1, out=b)
1095
+ raise AssertionError("compress with an out which cannot be "
1096
+ "safely casted should not return "
1097
+ "successfully")
1098
+ except TypeError:
1099
+ pass
1100
+
1101
+ def test_attributes(self):
1102
+ # Ticket #791
1103
+ class TestArray(np.ndarray):
1104
+ def __new__(cls, data, info):
1105
+ result = np.array(data)
1106
+ result = result.view(cls)
1107
+ result.info = info
1108
+ return result
1109
+
1110
+ def __array_finalize__(self, obj):
1111
+ self.info = getattr(obj, 'info', '')
1112
+
1113
+ dat = TestArray([[1, 2, 3, 4], [5, 6, 7, 8]], 'jubba')
1114
+ assert_(dat.info == 'jubba')
1115
+ dat.resize((4, 2))
1116
+ assert_(dat.info == 'jubba')
1117
+ dat.sort()
1118
+ assert_(dat.info == 'jubba')
1119
+ dat.fill(2)
1120
+ assert_(dat.info == 'jubba')
1121
+ dat.put([2, 3, 4], [6, 3, 4])
1122
+ assert_(dat.info == 'jubba')
1123
+ dat.setfield(4, np.int32, 0)
1124
+ assert_(dat.info == 'jubba')
1125
+ dat.setflags()
1126
+ assert_(dat.info == 'jubba')
1127
+ assert_(dat.all(1).info == 'jubba')
1128
+ assert_(dat.any(1).info == 'jubba')
1129
+ assert_(dat.argmax(1).info == 'jubba')
1130
+ assert_(dat.argmin(1).info == 'jubba')
1131
+ assert_(dat.argsort(1).info == 'jubba')
1132
+ assert_(dat.astype(TestArray).info == 'jubba')
1133
+ assert_(dat.byteswap().info == 'jubba')
1134
+ assert_(dat.clip(2, 7).info == 'jubba')
1135
+ assert_(dat.compress([0, 1, 1]).info == 'jubba')
1136
+ assert_(dat.conj().info == 'jubba')
1137
+ assert_(dat.conjugate().info == 'jubba')
1138
+ assert_(dat.copy().info == 'jubba')
1139
+ dat2 = TestArray([2, 3, 1, 0], 'jubba')
1140
+ choices = [[0, 1, 2, 3], [10, 11, 12, 13],
1141
+ [20, 21, 22, 23], [30, 31, 32, 33]]
1142
+ assert_(dat2.choose(choices).info == 'jubba')
1143
+ assert_(dat.cumprod(1).info == 'jubba')
1144
+ assert_(dat.cumsum(1).info == 'jubba')
1145
+ assert_(dat.diagonal().info == 'jubba')
1146
+ assert_(dat.flatten().info == 'jubba')
1147
+ assert_(dat.getfield(np.int32, 0).info == 'jubba')
1148
+ assert_(dat.imag.info == 'jubba')
1149
+ assert_(dat.max(1).info == 'jubba')
1150
+ assert_(dat.mean(1).info == 'jubba')
1151
+ assert_(dat.min(1).info == 'jubba')
1152
+ assert_(dat.prod(1).info == 'jubba')
1153
+ assert_(dat.ravel().info == 'jubba')
1154
+ assert_(dat.real.info == 'jubba')
1155
+ assert_(dat.repeat(2).info == 'jubba')
1156
+ assert_(dat.reshape((2, 4)).info == 'jubba')
1157
+ assert_(dat.round().info == 'jubba')
1158
+ assert_(dat.squeeze().info == 'jubba')
1159
+ assert_(dat.std(1).info == 'jubba')
1160
+ assert_(dat.sum(1).info == 'jubba')
1161
+ assert_(dat.swapaxes(0, 1).info == 'jubba')
1162
+ assert_(dat.take([2, 3, 5]).info == 'jubba')
1163
+ assert_(dat.transpose().info == 'jubba')
1164
+ assert_(dat.T.info == 'jubba')
1165
+ assert_(dat.var(1).info == 'jubba')
1166
+ assert_(dat.view(TestArray).info == 'jubba')
1167
+ # These methods do not preserve subclasses
1168
+ assert_(type(dat.nonzero()[0]) is np.ndarray)
1169
+ assert_(type(dat.nonzero()[1]) is np.ndarray)
1170
+
1171
+ def test_recarray_tolist(self):
1172
+ # Ticket #793, changeset r5215
1173
+ # Comparisons fail for NaN, so we can't use random memory
1174
+ # for the test.
1175
+ buf = np.zeros(40, dtype=np.int8)
1176
+ a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf)
1177
+ b = a.tolist()
1178
+ assert_(a[0].tolist() == b[0])
1179
+ assert_(a[1].tolist() == b[1])
1180
+
1181
+ def test_nonscalar_item_method(self):
1182
+ # Make sure that .item() fails graciously when it should
1183
+ a = np.arange(5)
1184
+ assert_raises(ValueError, a.item)
1185
+
1186
+ def test_char_array_creation(self):
1187
+ a = np.array('123', dtype='c')
1188
+ b = np.array([b'1', b'2', b'3'])
1189
+ assert_equal(a, b)
1190
+
1191
+ def test_unaligned_unicode_access(self):
1192
+ # Ticket #825
1193
+ for i in range(1, 9):
1194
+ msg = 'unicode offset: %d chars' % i
1195
+ t = np.dtype([('a', 'S%d' % i), ('b', 'U2')])
1196
+ x = np.array([(b'a', 'b')], dtype=t)
1197
+ assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg)
1198
+
1199
+ def test_sign_for_complex_nan(self):
1200
+ # Ticket 794.
1201
+ with np.errstate(invalid='ignore'):
1202
+ C = np.array([-np.inf, -3 + 4j, 0, 4 - 3j, np.inf, np.nan])
1203
+ have = np.sign(C)
1204
+ want = np.array([-1 + 0j, -0.6 + 0.8j, 0 + 0j, 0.8 - 0.6j, 1 + 0j,
1205
+ complex(np.nan, np.nan)])
1206
+ assert_equal(have, want)
1207
+
1208
+ def test_for_equal_names(self):
1209
+ # Ticket #674
1210
+ dt = np.dtype([('foo', float), ('bar', float)])
1211
+ a = np.zeros(10, dt)
1212
+ b = list(a.dtype.names)
1213
+ b[0] = "notfoo"
1214
+ a.dtype.names = b
1215
+ assert_(a.dtype.names[0] == "notfoo")
1216
+ assert_(a.dtype.names[1] == "bar")
1217
+
1218
+ def test_for_object_scalar_creation(self):
1219
+ # Ticket #816
1220
+ a = np.object_()
1221
+ b = np.object_(3)
1222
+ b2 = np.object_(3.0)
1223
+ c = np.object_([4, 5])
1224
+ d = np.object_([None, {}, []])
1225
+ assert_(a is None)
1226
+ assert_(type(b) is int)
1227
+ assert_(type(b2) is float)
1228
+ assert_(type(c) is np.ndarray)
1229
+ assert_(c.dtype == object)
1230
+ assert_(d.dtype == object)
1231
+
1232
+ def test_array_resize_method_system_error(self):
1233
+ # Ticket #840 - order should be an invalid keyword.
1234
+ x = np.array([[0, 1], [2, 3]])
1235
+ assert_raises(TypeError, x.resize, (2, 2), order='C')
1236
+
1237
+ def test_for_zero_length_in_choose(self):
1238
+ "Ticket #882"
1239
+ a = np.array(1)
1240
+ assert_raises(ValueError, lambda x: x.choose([]), a)
1241
+
1242
+ def test_array_ndmin_overflow(self):
1243
+ "Ticket #947."
1244
+ assert_raises(ValueError, lambda: np.array([1], ndmin=65))
1245
+
1246
+ def test_void_scalar_with_titles(self):
1247
+ # No ticket
1248
+ data = [('john', 4), ('mary', 5)]
1249
+ dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)]
1250
+ arr = np.array(data, dtype=dtype1)
1251
+ assert_(arr[0][0] == 'john')
1252
+ assert_(arr[0][1] == 4)
1253
+
1254
+ def test_void_scalar_constructor(self):
1255
+ # Issue #1550
1256
+
1257
+ # Create test string data, construct void scalar from data and assert
1258
+ # that void scalar contains original data.
1259
+ test_string = np.array("test")
1260
+ test_string_void_scalar = np._core.multiarray.scalar(
1261
+ np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes())
1262
+
1263
+ assert_(test_string_void_scalar.view(test_string.dtype) == test_string)
1264
+
1265
+ # Create record scalar, construct from data and assert that
1266
+ # reconstructed scalar is correct.
1267
+ test_record = np.ones((), "i,i")
1268
+ test_record_void_scalar = np._core.multiarray.scalar(
1269
+ test_record.dtype, test_record.tobytes())
1270
+
1271
+ assert_(test_record_void_scalar == test_record)
1272
+
1273
+ # Test pickle and unpickle of void and record scalars
1274
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
1275
+ assert_(pickle.loads(
1276
+ pickle.dumps(test_string, protocol=proto)) == test_string)
1277
+ assert_(pickle.loads(
1278
+ pickle.dumps(test_record, protocol=proto)) == test_record)
1279
+
1280
+ @_no_tracing
1281
+ def test_blasdot_uninitialized_memory(self):
1282
+ # Ticket #950
1283
+ for m in [0, 1, 2]:
1284
+ for n in [0, 1, 2]:
1285
+ for k in range(3):
1286
+ # Try to ensure that x->data contains non-zero floats
1287
+ x = np.array([123456789e199], dtype=np.float64)
1288
+ if IS_PYPY:
1289
+ x.resize((m, 0), refcheck=False)
1290
+ else:
1291
+ x.resize((m, 0))
1292
+ y = np.array([123456789e199], dtype=np.float64)
1293
+ if IS_PYPY:
1294
+ y.resize((0, n), refcheck=False)
1295
+ else:
1296
+ y.resize((0, n))
1297
+
1298
+ # `dot` should just return zero (m, n) matrix
1299
+ z = np.dot(x, y)
1300
+ assert_(np.all(z == 0))
1301
+ assert_(z.shape == (m, n))
1302
+
1303
+ def test_zeros(self):
1304
+ # Regression test for #1061.
1305
+ # Set a size which cannot fit into a 64 bits signed integer
1306
+ sz = 2 ** 64
1307
+ with assert_raises_regex(ValueError,
1308
+ 'Maximum allowed dimension exceeded'):
1309
+ np.empty(sz)
1310
+
1311
+ def test_huge_arange(self):
1312
+ # Regression test for #1062.
1313
+ # Set a size which cannot fit into a 64 bits signed integer
1314
+ sz = 2 ** 64
1315
+ with assert_raises_regex(ValueError,
1316
+ 'Maximum allowed size exceeded'):
1317
+ np.arange(sz)
1318
+ assert_(np.size == sz)
1319
+
1320
+ def test_fromiter_bytes(self):
1321
+ # Ticket #1058
1322
+ a = np.fromiter(list(range(10)), dtype='b')
1323
+ b = np.fromiter(list(range(10)), dtype='B')
1324
+ assert_(np.all(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
1325
+ assert_(np.all(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
1326
+
1327
+ def test_array_from_sequence_scalar_array(self):
1328
+ # Ticket #1078: segfaults when creating an array with a sequence of
1329
+ # 0d arrays.
1330
+ a = np.array((np.ones(2), np.array(2)), dtype=object)
1331
+ assert_equal(a.shape, (2,))
1332
+ assert_equal(a.dtype, np.dtype(object))
1333
+ assert_equal(a[0], np.ones(2))
1334
+ assert_equal(a[1], np.array(2))
1335
+
1336
+ a = np.array(((1,), np.array(1)), dtype=object)
1337
+ assert_equal(a.shape, (2,))
1338
+ assert_equal(a.dtype, np.dtype(object))
1339
+ assert_equal(a[0], (1,))
1340
+ assert_equal(a[1], np.array(1))
1341
+
1342
+ def test_array_from_sequence_scalar_array2(self):
1343
+ # Ticket #1081: weird array with strange input...
1344
+ t = np.array([np.array([]), np.array(0, object)], dtype=object)
1345
+ assert_equal(t.shape, (2,))
1346
+ assert_equal(t.dtype, np.dtype(object))
1347
+
1348
+ def test_array_too_big(self):
1349
+ # Ticket #1080.
1350
+ assert_raises(ValueError, np.zeros, [975] * 7, np.int8)
1351
+ assert_raises(ValueError, np.zeros, [26244] * 5, np.int8)
1352
+
1353
+ def test_dtype_keyerrors_(self):
1354
+ # Ticket #1106.
1355
+ dt = np.dtype([('f1', np.uint)])
1356
+ assert_raises(KeyError, dt.__getitem__, "f2")
1357
+ assert_raises(IndexError, dt.__getitem__, 1)
1358
+ assert_raises(TypeError, dt.__getitem__, 0.0)
1359
+
1360
+ def test_lexsort_buffer_length(self):
1361
+ # Ticket #1217, don't segfault.
1362
+ a = np.ones(100, dtype=np.int8)
1363
+ b = np.ones(100, dtype=np.int32)
1364
+ i = np.lexsort((a[::-1], b))
1365
+ assert_equal(i, np.arange(100, dtype=int))
1366
+
1367
+ def test_object_array_to_fixed_string(self):
1368
+ # Ticket #1235.
1369
+ a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
1370
+ b = np.array(a, dtype=(np.str_, 8))
1371
+ assert_equal(a, b)
1372
+ c = np.array(a, dtype=(np.str_, 5))
1373
+ assert_equal(c, np.array(['abcde', 'ijklm']))
1374
+ d = np.array(a, dtype=(np.str_, 12))
1375
+ assert_equal(a, d)
1376
+ e = np.empty((2, ), dtype=(np.str_, 8))
1377
+ e[:] = a[:]
1378
+ assert_equal(a, e)
1379
+
1380
+ def test_unicode_to_string_cast(self):
1381
+ # Ticket #1240.
1382
+ a = np.array([['abc', '\u03a3'],
1383
+ ['asdf', 'erw']],
1384
+ dtype='U')
1385
+ assert_raises(UnicodeEncodeError, np.array, a, 'S4')
1386
+
1387
+ def test_unicode_to_string_cast_error(self):
1388
+ # gh-15790
1389
+ a = np.array(['\x80'] * 129, dtype='U3')
1390
+ assert_raises(UnicodeEncodeError, np.array, a, 'S')
1391
+ b = a.reshape(3, 43)[:-1, :-1]
1392
+ assert_raises(UnicodeEncodeError, np.array, b, 'S')
1393
+
1394
+ def test_mixed_string_byte_array_creation(self):
1395
+ a = np.array(['1234', b'123'])
1396
+ assert_(a.itemsize == 16)
1397
+ a = np.array([b'123', '1234'])
1398
+ assert_(a.itemsize == 16)
1399
+ a = np.array(['1234', b'123', '12345'])
1400
+ assert_(a.itemsize == 20)
1401
+ a = np.array([b'123', '1234', b'12345'])
1402
+ assert_(a.itemsize == 20)
1403
+ a = np.array([b'123', '1234', b'1234'])
1404
+ assert_(a.itemsize == 16)
1405
+
1406
+ def test_misaligned_objects_segfault(self):
1407
+ # Ticket #1198 and #1267
1408
+ a1 = np.zeros((10,), dtype='O,c')
1409
+ a2 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'S10')
1410
+ a1['f0'] = a2
1411
+ repr(a1)
1412
+ np.argmax(a1['f0'])
1413
+ a1['f0'][1] = "FOO"
1414
+ a1['f0'] = "FOO"
1415
+ np.array(a1['f0'], dtype='S')
1416
+ np.nonzero(a1['f0'])
1417
+ a1.sort()
1418
+ copy.deepcopy(a1)
1419
+
1420
+ def test_misaligned_scalars_segfault(self):
1421
+ # Ticket #1267
1422
+ s1 = np.array(('a', 'Foo'), dtype='c,O')
1423
+ s2 = np.array(('b', 'Bar'), dtype='c,O')
1424
+ s1['f1'] = s2['f1']
1425
+ s1['f1'] = 'Baz'
1426
+
1427
+ def test_misaligned_dot_product_objects(self):
1428
+ # Ticket #1267
1429
+ # This didn't require a fix, but it's worth testing anyway, because
1430
+ # it may fail if .dot stops enforcing the arrays to be BEHAVED
1431
+ a = np.array([[(1, 'a'), (0, 'a')], [(0, 'a'), (1, 'a')]], dtype='O,c')
1432
+ b = np.array([[(4, 'a'), (1, 'a')], [(2, 'a'), (2, 'a')]], dtype='O,c')
1433
+ np.dot(a['f0'], b['f0'])
1434
+
1435
+ def test_byteswap_complex_scalar(self):
1436
+ # Ticket #1259 and gh-441
1437
+ for dtype in [np.dtype('<' + t) for t in np.typecodes['Complex']]:
1438
+ z = np.array([2.2 - 1.1j], dtype)
1439
+ x = z[0] # always native-endian
1440
+ y = x.byteswap()
1441
+ if x.dtype.byteorder == z.dtype.byteorder:
1442
+ # little-endian machine
1443
+ assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype.newbyteorder()))
1444
+ else:
1445
+ # big-endian machine
1446
+ assert_equal(x, np.frombuffer(y.tobytes(), dtype=dtype))
1447
+ # double check real and imaginary parts:
1448
+ assert_equal(x.real, y.real.byteswap())
1449
+ assert_equal(x.imag, y.imag.byteswap())
1450
+
1451
+ def test_structured_arrays_with_objects1(self):
1452
+ # Ticket #1299
1453
+ stra = 'aaaa'
1454
+ strb = 'bbbb'
1455
+ x = np.array([[(0, stra), (1, strb)]], 'i8,O')
1456
+ x[x.nonzero()] = x.ravel()[:1]
1457
+ assert_(x[0, 1] == x[0, 0])
1458
+
1459
+ @pytest.mark.skipif(
1460
+ sys.version_info >= (3, 12),
1461
+ reason="Python 3.12 has immortal refcounts, this test no longer works."
1462
+ )
1463
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
1464
+ def test_structured_arrays_with_objects2(self):
1465
+ # Ticket #1299 second test
1466
+ stra = 'aaaa'
1467
+ strb = 'bbbb'
1468
+ numb = sys.getrefcount(strb)
1469
+ numa = sys.getrefcount(stra)
1470
+ x = np.array([[(0, stra), (1, strb)]], 'i8,O')
1471
+ x[x.nonzero()] = x.ravel()[:1]
1472
+ assert_(sys.getrefcount(strb) == numb)
1473
+ assert_(sys.getrefcount(stra) == numa + 2)
1474
+
1475
+ def test_duplicate_title_and_name(self):
1476
+ # Ticket #1254
1477
+ dtspec = [(('a', 'a'), 'i'), ('b', 'i')]
1478
+ assert_raises(ValueError, np.dtype, dtspec)
1479
+
1480
+ def test_signed_integer_division_overflow(self):
1481
+ # Ticket #1317.
1482
+ def test_type(t):
1483
+ min = np.array([np.iinfo(t).min])
1484
+ min //= -1
1485
+
1486
+ with np.errstate(over="ignore"):
1487
+ for t in (np.int8, np.int16, np.int32, np.int64, int):
1488
+ test_type(t)
1489
+
1490
+ def test_buffer_hashlib(self):
1491
+ from hashlib import sha256
1492
+
1493
+ x = np.array([1, 2, 3], dtype=np.dtype('<i4'))
1494
+ assert_equal(
1495
+ sha256(x).hexdigest(),
1496
+ '4636993d3e1da4e9d6b8f87b79e8f7c6d018580d52661950eabc3845c5897a4d'
1497
+ )
1498
+
1499
+ def test_0d_string_scalar(self):
1500
+ # Bug #1436; the following should succeed
1501
+ np.asarray('x', '>c')
1502
+
1503
+ def test_log1p_compiler_shenanigans(self):
1504
+ # Check if log1p is behaving on 32 bit intel systems.
1505
+ assert_(np.isfinite(np.log1p(np.exp2(-53))))
1506
+
1507
+ def test_fromiter_comparison(self):
1508
+ a = np.fromiter(list(range(10)), dtype='b')
1509
+ b = np.fromiter(list(range(10)), dtype='B')
1510
+ assert_(np.all(a == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
1511
+ assert_(np.all(b == np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])))
1512
+
1513
+ def test_fromstring_crash(self):
1514
+ with assert_raises(ValueError):
1515
+ np.fromstring(b'aa, aa, 1.0', sep=',')
1516
+
1517
+ def test_ticket_1539(self):
1518
+ dtypes = [x for x in np._core.sctypeDict.values()
1519
+ if (issubclass(x, np.number)
1520
+ and not issubclass(x, np.timedelta64))]
1521
+ a = np.array([], np.bool) # not x[0] because it is unordered
1522
+ failures = []
1523
+
1524
+ for x in dtypes:
1525
+ b = a.astype(x)
1526
+ for y in dtypes:
1527
+ c = a.astype(y)
1528
+ try:
1529
+ d = np.dot(b, c)
1530
+ except TypeError:
1531
+ failures.append((x, y))
1532
+ else:
1533
+ if d != 0:
1534
+ failures.append((x, y))
1535
+ if failures:
1536
+ raise AssertionError(f"Failures: {failures!r}")
1537
+
1538
+ def test_ticket_1538(self):
1539
+ x = np.finfo(np.float32)
1540
+ for name in ('eps', 'epsneg', 'max', 'min', 'resolution', 'tiny'):
1541
+ assert_equal(type(getattr(x, name)), np.float32,
1542
+ err_msg=name)
1543
+
1544
+ def test_ticket_1434(self):
1545
+ # Check that the out= argument in var and std has an effect
1546
+ data = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
1547
+ out = np.zeros((3,))
1548
+
1549
+ ret = data.var(axis=1, out=out)
1550
+ assert_(ret is out)
1551
+ assert_array_equal(ret, data.var(axis=1))
1552
+
1553
+ ret = data.std(axis=1, out=out)
1554
+ assert_(ret is out)
1555
+ assert_array_equal(ret, data.std(axis=1))
1556
+
1557
+ def test_complex_nan_maximum(self):
1558
+ cnan = complex(0, np.nan)
1559
+ assert_equal(np.maximum(1, cnan), cnan)
1560
+
1561
+ def test_subclass_int_tuple_assignment(self):
1562
+ # ticket #1563
1563
+ class Subclass(np.ndarray):
1564
+ def __new__(cls, i):
1565
+ return np.ones((i,)).view(cls)
1566
+
1567
+ x = Subclass(5)
1568
+ x[(0,)] = 2 # shouldn't raise an exception
1569
+ assert_equal(x[0], 2)
1570
+
1571
+ def test_ufunc_no_unnecessary_views(self):
1572
+ # ticket #1548
1573
+ class Subclass(np.ndarray):
1574
+ pass
1575
+ x = np.array([1, 2, 3]).view(Subclass)
1576
+ y = np.add(x, x, x)
1577
+ assert_equal(id(x), id(y))
1578
+
1579
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
1580
+ def test_take_refcount(self):
1581
+ # ticket #939
1582
+ a = np.arange(16, dtype=float)
1583
+ a.shape = (4, 4)
1584
+ lut = np.ones((5 + 3, 4), float)
1585
+ rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype)
1586
+ c1 = sys.getrefcount(rgba)
1587
+ try:
1588
+ lut.take(a, axis=0, mode='clip', out=rgba)
1589
+ except TypeError:
1590
+ pass
1591
+ c2 = sys.getrefcount(rgba)
1592
+ assert_equal(c1, c2)
1593
+
1594
+ def test_fromfile_tofile_seeks(self):
1595
+ # tofile/fromfile used to get (#1610) the Python file handle out of sync
1596
+ with tempfile.NamedTemporaryFile() as f:
1597
+ f.write(np.arange(255, dtype='u1').tobytes())
1598
+
1599
+ f.seek(20)
1600
+ ret = np.fromfile(f, count=4, dtype='u1')
1601
+ assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1'))
1602
+ assert_equal(f.tell(), 24)
1603
+
1604
+ f.seek(40)
1605
+ np.array([1, 2, 3], dtype='u1').tofile(f)
1606
+ assert_equal(f.tell(), 43)
1607
+
1608
+ f.seek(40)
1609
+ data = f.read(3)
1610
+ assert_equal(data, b"\x01\x02\x03")
1611
+
1612
+ f.seek(80)
1613
+ f.read(4)
1614
+ data = np.fromfile(f, dtype='u1', count=4)
1615
+ assert_equal(data, np.array([84, 85, 86, 87], dtype='u1'))
1616
+
1617
+ def test_complex_scalar_warning(self):
1618
+ for tp in [np.csingle, np.cdouble, np.clongdouble]:
1619
+ x = tp(1 + 2j)
1620
+ assert_warns(ComplexWarning, float, x)
1621
+ with suppress_warnings() as sup:
1622
+ sup.filter(ComplexWarning)
1623
+ assert_equal(float(x), float(x.real))
1624
+
1625
+ def test_complex_scalar_complex_cast(self):
1626
+ for tp in [np.csingle, np.cdouble, np.clongdouble]:
1627
+ x = tp(1 + 2j)
1628
+ assert_equal(complex(x), 1 + 2j)
1629
+
1630
+ def test_complex_boolean_cast(self):
1631
+ # Ticket #2218
1632
+ for tp in [np.csingle, np.cdouble, np.clongdouble]:
1633
+ x = np.array([0, 0 + 0.5j, 0.5 + 0j], dtype=tp)
1634
+ assert_equal(x.astype(bool), np.array([0, 1, 1], dtype=bool))
1635
+ assert_(np.any(x))
1636
+ assert_(np.all(x[1:]))
1637
+
1638
+ def test_uint_int_conversion(self):
1639
+ x = 2**64 - 1
1640
+ assert_equal(int(np.uint64(x)), x)
1641
+
1642
+ def test_duplicate_field_names_assign(self):
1643
+ ra = np.fromiter(((i * 3, i * 2) for i in range(10)), dtype='i8,f8')
1644
+ ra.dtype.names = ('f1', 'f2')
1645
+ repr(ra) # should not cause a segmentation fault
1646
+ assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1'))
1647
+
1648
+ def test_eq_string_and_object_array(self):
1649
+ # From e-mail thread "__eq__ with str and object" (Keith Goodman)
1650
+ a1 = np.array(['a', 'b'], dtype=object)
1651
+ a2 = np.array(['a', 'c'])
1652
+ assert_array_equal(a1 == a2, [True, False])
1653
+ assert_array_equal(a2 == a1, [True, False])
1654
+
1655
+ def test_nonzero_byteswap(self):
1656
+ a = np.array([0x80000000, 0x00000080, 0], dtype=np.uint32)
1657
+ a.dtype = np.float32
1658
+ assert_equal(a.nonzero()[0], [1])
1659
+ a = a.byteswap()
1660
+ a = a.view(a.dtype.newbyteorder())
1661
+ assert_equal(a.nonzero()[0], [1]) # [0] if nonzero() ignores swap
1662
+
1663
+ def test_empty_mul(self):
1664
+ a = np.array([1.])
1665
+ a[1:1] *= 2
1666
+ assert_equal(a, [1.])
1667
+
1668
+ def test_array_side_effect(self):
1669
+ # The second use of itemsize was throwing an exception because in
1670
+ # ctors.c, discover_itemsize was calling PyObject_Length without
1671
+ # checking the return code. This failed to get the length of the
1672
+ # number 2, and the exception hung around until something checked
1673
+ # PyErr_Occurred() and returned an error.
1674
+ assert_equal(np.dtype('S10').itemsize, 10)
1675
+ np.array([['abc', 2], ['long ', '0123456789']], dtype=np.bytes_)
1676
+ assert_equal(np.dtype('S10').itemsize, 10)
1677
+
1678
+ def test_any_float(self):
1679
+ # all and any for floats
1680
+ a = np.array([0.1, 0.9])
1681
+ assert_(np.any(a))
1682
+ assert_(np.all(a))
1683
+
1684
+ def test_large_float_sum(self):
1685
+ a = np.arange(10000, dtype='f')
1686
+ assert_equal(a.sum(dtype='d'), a.astype('d').sum())
1687
+
1688
+ def test_ufunc_casting_out(self):
1689
+ a = np.array(1.0, dtype=np.float32)
1690
+ b = np.array(1.0, dtype=np.float64)
1691
+ c = np.array(1.0, dtype=np.float32)
1692
+ np.add(a, b, out=c)
1693
+ assert_equal(c, 2.0)
1694
+
1695
+ def test_array_scalar_contiguous(self):
1696
+ # Array scalars are both C and Fortran contiguous
1697
+ assert_(np.array(1.0).flags.c_contiguous)
1698
+ assert_(np.array(1.0).flags.f_contiguous)
1699
+ assert_(np.array(np.float32(1.0)).flags.c_contiguous)
1700
+ assert_(np.array(np.float32(1.0)).flags.f_contiguous)
1701
+
1702
+ def test_squeeze_contiguous(self):
1703
+ # Similar to GitHub issue #387
1704
+ a = np.zeros((1, 2)).squeeze()
1705
+ b = np.zeros((2, 2, 2), order='F')[:, :, ::2].squeeze()
1706
+ assert_(a.flags.c_contiguous)
1707
+ assert_(a.flags.f_contiguous)
1708
+ assert_(b.flags.f_contiguous)
1709
+
1710
+ def test_squeeze_axis_handling(self):
1711
+ # Issue #10779
1712
+ # Ensure proper handling of objects
1713
+ # that don't support axis specification
1714
+ # when squeezing
1715
+
1716
+ class OldSqueeze(np.ndarray):
1717
+
1718
+ def __new__(cls,
1719
+ input_array):
1720
+ obj = np.asarray(input_array).view(cls)
1721
+ return obj
1722
+
1723
+ # it is perfectly reasonable that prior
1724
+ # to numpy version 1.7.0 a subclass of ndarray
1725
+ # might have been created that did not expect
1726
+ # squeeze to have an axis argument
1727
+ # NOTE: this example is somewhat artificial;
1728
+ # it is designed to simulate an old API
1729
+ # expectation to guard against regression
1730
+ def squeeze(self):
1731
+ return super().squeeze()
1732
+
1733
+ oldsqueeze = OldSqueeze(np.array([[1], [2], [3]]))
1734
+
1735
+ # if no axis argument is specified the old API
1736
+ # expectation should give the correct result
1737
+ assert_equal(np.squeeze(oldsqueeze),
1738
+ np.array([1, 2, 3]))
1739
+
1740
+ # likewise, axis=None should work perfectly well
1741
+ # with the old API expectation
1742
+ assert_equal(np.squeeze(oldsqueeze, axis=None),
1743
+ np.array([1, 2, 3]))
1744
+
1745
+ # however, specification of any particular axis
1746
+ # should raise a TypeError in the context of the
1747
+ # old API specification, even when using a valid
1748
+ # axis specification like 1 for this array
1749
+ with assert_raises(TypeError):
1750
+ # this would silently succeed for array
1751
+ # subclasses / objects that did not support
1752
+ # squeeze axis argument handling before fixing
1753
+ # Issue #10779
1754
+ np.squeeze(oldsqueeze, axis=1)
1755
+
1756
+ # check for the same behavior when using an invalid
1757
+ # axis specification -- in this case axis=0 does not
1758
+ # have size 1, but the priority should be to raise
1759
+ # a TypeError for the axis argument and NOT a
1760
+ # ValueError for squeezing a non-empty dimension
1761
+ with assert_raises(TypeError):
1762
+ np.squeeze(oldsqueeze, axis=0)
1763
+
1764
+ # the new API knows how to handle the axis
1765
+ # argument and will return a ValueError if
1766
+ # attempting to squeeze an axis that is not
1767
+ # of length 1
1768
+ with assert_raises(ValueError):
1769
+ np.squeeze(np.array([[1], [2], [3]]), axis=0)
1770
+
1771
+ def test_reduce_contiguous(self):
1772
+ # GitHub issue #387
1773
+ a = np.add.reduce(np.zeros((2, 1, 2)), (0, 1))
1774
+ b = np.add.reduce(np.zeros((2, 1, 2)), 1)
1775
+ assert_(a.flags.c_contiguous)
1776
+ assert_(a.flags.f_contiguous)
1777
+ assert_(b.flags.c_contiguous)
1778
+
1779
+ @pytest.mark.skipif(IS_PYSTON, reason="Pyston disables recursion checking")
1780
+ @pytest.mark.skipif(IS_WASM, reason="Pyodide/WASM has limited stack size")
1781
+ def test_object_array_self_reference(self):
1782
+ # Object arrays with references to themselves can cause problems
1783
+ a = np.array(0, dtype=object)
1784
+ a[()] = a
1785
+ assert_raises(RecursionError, int, a)
1786
+ assert_raises(RecursionError, float, a)
1787
+ a[()] = None
1788
+
1789
+ @pytest.mark.skipif(IS_PYSTON, reason="Pyston disables recursion checking")
1790
+ @pytest.mark.skipif(IS_WASM, reason="Pyodide/WASM has limited stack size")
1791
+ def test_object_array_circular_reference(self):
1792
+ # Test the same for a circular reference.
1793
+ a = np.array(0, dtype=object)
1794
+ b = np.array(0, dtype=object)
1795
+ a[()] = b
1796
+ b[()] = a
1797
+ assert_raises(RecursionError, int, a)
1798
+ # NumPy has no tp_traverse currently, so circular references
1799
+ # cannot be detected. So resolve it:
1800
+ a[()] = None
1801
+
1802
+ # This was causing a to become like the above
1803
+ a = np.array(0, dtype=object)
1804
+ a[...] += 1
1805
+ assert_equal(a, 1)
1806
+
1807
+ def test_object_array_nested(self):
1808
+ # but is fine with a reference to a different array
1809
+ a = np.array(0, dtype=object)
1810
+ b = np.array(0, dtype=object)
1811
+ a[()] = b
1812
+ assert_equal(int(a), int(0)) # noqa: UP018
1813
+ assert_equal(float(a), float(0))
1814
+
1815
+ def test_object_array_self_copy(self):
1816
+ # An object array being copied into itself DECREF'ed before INCREF'ing
1817
+ # causing segmentation faults (gh-3787)
1818
+ a = np.array(object(), dtype=object)
1819
+ np.copyto(a, a)
1820
+ if HAS_REFCOUNT:
1821
+ assert_(sys.getrefcount(a[()]) == 2)
1822
+ a[()].__class__ # will segfault if object was deleted
1823
+
1824
+ def test_zerosize_accumulate(self):
1825
+ "Ticket #1733"
1826
+ x = np.array([[42, 0]], dtype=np.uint32)
1827
+ assert_equal(np.add.accumulate(x[:-1, 0]), [])
1828
+
1829
+ def test_objectarray_setfield(self):
1830
+ # Setfield should not overwrite Object fields with non-Object data
1831
+ x = np.array([1, 2, 3], dtype=object)
1832
+ assert_raises(TypeError, x.setfield, 4, np.int32, 0)
1833
+
1834
+ def test_setting_rank0_string(self):
1835
+ "Ticket #1736"
1836
+ s1 = b"hello1"
1837
+ s2 = b"hello2"
1838
+ a = np.zeros((), dtype="S10")
1839
+ a[()] = s1
1840
+ assert_equal(a, np.array(s1))
1841
+ a[()] = np.array(s2)
1842
+ assert_equal(a, np.array(s2))
1843
+
1844
+ a = np.zeros((), dtype='f4')
1845
+ a[()] = 3
1846
+ assert_equal(a, np.array(3))
1847
+ a[()] = np.array(4)
1848
+ assert_equal(a, np.array(4))
1849
+
1850
+ def test_string_astype(self):
1851
+ "Ticket #1748"
1852
+ s1 = b'black'
1853
+ s2 = b'white'
1854
+ s3 = b'other'
1855
+ a = np.array([[s1], [s2], [s3]])
1856
+ assert_equal(a.dtype, np.dtype('S5'))
1857
+ b = a.astype(np.dtype('S0'))
1858
+ assert_equal(b.dtype, np.dtype('S5'))
1859
+
1860
+ def test_ticket_1756(self):
1861
+ # Ticket #1756
1862
+ s = b'0123456789abcdef'
1863
+ a = np.array([s] * 5)
1864
+ for i in range(1, 17):
1865
+ a1 = np.array(a, "|S%d" % i)
1866
+ a2 = np.array([s[:i]] * 5)
1867
+ assert_equal(a1, a2)
1868
+
1869
+ def test_fields_strides(self):
1870
+ "gh-2355"
1871
+ r = np.frombuffer(b'abcdefghijklmnop' * 4 * 3, dtype='i4,(2,3)u2')
1872
+ assert_equal(r[0:3:2]['f1'], r['f1'][0:3:2])
1873
+ assert_equal(r[0:3:2]['f1'][0], r[0:3:2][0]['f1'])
1874
+ assert_equal(r[0:3:2]['f1'][0][()], r[0:3:2][0]['f1'][()])
1875
+ assert_equal(r[0:3:2]['f1'][0].strides, r[0:3:2][0]['f1'].strides)
1876
+
1877
+ def test_alignment_update(self):
1878
+ # Check that alignment flag is updated on stride setting
1879
+ a = np.arange(10)
1880
+ assert_(a.flags.aligned)
1881
+ a.strides = 3
1882
+ assert_(not a.flags.aligned)
1883
+
1884
+ def test_ticket_1770(self):
1885
+ "Should not segfault on python 3k"
1886
+ import numpy as np
1887
+ try:
1888
+ a = np.zeros((1,), dtype=[('f1', 'f')])
1889
+ a['f1'] = 1
1890
+ a['f2'] = 1
1891
+ except ValueError:
1892
+ pass
1893
+ except Exception:
1894
+ raise AssertionError
1895
+
1896
+ def test_ticket_1608(self):
1897
+ "x.flat shouldn't modify data"
1898
+ x = np.array([[1, 2], [3, 4]]).T
1899
+ np.array(x.flat)
1900
+ assert_equal(x, [[1, 3], [2, 4]])
1901
+
1902
+ def test_pickle_string_overwrite(self):
1903
+ import re
1904
+
1905
+ data = np.array([1], dtype='b')
1906
+ blob = pickle.dumps(data, protocol=1)
1907
+ data = pickle.loads(blob)
1908
+
1909
+ # Check that loads does not clobber interned strings
1910
+ s = re.sub(r"a(.)", "\x01\\1", "a_")
1911
+ assert_equal(s[0], "\x01")
1912
+ data[0] = 0x6a
1913
+ s = re.sub(r"a(.)", "\x01\\1", "a_")
1914
+ assert_equal(s[0], "\x01")
1915
+
1916
+ def test_pickle_bytes_overwrite(self):
1917
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
1918
+ data = np.array([1], dtype='b')
1919
+ data = pickle.loads(pickle.dumps(data, protocol=proto))
1920
+ data[0] = 0x7d
1921
+ bytestring = "\x01 ".encode('ascii')
1922
+ assert_equal(bytestring[0:1], '\x01'.encode('ascii'))
1923
+
1924
+ def test_pickle_py2_array_latin1_hack(self):
1925
+ # Check that unpickling hacks in Py3 that support
1926
+ # encoding='latin1' work correctly.
1927
+
1928
+ # Python2 output for pickle.dumps(numpy.array([129], dtype='b'))
1929
+ data = b"cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I1\ntp6\ncnumpy\ndtype\np7\n(S'i1'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x81'\np13\ntp14\nb."
1930
+ # This should work:
1931
+ result = pickle.loads(data, encoding='latin1')
1932
+ assert_array_equal(result, np.array([129]).astype('b'))
1933
+ # Should not segfault:
1934
+ assert_raises(Exception, pickle.loads, data, encoding='koi8-r')
1935
+
1936
+ def test_pickle_py2_scalar_latin1_hack(self):
1937
+ # Check that scalar unpickling hack in Py3 that supports
1938
+ # encoding='latin1' work correctly.
1939
+
1940
+ # Python2 output for pickle.dumps(...)
1941
+ datas = [
1942
+ # (original, python2_pickle, koi8r_validity)
1943
+ (np.str_('\u6bd2'),
1944
+ b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'U1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI4\nI4\nI0\ntp6\nbS'\\xd2k\\x00\\x00'\np7\ntp8\nRp9\n.",
1945
+ 'invalid'),
1946
+
1947
+ (np.float64(9e123),
1948
+ b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'f8'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'<'\np5\nNNNI-1\nI-1\nI0\ntp6\nbS'O\\x81\\xb7Z\\xaa:\\xabY'\np7\ntp8\nRp9\n.",
1949
+ 'invalid'),
1950
+
1951
+ # different 8-bit code point in KOI8-R vs latin1
1952
+ (np.bytes_(b'\x9c'),
1953
+ b"cnumpy.core.multiarray\nscalar\np0\n(cnumpy\ndtype\np1\n(S'S1'\np2\nI0\nI1\ntp3\nRp4\n(I3\nS'|'\np5\nNNNI1\nI1\nI0\ntp6\nbS'\\x9c'\np7\ntp8\nRp9\n.",
1954
+ 'different'),
1955
+ ]
1956
+ for original, data, koi8r_validity in datas:
1957
+ result = pickle.loads(data, encoding='latin1')
1958
+ assert_equal(result, original)
1959
+
1960
+ # Decoding under non-latin1 encoding (e.g.) KOI8-R can
1961
+ # produce bad results, but should not segfault.
1962
+ if koi8r_validity == 'different':
1963
+ # Unicode code points happen to lie within latin1,
1964
+ # but are different in koi8-r, resulting to silent
1965
+ # bogus results
1966
+ result = pickle.loads(data, encoding='koi8-r')
1967
+ assert_(result != original)
1968
+ elif koi8r_validity == 'invalid':
1969
+ # Unicode code points outside latin1, so results
1970
+ # to an encoding exception
1971
+ assert_raises(
1972
+ ValueError, pickle.loads, data, encoding='koi8-r'
1973
+ )
1974
+ else:
1975
+ raise ValueError(koi8r_validity)
1976
+
1977
+ def test_structured_type_to_object(self):
1978
+ a_rec = np.array([(0, 1), (3, 2)], dtype='i4,i8')
1979
+ a_obj = np.empty((2,), dtype=object)
1980
+ a_obj[0] = (0, 1)
1981
+ a_obj[1] = (3, 2)
1982
+ # astype records -> object
1983
+ assert_equal(a_rec.astype(object), a_obj)
1984
+ # '=' records -> object
1985
+ b = np.empty_like(a_obj)
1986
+ b[...] = a_rec
1987
+ assert_equal(b, a_obj)
1988
+ # '=' object -> records
1989
+ b = np.empty_like(a_rec)
1990
+ b[...] = a_obj
1991
+ assert_equal(b, a_rec)
1992
+
1993
+ def test_assign_obj_listoflists(self):
1994
+ # Ticket # 1870
1995
+ # The inner list should get assigned to the object elements
1996
+ a = np.zeros(4, dtype=object)
1997
+ b = a.copy()
1998
+ a[0] = [1]
1999
+ a[1] = [2]
2000
+ a[2] = [3]
2001
+ a[3] = [4]
2002
+ b[...] = [[1], [2], [3], [4]]
2003
+ assert_equal(a, b)
2004
+ # The first dimension should get broadcast
2005
+ a = np.zeros((2, 2), dtype=object)
2006
+ a[...] = [[1, 2]]
2007
+ assert_equal(a, [[1, 2], [1, 2]])
2008
+
2009
+ @pytest.mark.slow_pypy
2010
+ def test_memoryleak(self):
2011
+ # Ticket #1917 - ensure that array data doesn't leak
2012
+ for i in range(1000):
2013
+ # 100MB times 1000 would give 100GB of memory usage if it leaks
2014
+ a = np.empty((100000000,), dtype='i1')
2015
+ del a
2016
+
2017
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2018
+ def test_ufunc_reduce_memoryleak(self):
2019
+ a = np.arange(6)
2020
+ acnt = sys.getrefcount(a)
2021
+ np.add.reduce(a)
2022
+ assert_equal(sys.getrefcount(a), acnt)
2023
+
2024
+ def test_search_sorted_invalid_arguments(self):
2025
+ # Ticket #2021, should not segfault.
2026
+ x = np.arange(0, 4, dtype='datetime64[D]')
2027
+ assert_raises(TypeError, x.searchsorted, 1)
2028
+
2029
+ def test_string_truncation(self):
2030
+ # Ticket #1990 - Data can be truncated in creation of an array from a
2031
+ # mixed sequence of numeric values and strings (gh-2583)
2032
+ for val in [True, 1234, 123.4, complex(1, 234)]:
2033
+ for tostr, dtype in [(asunicode, "U"), (asbytes, "S")]:
2034
+ b = np.array([val, tostr('xx')], dtype=dtype)
2035
+ assert_equal(tostr(b[0]), tostr(val))
2036
+ b = np.array([tostr('xx'), val], dtype=dtype)
2037
+ assert_equal(tostr(b[1]), tostr(val))
2038
+
2039
+ # test also with longer strings
2040
+ b = np.array([val, tostr('xxxxxxxxxx')], dtype=dtype)
2041
+ assert_equal(tostr(b[0]), tostr(val))
2042
+ b = np.array([tostr('xxxxxxxxxx'), val], dtype=dtype)
2043
+ assert_equal(tostr(b[1]), tostr(val))
2044
+
2045
+ def test_string_truncation_ucs2(self):
2046
+ # Ticket #2081. Python compiled with two byte unicode
2047
+ # can lead to truncation if itemsize is not properly
2048
+ # adjusted for NumPy's four byte unicode.
2049
+ a = np.array(['abcd'])
2050
+ assert_equal(a.dtype.itemsize, 16)
2051
+
2052
+ def test_unique_stable(self):
2053
+ # Ticket #2063 must always choose stable sort for argsort to
2054
+ # get consistent results
2055
+ v = np.array(([0] * 5 + [1] * 6 + [2] * 6) * 4)
2056
+ res = np.unique(v, return_index=True)
2057
+ tgt = (np.array([0, 1, 2]), np.array([0, 5, 11]))
2058
+ assert_equal(res, tgt)
2059
+
2060
+ def test_unicode_alloc_dealloc_match(self):
2061
+ # Ticket #1578, the mismatch only showed up when running
2062
+ # python-debug for python versions >= 2.7, and then as
2063
+ # a core dump and error message.
2064
+ a = np.array(['abc'], dtype=np.str_)[0]
2065
+ del a
2066
+
2067
+ def test_refcount_error_in_clip(self):
2068
+ # Ticket #1588
2069
+ a = np.zeros((2,), dtype='>i2').clip(min=0)
2070
+ x = a + a
2071
+ # This used to segfault:
2072
+ y = str(x)
2073
+ # Check the final string:
2074
+ assert_(y == "[0 0]")
2075
+
2076
+ def test_searchsorted_wrong_dtype(self):
2077
+ # Ticket #2189, it used to segfault, so we check that it raises the
2078
+ # proper exception.
2079
+ a = np.array([('a', 1)], dtype='S1, int')
2080
+ assert_raises(TypeError, np.searchsorted, a, 1.2)
2081
+ # Ticket #2066, similar problem:
2082
+ dtype = np.rec.format_parser(['i4', 'i4'], [], [])
2083
+ a = np.recarray((2,), dtype)
2084
+ a[...] = [(1, 2), (3, 4)]
2085
+ assert_raises(TypeError, np.searchsorted, a, 1)
2086
+
2087
+ def test_complex64_alignment(self):
2088
+ # Issue gh-2668 (trac 2076), segfault on sparc due to misalignment
2089
+ dtt = np.complex64
2090
+ arr = np.arange(10, dtype=dtt)
2091
+ # 2D array
2092
+ arr2 = np.reshape(arr, (2, 5))
2093
+ # Fortran write followed by (C or F) read caused bus error
2094
+ data_str = arr2.tobytes('F')
2095
+ data_back = np.ndarray(arr2.shape,
2096
+ arr2.dtype,
2097
+ buffer=data_str,
2098
+ order='F')
2099
+ assert_array_equal(arr2, data_back)
2100
+
2101
+ def test_structured_count_nonzero(self):
2102
+ arr = np.array([0, 1]).astype('i4, 2i4')[:1]
2103
+ count = np.count_nonzero(arr)
2104
+ assert_equal(count, 0)
2105
+
2106
+ def test_copymodule_preserves_f_contiguity(self):
2107
+ a = np.empty((2, 2), order='F')
2108
+ b = copy.copy(a)
2109
+ c = copy.deepcopy(a)
2110
+ assert_(b.flags.fortran)
2111
+ assert_(b.flags.f_contiguous)
2112
+ assert_(c.flags.fortran)
2113
+ assert_(c.flags.f_contiguous)
2114
+
2115
+ def test_fortran_order_buffer(self):
2116
+ import numpy as np
2117
+ a = np.array([['Hello', 'Foob']], dtype='U5', order='F')
2118
+ arr = np.ndarray(shape=[1, 2, 5], dtype='U1', buffer=a)
2119
+ arr2 = np.array([[['H', 'e', 'l', 'l', 'o'],
2120
+ ['F', 'o', 'o', 'b', '']]])
2121
+ assert_array_equal(arr, arr2)
2122
+
2123
+ def test_assign_from_sequence_error(self):
2124
+ # Ticket #4024.
2125
+ arr = np.array([1, 2, 3])
2126
+ assert_raises(ValueError, arr.__setitem__, slice(None), [9, 9])
2127
+ arr.__setitem__(slice(None), [9])
2128
+ assert_equal(arr, [9, 9, 9])
2129
+
2130
+ def test_format_on_flex_array_element(self):
2131
+ # Ticket #4369.
2132
+ dt = np.dtype([('date', '<M8[D]'), ('val', '<f8')])
2133
+ arr = np.array([('2000-01-01', 1)], dt)
2134
+ formatted = f'{arr[0]}'
2135
+ assert_equal(formatted, str(arr[0]))
2136
+
2137
+ def test_deepcopy_on_0d_array(self):
2138
+ # Ticket #3311.
2139
+ arr = np.array(3)
2140
+ arr_cp = copy.deepcopy(arr)
2141
+
2142
+ assert_equal(arr, arr_cp)
2143
+ assert_equal(arr.shape, arr_cp.shape)
2144
+ assert_equal(int(arr), int(arr_cp))
2145
+ assert_(arr is not arr_cp)
2146
+ assert_(isinstance(arr_cp, type(arr)))
2147
+
2148
+ def test_deepcopy_F_order_object_array(self):
2149
+ # Ticket #6456.
2150
+ a = {'a': 1}
2151
+ b = {'b': 2}
2152
+ arr = np.array([[a, b], [a, b]], order='F')
2153
+ arr_cp = copy.deepcopy(arr)
2154
+
2155
+ assert_equal(arr, arr_cp)
2156
+ assert_(arr is not arr_cp)
2157
+ # Ensure that we have actually copied the item.
2158
+ assert_(arr[0, 1] is not arr_cp[1, 1])
2159
+ # Ensure we are allowed to have references to the same object.
2160
+ assert_(arr[0, 1] is arr[1, 1])
2161
+ # Check the references hold for the copied objects.
2162
+ assert_(arr_cp[0, 1] is arr_cp[1, 1])
2163
+
2164
+ def test_deepcopy_empty_object_array(self):
2165
+ # Ticket #8536.
2166
+ # Deepcopy should succeed
2167
+ a = np.array([], dtype=object)
2168
+ b = copy.deepcopy(a)
2169
+ assert_(a.shape == b.shape)
2170
+
2171
+ def test_bool_subscript_crash(self):
2172
+ # gh-4494
2173
+ c = np.rec.array([(1, 2, 3), (4, 5, 6)])
2174
+ masked = c[np.array([True, False])]
2175
+ base = masked.base
2176
+ del masked, c
2177
+ base.dtype
2178
+
2179
+ def test_richcompare_crash(self):
2180
+ # gh-4613
2181
+ import operator as op
2182
+
2183
+ # dummy class where __array__ throws exception
2184
+ class Foo:
2185
+ __array_priority__ = 1002
2186
+
2187
+ def __array__(self, *args, **kwargs):
2188
+ raise Exception
2189
+
2190
+ rhs = Foo()
2191
+ lhs = np.array(1)
2192
+ for f in [op.lt, op.le, op.gt, op.ge]:
2193
+ assert_raises(TypeError, f, lhs, rhs)
2194
+ assert_(not op.eq(lhs, rhs))
2195
+ assert_(op.ne(lhs, rhs))
2196
+
2197
+ def test_richcompare_scalar_and_subclass(self):
2198
+ # gh-4709
2199
+ class Foo(np.ndarray):
2200
+ def __eq__(self, other):
2201
+ return "OK"
2202
+
2203
+ x = np.array([1, 2, 3]).view(Foo)
2204
+ assert_equal(10 == x, "OK")
2205
+ assert_equal(np.int32(10) == x, "OK")
2206
+ assert_equal(np.array([10]) == x, "OK")
2207
+
2208
+ def test_pickle_empty_string(self):
2209
+ # gh-3926
2210
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
2211
+ test_string = np.bytes_('')
2212
+ assert_equal(pickle.loads(
2213
+ pickle.dumps(test_string, protocol=proto)), test_string)
2214
+
2215
+ def test_frompyfunc_many_args(self):
2216
+ # gh-5672
2217
+
2218
+ def passer(*args):
2219
+ pass
2220
+
2221
+ assert_raises(ValueError, np.frompyfunc, passer, 64, 1)
2222
+
2223
+ def test_repeat_broadcasting(self):
2224
+ # gh-5743
2225
+ a = np.arange(60).reshape(3, 4, 5)
2226
+ for axis in chain(range(-a.ndim, a.ndim), [None]):
2227
+ assert_equal(a.repeat(2, axis=axis), a.repeat([2], axis=axis))
2228
+
2229
+ def test_frompyfunc_nout_0(self):
2230
+ # gh-2014
2231
+
2232
+ def f(x):
2233
+ x[0], x[-1] = x[-1], x[0]
2234
+
2235
+ uf = np.frompyfunc(f, 1, 0)
2236
+ a = np.array([[1, 2, 3], [4, 5], [6, 7, 8, 9]], dtype=object)
2237
+ assert_equal(uf(a), ())
2238
+ expected = np.array([[3, 2, 1], [5, 4], [9, 7, 8, 6]], dtype=object)
2239
+ assert_array_equal(a, expected)
2240
+
2241
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2242
+ def test_leak_in_structured_dtype_comparison(self):
2243
+ # gh-6250
2244
+ recordtype = np.dtype([('a', np.float64),
2245
+ ('b', np.int32),
2246
+ ('d', (str, 5))])
2247
+
2248
+ # Simple case
2249
+ a = np.zeros(2, dtype=recordtype)
2250
+ for i in range(100):
2251
+ a == a
2252
+ assert_(sys.getrefcount(a) < 10)
2253
+
2254
+ # The case in the bug report.
2255
+ before = sys.getrefcount(a)
2256
+ u, v = a[0], a[1]
2257
+ u == v
2258
+ del u, v
2259
+ gc.collect()
2260
+ after = sys.getrefcount(a)
2261
+ assert_equal(before, after)
2262
+
2263
+ def test_empty_percentile(self):
2264
+ # gh-6530 / gh-6553
2265
+ assert_array_equal(np.percentile(np.arange(10), []), np.array([]))
2266
+
2267
+ def test_void_compare_segfault(self):
2268
+ # gh-6922. The following should not segfault
2269
+ a = np.ones(3, dtype=[('object', 'O'), ('int', '<i2')])
2270
+ a.sort()
2271
+
2272
+ def test_reshape_size_overflow(self):
2273
+ # gh-7455
2274
+ a = np.ones(20)[::2]
2275
+ if IS_64BIT:
2276
+ # 64 bit. The following are the prime factors of 2**63 + 5,
2277
+ # plus a leading 2, so when multiplied together as int64,
2278
+ # the result overflows to a total size of 10.
2279
+ new_shape = (2, 13, 419, 691, 823, 2977518503)
2280
+ else:
2281
+ # 32 bit. The following are the prime factors of 2**31 + 5,
2282
+ # plus a leading 2, so when multiplied together as int32,
2283
+ # the result overflows to a total size of 10.
2284
+ new_shape = (2, 7, 7, 43826197)
2285
+ assert_raises(ValueError, a.reshape, new_shape)
2286
+
2287
+ @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
2288
+ reason="PyPy bug in error formatting")
2289
+ def test_invalid_structured_dtypes(self):
2290
+ # gh-2865
2291
+ # mapping python objects to other dtypes
2292
+ assert_raises(ValueError, np.dtype, ('O', [('name', 'i8')]))
2293
+ assert_raises(ValueError, np.dtype, ('i8', [('name', 'O')]))
2294
+ assert_raises(ValueError, np.dtype,
2295
+ ('i8', [('name', [('name', 'O')])]))
2296
+ assert_raises(ValueError, np.dtype, ([('a', 'i4'), ('b', 'i4')], 'O'))
2297
+ assert_raises(ValueError, np.dtype, ('i8', 'O'))
2298
+ # wrong number/type of tuple elements in dict
2299
+ assert_raises(ValueError, np.dtype,
2300
+ ('i', {'name': ('i', 0, 'title', 'oops')}))
2301
+ assert_raises(ValueError, np.dtype,
2302
+ ('i', {'name': ('i', 'wrongtype', 'title')}))
2303
+ # disallowed as of 1.13
2304
+ assert_raises(ValueError, np.dtype,
2305
+ ([('a', 'O'), ('b', 'O')], [('c', 'O'), ('d', 'O')]))
2306
+ # allowed as a special case due to existing use, see gh-2798
2307
+ a = np.ones(1, dtype=('O', [('name', 'O')]))
2308
+ assert_equal(a[0], 1)
2309
+ # In particular, the above union dtype (and union dtypes in general)
2310
+ # should mainly behave like the main (object) dtype:
2311
+ assert a[0] is a.item()
2312
+ assert type(a[0]) is int
2313
+
2314
+ def test_correct_hash_dict(self):
2315
+ # gh-8887 - __hash__ would be None despite tp_hash being set
2316
+ all_types = set(np._core.sctypeDict.values()) - {np.void}
2317
+ for t in all_types:
2318
+ val = t()
2319
+
2320
+ try:
2321
+ hash(val)
2322
+ except TypeError:
2323
+ assert_(t.__hash__ is None)
2324
+ except ValueError:
2325
+ assert_(t is np.timedelta64)
2326
+ assert_(t.__hash__ is not None)
2327
+ else:
2328
+ assert_(t.__hash__ is not None)
2329
+
2330
+ def test_scalar_copy(self):
2331
+ scalar_types = set(np._core.sctypeDict.values())
2332
+ values = {
2333
+ np.void: b"a",
2334
+ np.bytes_: b"a",
2335
+ np.str_: "a",
2336
+ np.datetime64: "2017-08-25",
2337
+ }
2338
+ for sctype in scalar_types:
2339
+ item = sctype(values.get(sctype, 1))
2340
+ item2 = copy.copy(item)
2341
+ assert_equal(item, item2)
2342
+
2343
+ def test_void_item_memview(self):
2344
+ va = np.zeros(10, 'V4')
2345
+ x = va[:1].item()
2346
+ va[0] = b'\xff\xff\xff\xff'
2347
+ del va
2348
+ assert_equal(x, b'\x00\x00\x00\x00')
2349
+
2350
+ def test_void_getitem(self):
2351
+ # Test fix for gh-11668.
2352
+ assert_(np.array([b'a'], 'V1').astype('O') == b'a')
2353
+ assert_(np.array([b'ab'], 'V2').astype('O') == b'ab')
2354
+ assert_(np.array([b'abc'], 'V3').astype('O') == b'abc')
2355
+ assert_(np.array([b'abcd'], 'V4').astype('O') == b'abcd')
2356
+
2357
+ def test_structarray_title(self):
2358
+ # The following used to segfault on pypy, due to NPY_TITLE_KEY
2359
+ # not working properly and resulting to double-decref of the
2360
+ # structured array field items:
2361
+ # See: https://bitbucket.org/pypy/pypy/issues/2789
2362
+ for j in range(5):
2363
+ structure = np.array([1], dtype=[(('x', 'X'), np.object_)])
2364
+ structure[0]['x'] = np.array([2])
2365
+ gc.collect()
2366
+
2367
+ def test_dtype_scalar_squeeze(self):
2368
+ # gh-11384
2369
+ values = {
2370
+ 'S': b"a",
2371
+ 'M': "2018-06-20",
2372
+ }
2373
+ for ch in np.typecodes['All']:
2374
+ if ch in 'O':
2375
+ continue
2376
+ sctype = np.dtype(ch).type
2377
+ scvalue = sctype(values.get(ch, 3))
2378
+ for axis in [None, ()]:
2379
+ squeezed = scvalue.squeeze(axis=axis)
2380
+ assert_equal(squeezed, scvalue)
2381
+ assert_equal(type(squeezed), type(scvalue))
2382
+
2383
+ def test_field_access_by_title(self):
2384
+ # gh-11507
2385
+ s = 'Some long field name'
2386
+ if HAS_REFCOUNT:
2387
+ base = sys.getrefcount(s)
2388
+ t = np.dtype([((s, 'f1'), np.float64)])
2389
+ data = np.zeros(10, t)
2390
+ for i in range(10):
2391
+ str(data[['f1']])
2392
+ if HAS_REFCOUNT:
2393
+ assert_(base <= sys.getrefcount(s))
2394
+
2395
+ @pytest.mark.parametrize('val', [
2396
+ # arrays and scalars
2397
+ np.ones((10, 10), dtype='int32'),
2398
+ np.uint64(10),
2399
+ ])
2400
+ @pytest.mark.parametrize('protocol',
2401
+ range(2, pickle.HIGHEST_PROTOCOL + 1)
2402
+ )
2403
+ def test_pickle_module(self, protocol, val):
2404
+ # gh-12837
2405
+ s = pickle.dumps(val, protocol)
2406
+ assert b'_multiarray_umath' not in s
2407
+ if protocol == 5 and len(val.shape) > 0:
2408
+ # unpickling ndarray goes through _frombuffer for protocol 5
2409
+ assert b'numpy._core.numeric' in s
2410
+ else:
2411
+ assert b'numpy._core.multiarray' in s
2412
+
2413
+ def test_object_casting_errors(self):
2414
+ # gh-11993 update to ValueError (see gh-16909), since strings can in
2415
+ # principle be converted to complex, but this string cannot.
2416
+ arr = np.array(['AAAAA', 18465886.0, 18465886.0], dtype=object)
2417
+ assert_raises(ValueError, arr.astype, 'c8')
2418
+
2419
+ def test_eff1d_casting(self):
2420
+ # gh-12711
2421
+ x = np.array([1, 2, 4, 7, 0], dtype=np.int16)
2422
+ res = np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
2423
+ assert_equal(res, [-99, 1, 2, 3, -7, 88, 99])
2424
+
2425
+ # The use of safe casting means, that 1<<20 is cast unsafely, an
2426
+ # error may be better, but currently there is no mechanism for it.
2427
+ res = np.ediff1d(x, to_begin=(1 << 20), to_end=(1 << 20))
2428
+ assert_equal(res, [0, 1, 2, 3, -7, 0])
2429
+
2430
+ def test_pickle_datetime64_array(self):
2431
+ # gh-12745 (would fail with pickle5 installed)
2432
+ d = np.datetime64('2015-07-04 12:59:59.50', 'ns')
2433
+ arr = np.array([d])
2434
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
2435
+ dumped = pickle.dumps(arr, protocol=proto)
2436
+ assert_equal(pickle.loads(dumped), arr)
2437
+
2438
+ def test_bad_array_interface(self):
2439
+ class T:
2440
+ __array_interface__ = {}
2441
+
2442
+ with assert_raises(ValueError):
2443
+ np.array([T()])
2444
+
2445
+ def test_2d__array__shape(self):
2446
+ class T:
2447
+ def __array__(self, dtype=None, copy=None):
2448
+ return np.ndarray(shape=(0, 0))
2449
+
2450
+ # Make sure __array__ is used instead of Sequence methods.
2451
+ def __iter__(self):
2452
+ return iter([])
2453
+
2454
+ def __getitem__(self, idx):
2455
+ raise AssertionError("__getitem__ was called")
2456
+
2457
+ def __len__(self):
2458
+ return 0
2459
+
2460
+ t = T()
2461
+ # gh-13659, would raise in broadcasting [x=t for x in result]
2462
+ arr = np.array([t])
2463
+ assert arr.shape == (1, 0, 0)
2464
+
2465
+ @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python')
2466
+ def test_to_ctypes(self):
2467
+ # gh-14214
2468
+ arr = np.zeros((2 ** 31 + 1,), 'b')
2469
+ assert arr.size * arr.itemsize > 2 ** 31
2470
+ c_arr = np.ctypeslib.as_ctypes(arr)
2471
+ assert_equal(c_arr._length_, arr.size)
2472
+
2473
+ def test_complex_conversion_error(self):
2474
+ # gh-17068
2475
+ with pytest.raises(TypeError, match=r"Unable to convert dtype.*"):
2476
+ complex(np.array("now", np.datetime64))
2477
+
2478
+ def test__array_interface__descr(self):
2479
+ # gh-17068
2480
+ dt = np.dtype({'names': ['a', 'b'],
2481
+ 'offsets': [0, 0],
2482
+ 'formats': [np.int64, np.int64]})
2483
+ descr = np.array((1, 1), dtype=dt).__array_interface__['descr']
2484
+ assert descr == [('', '|V8')] # instead of [(b'', '|V8')]
2485
+
2486
+ @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python')
2487
+ @requires_memory(free_bytes=9e9)
2488
+ def test_dot_big_stride(self):
2489
+ # gh-17111
2490
+ # blas stride = stride//itemsize > int32 max
2491
+ int32_max = np.iinfo(np.int32).max
2492
+ n = int32_max + 3
2493
+ a = np.empty([n], dtype=np.float32)
2494
+ b = a[::n - 1]
2495
+ b[...] = 1
2496
+ assert b.strides[0] > int32_max * b.dtype.itemsize
2497
+ assert np.dot(b, b) == 2.0
2498
+
2499
+ def test_frompyfunc_name(self):
2500
+ # name conversion was failing for python 3 strings
2501
+ # resulting in the default '?' name. Also test utf-8
2502
+ # encoding using non-ascii name.
2503
+ def cassé(x):
2504
+ return x
2505
+
2506
+ f = np.frompyfunc(cassé, 1, 1)
2507
+ assert str(f) == "<ufunc 'cassé (vectorized)'>"
2508
+
2509
+ @pytest.mark.parametrize("operation", [
2510
+ 'add', 'subtract', 'multiply', 'floor_divide',
2511
+ 'conjugate', 'fmod', 'square', 'reciprocal',
2512
+ 'power', 'absolute', 'negative', 'positive',
2513
+ 'greater', 'greater_equal', 'less',
2514
+ 'less_equal', 'equal', 'not_equal', 'logical_and',
2515
+ 'logical_not', 'logical_or', 'bitwise_and', 'bitwise_or',
2516
+ 'bitwise_xor', 'invert', 'left_shift', 'right_shift',
2517
+ 'gcd', 'lcm'
2518
+ ]
2519
+ )
2520
+ @pytest.mark.parametrize("order", [
2521
+ ('b->', 'B->'),
2522
+ ('h->', 'H->'),
2523
+ ('i->', 'I->'),
2524
+ ('l->', 'L->'),
2525
+ ('q->', 'Q->'),
2526
+ ]
2527
+ )
2528
+ def test_ufunc_order(self, operation, order):
2529
+ # gh-18075
2530
+ # Ensure signed types before unsigned
2531
+ def get_idx(string, str_lst):
2532
+ for i, s in enumerate(str_lst):
2533
+ if string in s:
2534
+ return i
2535
+ raise ValueError(f"{string} not in list")
2536
+ types = getattr(np, operation).types
2537
+ assert get_idx(order[0], types) < get_idx(order[1], types), (
2538
+ f"Unexpected types order of ufunc in {operation}"
2539
+ f"for {order}. Possible fix: Use signed before unsigned"
2540
+ "in generate_umath.py")
2541
+
2542
+ def test_nonbool_logical(self):
2543
+ # gh-22845
2544
+ # create two arrays with bit patterns that do not overlap.
2545
+ # needs to be large enough to test both SIMD and scalar paths
2546
+ size = 100
2547
+ a = np.frombuffer(b'\x01' * size, dtype=np.bool)
2548
+ b = np.frombuffer(b'\x80' * size, dtype=np.bool)
2549
+ expected = np.ones(size, dtype=np.bool)
2550
+ assert_array_equal(np.logical_and(a, b), expected)
2551
+
2552
+ @pytest.mark.skipif(IS_PYPY, reason="PyPy issue 2742")
2553
+ def test_gh_23737(self):
2554
+ with pytest.raises(TypeError, match="not an acceptable base type"):
2555
+ class Y(np.flexible):
2556
+ pass
2557
+
2558
+ with pytest.raises(TypeError, match="not an acceptable base type"):
2559
+ class X(np.flexible, np.ma.core.MaskedArray):
2560
+ pass
2561
+
2562
+ def test_load_ufunc_pickle(self):
2563
+ # ufuncs are pickled with a semi-private path in
2564
+ # numpy.core._multiarray_umath and must be loadable without warning
2565
+ # despite np.core being deprecated.
2566
+ test_data = b'\x80\x04\x95(\x00\x00\x00\x00\x00\x00\x00\x8c\x1cnumpy.core._multiarray_umath\x94\x8c\x03add\x94\x93\x94.'
2567
+ result = pickle.loads(test_data, encoding='bytes')
2568
+ assert result is np.add
2569
+
2570
+ def test__array_namespace__(self):
2571
+ arr = np.arange(2)
2572
+
2573
+ xp = arr.__array_namespace__()
2574
+ assert xp is np
2575
+ xp = arr.__array_namespace__(api_version="2021.12")
2576
+ assert xp is np
2577
+ xp = arr.__array_namespace__(api_version="2022.12")
2578
+ assert xp is np
2579
+ xp = arr.__array_namespace__(api_version="2023.12")
2580
+ assert xp is np
2581
+ xp = arr.__array_namespace__(api_version="2024.12")
2582
+ assert xp is np
2583
+ xp = arr.__array_namespace__(api_version=None)
2584
+ assert xp is np
2585
+
2586
+ with pytest.raises(
2587
+ ValueError,
2588
+ match="Version \"2025.12\" of the Array API Standard "
2589
+ "is not supported."
2590
+ ):
2591
+ arr.__array_namespace__(api_version="2025.12")
2592
+
2593
+ with pytest.raises(
2594
+ ValueError,
2595
+ match="Only None and strings are allowed as the Array API version"
2596
+ ):
2597
+ arr.__array_namespace__(api_version=2024)
2598
+
2599
+ def test_isin_refcnt_bug(self):
2600
+ # gh-25295
2601
+ for _ in range(1000):
2602
+ np.isclose(np.int64(2), np.int64(2), atol=1e-15, rtol=1e-300)
2603
+
2604
+ def test_replace_regression(self):
2605
+ # gh-25513 segfault
2606
+ carr = np.char.chararray((2,), itemsize=25)
2607
+ test_strings = [b' 4.52173913043478315E+00',
2608
+ b' 4.95652173913043548E+00']
2609
+ carr[:] = test_strings
2610
+ out = carr.replace(b"E", b"D")
2611
+ expected = np.char.chararray((2,), itemsize=25)
2612
+ expected[:] = [s.replace(b"E", b"D") for s in test_strings]
2613
+ assert_array_equal(out, expected)
2614
+
2615
+ def test_logspace_base_does_not_determine_dtype(self):
2616
+ # gh-24957 and cupy/cupy/issues/7946
2617
+ start = np.array([0, 2], dtype=np.float16)
2618
+ stop = np.array([2, 0], dtype=np.float16)
2619
+ out = np.logspace(start, stop, num=5, axis=1, dtype=np.float32)
2620
+ expected = np.array([[1., 3.1621094, 10., 31.625, 100.],
2621
+ [100., 31.625, 10., 3.1621094, 1.]],
2622
+ dtype=np.float32)
2623
+ assert_almost_equal(out, expected)
2624
+ # Check test fails if the calculation is done in float64, as happened
2625
+ # before when a python float base incorrectly influenced the dtype.
2626
+ out2 = np.logspace(start, stop, num=5, axis=1, dtype=np.float32,
2627
+ base=np.array([10.0]))
2628
+ with pytest.raises(AssertionError, match="not almost equal"):
2629
+ assert_almost_equal(out2, expected)
2630
+
2631
+ def test_vectorize_fixed_width_string(self):
2632
+ arr = np.array(["SOme wOrd DŽ ß ᾛ ΣΣ ffi⁵Å Ç Ⅰ"]).astype(np.str_)
2633
+ f = str.casefold
2634
+ res = np.vectorize(f, otypes=[arr.dtype])(arr)
2635
+ assert res.dtype == "U30"
2636
+
2637
+ def test_repeated_square_consistency(self):
2638
+ # gh-26940
2639
+ buf = np.array([-5.171866611150749e-07 + 2.5618634555957426e-07j,
2640
+ 0, 0, 0, 0, 0])
2641
+ # Test buffer with regular and reverse strides
2642
+ for in_vec in [buf[:3], buf[:3][::-1]]:
2643
+ expected_res = np.square(in_vec)
2644
+ # Output vector immediately follows input vector
2645
+ # to reproduce off-by-one in nomemoverlap check.
2646
+ for res in [buf[3:], buf[3:][::-1]]:
2647
+ res = buf[3:]
2648
+ np.square(in_vec, out=res)
2649
+ assert_equal(res, expected_res)
2650
+
2651
+ def test_sort_unique_crash(self):
2652
+ # gh-27037
2653
+ for _ in range(4):
2654
+ vals = np.linspace(0, 1, num=128)
2655
+ data = np.broadcast_to(vals, (128, 128, 128))
2656
+ data = data.transpose(0, 2, 1).copy()
2657
+ np.unique(data)
2658
+
2659
+ def test_sort_overlap(self):
2660
+ # gh-27273
2661
+ size = 100
2662
+ inp = np.linspace(0, size, num=size, dtype=np.intc)
2663
+ out = np.sort(inp)
2664
+ assert_equal(inp, out)
2665
+
2666
+ def test_searchsorted_structured(self):
2667
+ # gh-28190
2668
+ x = np.array([(0, 1.)], dtype=[('time', '<i8'), ('value', '<f8')])
2669
+ y = np.array((0, 0.), dtype=[('time', '<i8'), ('value', '<f8')])
2670
+ x.searchsorted(y)