numpy 2.5.2__cp315-cp315-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (942) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +108 -0
  3. numpy/__init__.cython-30.pxd +1312 -0
  4. numpy/__init__.pxd +12 -0
  5. numpy/__init__.py +926 -0
  6. numpy/__init__.pyi +7691 -0
  7. numpy/_array_api_info.py +349 -0
  8. numpy/_array_api_info.pyi +177 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +203 -0
  12. numpy/_core/__init__.pyi +666 -0
  13. numpy/_core/_add_newdocs.py +7131 -0
  14. numpy/_core/_add_newdocs.pyi +2 -0
  15. numpy/_core/_add_newdocs_scalars.py +381 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +130 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +54 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +48 -0
  25. numpy/_core/_internal.py +964 -0
  26. numpy/_core/_internal.pyi +56 -0
  27. numpy/_core/_methods.py +252 -0
  28. numpy/_core/_methods.pyi +22 -0
  29. numpy/_core/_multiarray_tests.cp315-win32.lib +0 -0
  30. numpy/_core/_multiarray_tests.cp315-win32.pyd +0 -0
  31. numpy/_core/_multiarray_umath.cp315-win32.lib +0 -0
  32. numpy/_core/_multiarray_umath.cp315-win32.pyd +0 -0
  33. numpy/_core/_operand_flag_tests.cp315-win32.lib +0 -0
  34. numpy/_core/_operand_flag_tests.cp315-win32.pyd +0 -0
  35. numpy/_core/_rational_tests.cp315-win32.lib +0 -0
  36. numpy/_core/_rational_tests.cp315-win32.pyd +0 -0
  37. numpy/_core/_simd.cp315-win32.lib +0 -0
  38. numpy/_core/_simd.cp315-win32.pyd +0 -0
  39. numpy/_core/_simd.pyi +35 -0
  40. numpy/_core/_string_helpers.py +100 -0
  41. numpy/_core/_string_helpers.pyi +12 -0
  42. numpy/_core/_struct_ufunc_tests.cp315-win32.lib +0 -0
  43. numpy/_core/_struct_ufunc_tests.cp315-win32.pyd +0 -0
  44. numpy/_core/_type_aliases.py +130 -0
  45. numpy/_core/_type_aliases.pyi +86 -0
  46. numpy/_core/_ufunc_config.py +515 -0
  47. numpy/_core/_ufunc_config.pyi +67 -0
  48. numpy/_core/_umath_tests.cp315-win32.lib +0 -0
  49. numpy/_core/_umath_tests.cp315-win32.pyd +0 -0
  50. numpy/_core/_umath_tests.pyi +51 -0
  51. numpy/_core/arrayprint.py +1788 -0
  52. numpy/_core/arrayprint.pyi +152 -0
  53. numpy/_core/cversions.py +13 -0
  54. numpy/_core/defchararray.py +1429 -0
  55. numpy/_core/defchararray.pyi +778 -0
  56. numpy/_core/einsumfunc.py +1647 -0
  57. numpy/_core/einsumfunc.pyi +179 -0
  58. numpy/_core/fromnumeric.py +4271 -0
  59. numpy/_core/fromnumeric.pyi +3144 -0
  60. numpy/_core/function_base.py +547 -0
  61. numpy/_core/function_base.pyi +444 -0
  62. numpy/_core/getlimits.py +449 -0
  63. numpy/_core/getlimits.pyi +124 -0
  64. numpy/_core/include/numpy/__multiarray_api.c +386 -0
  65. numpy/_core/include/numpy/__multiarray_api.h +1708 -0
  66. numpy/_core/include/numpy/__ufunc_api.c +56 -0
  67. numpy/_core/include/numpy/__ufunc_api.h +357 -0
  68. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  69. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  70. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  71. numpy/_core/include/numpy/arrayobject.h +7 -0
  72. numpy/_core/include/numpy/arrayscalars.h +228 -0
  73. numpy/_core/include/numpy/dtype_api.h +557 -0
  74. numpy/_core/include/numpy/halffloat.h +70 -0
  75. numpy/_core/include/numpy/ndarrayobject.h +288 -0
  76. numpy/_core/include/numpy/ndarraytypes.h +2075 -0
  77. numpy/_core/include/numpy/npy_2_compat.h +430 -0
  78. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  79. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  80. numpy/_core/include/numpy/npy_common.h +989 -0
  81. numpy/_core/include/numpy/npy_cpu.h +126 -0
  82. numpy/_core/include/numpy/npy_endian.h +79 -0
  83. numpy/_core/include/numpy/npy_math.h +602 -0
  84. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  85. numpy/_core/include/numpy/npy_os.h +42 -0
  86. numpy/_core/include/numpy/numpyconfig.h +187 -0
  87. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  88. numpy/_core/include/numpy/random/bitgen.h +20 -0
  89. numpy/_core/include/numpy/random/distributions.h +209 -0
  90. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  91. numpy/_core/include/numpy/ufuncobject.h +368 -0
  92. numpy/_core/include/numpy/utils.h +99 -0
  93. numpy/_core/lib/npymath.lib +0 -0
  94. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  95. numpy/_core/memmap.py +362 -0
  96. numpy/_core/memmap.pyi +94 -0
  97. numpy/_core/multiarray.py +1743 -0
  98. numpy/_core/multiarray.pyi +1892 -0
  99. numpy/_core/numeric.py +2707 -0
  100. numpy/_core/numeric.pyi +1366 -0
  101. numpy/_core/numerictypes.py +576 -0
  102. numpy/_core/numerictypes.pyi +196 -0
  103. numpy/_core/overrides.py +188 -0
  104. numpy/_core/overrides.pyi +44 -0
  105. numpy/_core/printoptions.py +32 -0
  106. numpy/_core/printoptions.pyi +28 -0
  107. numpy/_core/records.py +1089 -0
  108. numpy/_core/records.pyi +336 -0
  109. numpy/_core/shape_base.py +996 -0
  110. numpy/_core/shape_base.pyi +210 -0
  111. numpy/_core/strings.py +1813 -0
  112. numpy/_core/strings.pyi +481 -0
  113. numpy/_core/tests/_locales.py +72 -0
  114. numpy/_core/tests/_natype.py +144 -0
  115. numpy/_core/tests/data/astype_copy.pkl +0 -0
  116. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  117. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  118. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  119. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  123. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  125. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  127. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  128. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  129. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  131. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  132. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  133. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  135. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  136. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  137. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  138. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  139. numpy/_core/tests/examples/cython/checks.pyx +381 -0
  140. numpy/_core/tests/examples/cython/meson.build +52 -0
  141. numpy/_core/tests/examples/cython/setup.py +39 -0
  142. numpy/_core/tests/examples/limited_api/limited_api.c +455 -0
  143. numpy/_core/tests/examples/limited_api/limited_api_cython.pyx +155 -0
  144. numpy/_core/tests/examples/limited_api/meson.build +94 -0
  145. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  146. numpy/_core/tests/test__exceptions.py +90 -0
  147. numpy/_core/tests/test_abc.py +54 -0
  148. numpy/_core/tests/test_api.py +668 -0
  149. numpy/_core/tests/test_argparse.py +90 -0
  150. numpy/_core/tests/test_array_api_info.py +113 -0
  151. numpy/_core/tests/test_array_coercion.py +943 -0
  152. numpy/_core/tests/test_array_interface.py +222 -0
  153. numpy/_core/tests/test_arraymethod.py +85 -0
  154. numpy/_core/tests/test_arrayobject.py +198 -0
  155. numpy/_core/tests/test_arrayprint.py +1363 -0
  156. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  157. numpy/_core/tests/test_casting_unittests.py +970 -0
  158. numpy/_core/tests/test_conversion_utils.py +209 -0
  159. numpy/_core/tests/test_cpu_dispatcher.py +48 -0
  160. numpy/_core/tests/test_cpu_features.py +533 -0
  161. numpy/_core/tests/test_custom_dtypes.py +511 -0
  162. numpy/_core/tests/test_cython.py +377 -0
  163. numpy/_core/tests/test_datetime.py +3220 -0
  164. numpy/_core/tests/test_defchararray.py +879 -0
  165. numpy/_core/tests/test_deprecations.py +511 -0
  166. numpy/_core/tests/test_dlpack.py +262 -0
  167. numpy/_core/tests/test_dtype.py +2107 -0
  168. numpy/_core/tests/test_einsum.py +1368 -0
  169. numpy/_core/tests/test_errstate.py +131 -0
  170. numpy/_core/tests/test_extint128.py +217 -0
  171. numpy/_core/tests/test_finfo.py +86 -0
  172. numpy/_core/tests/test_function_base.py +502 -0
  173. numpy/_core/tests/test_getlimits.py +188 -0
  174. numpy/_core/tests/test_half.py +589 -0
  175. numpy/_core/tests/test_hashtable.py +156 -0
  176. numpy/_core/tests/test_indexerrors.py +122 -0
  177. numpy/_core/tests/test_indexing.py +1717 -0
  178. numpy/_core/tests/test_item_selection.py +178 -0
  179. numpy/_core/tests/test_limited_api.py +254 -0
  180. numpy/_core/tests/test_longdouble.py +370 -0
  181. numpy/_core/tests/test_mem_overlap.py +933 -0
  182. numpy/_core/tests/test_mem_policy.py +448 -0
  183. numpy/_core/tests/test_memmap.py +286 -0
  184. numpy/_core/tests/test_multiarray.py +11569 -0
  185. numpy/_core/tests/test_multiprocessing.py +55 -0
  186. numpy/_core/tests/test_multithreading.py +746 -0
  187. numpy/_core/tests/test_nditer.py +3690 -0
  188. numpy/_core/tests/test_nep50_promotions.py +287 -0
  189. numpy/_core/tests/test_numeric.py +4278 -0
  190. numpy/_core/tests/test_numerictypes.py +640 -0
  191. numpy/_core/tests/test_overrides.py +800 -0
  192. numpy/_core/tests/test_print.py +202 -0
  193. numpy/_core/tests/test_protocols.py +46 -0
  194. numpy/_core/tests/test_records.py +595 -0
  195. numpy/_core/tests/test_regression.py +2672 -0
  196. numpy/_core/tests/test_scalar_ctors.py +203 -0
  197. numpy/_core/tests/test_scalar_methods.py +327 -0
  198. numpy/_core/tests/test_scalarbuffer.py +154 -0
  199. numpy/_core/tests/test_scalarinherit.py +105 -0
  200. numpy/_core/tests/test_scalarmath.py +1167 -0
  201. numpy/_core/tests/test_scalarprint.py +403 -0
  202. numpy/_core/tests/test_shape_base.py +899 -0
  203. numpy/_core/tests/test_simd.py +1345 -0
  204. numpy/_core/tests/test_simd_module.py +105 -0
  205. numpy/_core/tests/test_stringdtype.py +2573 -0
  206. numpy/_core/tests/test_strings.py +1506 -0
  207. numpy/_core/tests/test_ufunc.py +3452 -0
  208. numpy/_core/tests/test_umath.py +5231 -0
  209. numpy/_core/tests/test_umath_accuracy.py +92 -0
  210. numpy/_core/tests/test_umath_complex.py +631 -0
  211. numpy/_core/tests/test_unicode.py +369 -0
  212. numpy/_core/umath.py +59 -0
  213. numpy/_core/umath.pyi +232 -0
  214. numpy/_distributor_init.py +15 -0
  215. numpy/_distributor_init.pyi +1 -0
  216. numpy/_expired_attrs_2_0.py +78 -0
  217. numpy/_expired_attrs_2_0.pyi +61 -0
  218. numpy/_globals.py +121 -0
  219. numpy/_globals.pyi +17 -0
  220. numpy/_pyinstaller/__init__.py +0 -0
  221. numpy/_pyinstaller/__init__.pyi +0 -0
  222. numpy/_pyinstaller/hook-numpy.py +35 -0
  223. numpy/_pyinstaller/hook-numpy.pyi +6 -0
  224. numpy/_pyinstaller/tests/__init__.py +16 -0
  225. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  226. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  227. numpy/_pytesttester.py +186 -0
  228. numpy/_pytesttester.pyi +18 -0
  229. numpy/_typing/__init__.py +147 -0
  230. numpy/_typing/_add_docstring.py +153 -0
  231. numpy/_typing/_array_like.py +92 -0
  232. numpy/_typing/_char_codes.py +156 -0
  233. numpy/_typing/_dtype_like.py +108 -0
  234. numpy/_typing/_extended_precision.py +15 -0
  235. numpy/_typing/_nbit.py +17 -0
  236. numpy/_typing/_nbit_base.py +93 -0
  237. numpy/_typing/_nbit_base.pyi +39 -0
  238. numpy/_typing/_nested_sequence.py +85 -0
  239. numpy/_typing/_scalars.py +20 -0
  240. numpy/_typing/_shape.py +8 -0
  241. numpy/_typing/_ufunc.py +7 -0
  242. numpy/_typing/_ufunc.pyi +970 -0
  243. numpy/_utils/__init__.py +95 -0
  244. numpy/_utils/__init__.pyi +25 -0
  245. numpy/_utils/_conversions.py +18 -0
  246. numpy/_utils/_conversions.pyi +4 -0
  247. numpy/_utils/_inspect.py +192 -0
  248. numpy/_utils/_inspect.pyi +67 -0
  249. numpy/_utils/_pep440.py +486 -0
  250. numpy/_utils/_pep440.pyi +121 -0
  251. numpy/char/__init__.py +31 -0
  252. numpy/char/__init__.pyi +111 -0
  253. numpy/conftest.py +249 -0
  254. numpy/core/__init__.py +33 -0
  255. numpy/core/__init__.pyi +45 -0
  256. numpy/core/_dtype.py +10 -0
  257. numpy/core/_dtype.pyi +0 -0
  258. numpy/core/_dtype_ctypes.py +10 -0
  259. numpy/core/_dtype_ctypes.pyi +0 -0
  260. numpy/core/_internal.py +27 -0
  261. numpy/core/_internal.pyi +1 -0
  262. numpy/core/_multiarray_umath.py +57 -0
  263. numpy/core/_utils.py +21 -0
  264. numpy/core/arrayprint.py +10 -0
  265. numpy/core/arrayprint.pyi +4 -0
  266. numpy/core/defchararray.py +10 -0
  267. numpy/core/defchararray.pyi +4 -0
  268. numpy/core/einsumfunc.py +10 -0
  269. numpy/core/einsumfunc.pyi +4 -0
  270. numpy/core/fromnumeric.py +10 -0
  271. numpy/core/fromnumeric.pyi +4 -0
  272. numpy/core/function_base.py +10 -0
  273. numpy/core/function_base.pyi +4 -0
  274. numpy/core/getlimits.py +10 -0
  275. numpy/core/getlimits.pyi +4 -0
  276. numpy/core/multiarray.py +25 -0
  277. numpy/core/multiarray.pyi +4 -0
  278. numpy/core/numeric.py +12 -0
  279. numpy/core/numeric.pyi +4 -0
  280. numpy/core/numerictypes.py +10 -0
  281. numpy/core/numerictypes.pyi +4 -0
  282. numpy/core/overrides.py +10 -0
  283. numpy/core/overrides.pyi +7 -0
  284. numpy/core/records.py +10 -0
  285. numpy/core/records.pyi +4 -0
  286. numpy/core/shape_base.py +10 -0
  287. numpy/core/shape_base.pyi +4 -0
  288. numpy/core/umath.py +10 -0
  289. numpy/core/umath.pyi +4 -0
  290. numpy/ctypeslib/__init__.py +13 -0
  291. numpy/ctypeslib/__init__.pyi +15 -0
  292. numpy/ctypeslib/_ctypeslib.py +603 -0
  293. numpy/ctypeslib/_ctypeslib.pyi +222 -0
  294. numpy/doc/ufuncs.py +138 -0
  295. numpy/dtypes.py +86 -0
  296. numpy/dtypes.pyi +627 -0
  297. numpy/exceptions.py +246 -0
  298. numpy/exceptions.pyi +27 -0
  299. numpy/f2py/__init__.py +80 -0
  300. numpy/f2py/__init__.pyi +5 -0
  301. numpy/f2py/__main__.py +5 -0
  302. numpy/f2py/__version__.py +1 -0
  303. numpy/f2py/__version__.pyi +1 -0
  304. numpy/f2py/_backends/__init__.py +6 -0
  305. numpy/f2py/_backends/__init__.pyi +5 -0
  306. numpy/f2py/_backends/_backend.py +44 -0
  307. numpy/f2py/_backends/_backend.pyi +46 -0
  308. numpy/f2py/_backends/_meson.py +244 -0
  309. numpy/f2py/_backends/_meson.pyi +61 -0
  310. numpy/f2py/_backends/meson.build.template +63 -0
  311. numpy/f2py/_isocbind.py +62 -0
  312. numpy/f2py/_isocbind.pyi +13 -0
  313. numpy/f2py/_src_pyf.py +247 -0
  314. numpy/f2py/_src_pyf.pyi +28 -0
  315. numpy/f2py/auxfuncs.py +1005 -0
  316. numpy/f2py/auxfuncs.pyi +259 -0
  317. numpy/f2py/capi_maps.py +811 -0
  318. numpy/f2py/capi_maps.pyi +33 -0
  319. numpy/f2py/cb_rules.py +649 -0
  320. numpy/f2py/cb_rules.pyi +17 -0
  321. numpy/f2py/cfuncs.py +1579 -0
  322. numpy/f2py/cfuncs.pyi +31 -0
  323. numpy/f2py/common_rules.py +145 -0
  324. numpy/f2py/common_rules.pyi +9 -0
  325. numpy/f2py/crackfortran.py +3727 -0
  326. numpy/f2py/crackfortran.pyi +254 -0
  327. numpy/f2py/diagnose.py +57 -0
  328. numpy/f2py/diagnose.pyi +1 -0
  329. numpy/f2py/f2py2e.py +755 -0
  330. numpy/f2py/f2py2e.pyi +69 -0
  331. numpy/f2py/f90mod_rules.py +281 -0
  332. numpy/f2py/f90mod_rules.pyi +16 -0
  333. numpy/f2py/func2subr.py +329 -0
  334. numpy/f2py/func2subr.pyi +7 -0
  335. numpy/f2py/rules.py +1641 -0
  336. numpy/f2py/rules.pyi +36 -0
  337. numpy/f2py/setup.cfg +3 -0
  338. numpy/f2py/src/fortranobject.c +1471 -0
  339. numpy/f2py/src/fortranobject.h +173 -0
  340. numpy/f2py/symbolic.py +1518 -0
  341. numpy/f2py/symbolic.pyi +220 -0
  342. numpy/f2py/tests/__init__.py +16 -0
  343. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  344. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  345. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +262 -0
  346. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  347. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  348. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  349. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  350. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  351. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  352. numpy/f2py/tests/src/callback/foo.f +62 -0
  353. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  354. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  355. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  356. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  357. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  358. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  359. numpy/f2py/tests/src/cli/hi77.f +3 -0
  360. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  361. numpy/f2py/tests/src/common/block.f +11 -0
  362. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  363. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  365. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  366. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  367. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  368. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  369. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  370. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  371. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  372. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  373. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  374. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  375. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  376. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  377. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  378. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  379. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  380. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  381. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  382. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  383. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  384. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  385. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  386. numpy/f2py/tests/src/inplace/foo.f +31 -0
  387. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  388. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  389. numpy/f2py/tests/src/mixed/foo.f +5 -0
  390. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  391. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  392. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  393. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  394. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  395. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  396. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  397. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  398. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  399. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  400. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  401. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  402. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  403. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  404. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  405. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  406. numpy/f2py/tests/src/regression/AB.inc +1 -0
  407. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  408. numpy/f2py/tests/src/regression/complex_struct_compat.f90 +8 -0
  409. numpy/f2py/tests/src/regression/complex_struct_compat.pyf +12 -0
  410. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  411. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  412. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  413. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  414. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  415. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  416. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  417. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  418. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  419. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  420. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  421. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  422. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  423. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  424. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  425. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  426. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  427. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  428. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  429. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  430. numpy/f2py/tests/src/routines/subrout.f +4 -0
  431. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  432. numpy/f2py/tests/src/size/foo.f90 +44 -0
  433. numpy/f2py/tests/src/string/char.f90 +29 -0
  434. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  435. numpy/f2py/tests/src/string/gh24008.f +8 -0
  436. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  437. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  438. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  439. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  440. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  441. numpy/f2py/tests/src/string/string.f +12 -0
  442. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  443. numpy/f2py/tests/test_abstract_interface.py +26 -0
  444. numpy/f2py/tests/test_array_from_pyobj.py +732 -0
  445. numpy/f2py/tests/test_assumed_shape.py +52 -0
  446. numpy/f2py/tests/test_block_docstring.py +16 -0
  447. numpy/f2py/tests/test_callback.py +262 -0
  448. numpy/f2py/tests/test_capi_maps.py +10 -0
  449. numpy/f2py/tests/test_character.py +644 -0
  450. numpy/f2py/tests/test_common.py +24 -0
  451. numpy/f2py/tests/test_crackfortran.py +427 -0
  452. numpy/f2py/tests/test_data.py +74 -0
  453. numpy/f2py/tests/test_docs.py +66 -0
  454. numpy/f2py/tests/test_f2cmap.py +20 -0
  455. numpy/f2py/tests/test_f2py2e.py +1006 -0
  456. numpy/f2py/tests/test_inplace.py +49 -0
  457. numpy/f2py/tests/test_isoc.py +56 -0
  458. numpy/f2py/tests/test_kind.py +53 -0
  459. numpy/f2py/tests/test_mixed.py +31 -0
  460. numpy/f2py/tests/test_modules.py +87 -0
  461. numpy/f2py/tests/test_parameter.py +121 -0
  462. numpy/f2py/tests/test_pyf_src.py +43 -0
  463. numpy/f2py/tests/test_quoted_character.py +19 -0
  464. numpy/f2py/tests/test_regression.py +202 -0
  465. numpy/f2py/tests/test_return_character.py +48 -0
  466. numpy/f2py/tests/test_return_complex.py +67 -0
  467. numpy/f2py/tests/test_return_integer.py +55 -0
  468. numpy/f2py/tests/test_return_logical.py +66 -0
  469. numpy/f2py/tests/test_return_real.py +109 -0
  470. numpy/f2py/tests/test_routines.py +29 -0
  471. numpy/f2py/tests/test_semicolon_split.py +76 -0
  472. numpy/f2py/tests/test_size.py +42 -0
  473. numpy/f2py/tests/test_string.py +102 -0
  474. numpy/f2py/tests/test_symbolic.py +501 -0
  475. numpy/f2py/tests/test_value_attrspec.py +15 -0
  476. numpy/f2py/tests/util.py +442 -0
  477. numpy/f2py/use_rules.py +100 -0
  478. numpy/f2py/use_rules.pyi +9 -0
  479. numpy/fft/__init__.py +213 -0
  480. numpy/fft/__init__.pyi +38 -0
  481. numpy/fft/_helper.py +235 -0
  482. numpy/fft/_helper.pyi +145 -0
  483. numpy/fft/_pocketfft.py +1693 -0
  484. numpy/fft/_pocketfft.pyi +1131 -0
  485. numpy/fft/_pocketfft_umath.cp315-win32.lib +0 -0
  486. numpy/fft/_pocketfft_umath.cp315-win32.pyd +0 -0
  487. numpy/fft/tests/__init__.py +0 -0
  488. numpy/fft/tests/test_helper.py +167 -0
  489. numpy/fft/tests/test_pocketfft.py +609 -0
  490. numpy/lib/__init__.py +90 -0
  491. numpy/lib/__init__.pyi +52 -0
  492. numpy/lib/_array_utils_impl.py +62 -0
  493. numpy/lib/_array_utils_impl.pyi +10 -0
  494. numpy/lib/_arraypad_impl.py +926 -0
  495. numpy/lib/_arraypad_impl.pyi +99 -0
  496. numpy/lib/_arraysetops_impl.py +1158 -0
  497. numpy/lib/_arraysetops_impl.pyi +460 -0
  498. numpy/lib/_arrayterator_impl.py +224 -0
  499. numpy/lib/_arrayterator_impl.pyi +45 -0
  500. numpy/lib/_datasource.py +700 -0
  501. numpy/lib/_datasource.pyi +30 -0
  502. numpy/lib/_format_impl.py +1038 -0
  503. numpy/lib/_format_impl.pyi +56 -0
  504. numpy/lib/_function_base_impl.py +5775 -0
  505. numpy/lib/_function_base_impl.pyi +2315 -0
  506. numpy/lib/_histograms_impl.py +1085 -0
  507. numpy/lib/_histograms_impl.pyi +273 -0
  508. numpy/lib/_index_tricks_impl.py +1048 -0
  509. numpy/lib/_index_tricks_impl.pyi +350 -0
  510. numpy/lib/_iotools.py +900 -0
  511. numpy/lib/_iotools.pyi +113 -0
  512. numpy/lib/_nanfunctions_impl.py +2006 -0
  513. numpy/lib/_nanfunctions_impl.pyi +48 -0
  514. numpy/lib/_npyio_impl.py +2491 -0
  515. numpy/lib/_npyio_impl.pyi +288 -0
  516. numpy/lib/_polynomial_impl.py +1467 -0
  517. numpy/lib/_polynomial_impl.pyi +435 -0
  518. numpy/lib/_scimath_impl.py +642 -0
  519. numpy/lib/_scimath_impl.pyi +93 -0
  520. numpy/lib/_shape_base_impl.py +1247 -0
  521. numpy/lib/_shape_base_impl.pyi +256 -0
  522. numpy/lib/_stride_tricks_impl.py +656 -0
  523. numpy/lib/_stride_tricks_impl.pyi +75 -0
  524. numpy/lib/_twodim_base_impl.py +1242 -0
  525. numpy/lib/_twodim_base_impl.pyi +397 -0
  526. numpy/lib/_type_check_impl.py +714 -0
  527. numpy/lib/_type_check_impl.pyi +450 -0
  528. numpy/lib/_ufunclike_impl.py +212 -0
  529. numpy/lib/_ufunclike_impl.pyi +41 -0
  530. numpy/lib/_user_array_impl.py +310 -0
  531. numpy/lib/_user_array_impl.pyi +229 -0
  532. numpy/lib/_utils_impl.py +541 -0
  533. numpy/lib/_utils_impl.pyi +18 -0
  534. numpy/lib/_version.py +153 -0
  535. numpy/lib/_version.pyi +22 -0
  536. numpy/lib/array_utils.py +7 -0
  537. numpy/lib/array_utils.pyi +6 -0
  538. numpy/lib/format.py +24 -0
  539. numpy/lib/format.pyi +24 -0
  540. numpy/lib/introspect.py +94 -0
  541. numpy/lib/introspect.pyi +3 -0
  542. numpy/lib/mixins.py +180 -0
  543. numpy/lib/mixins.pyi +78 -0
  544. numpy/lib/npyio.py +1 -0
  545. numpy/lib/npyio.pyi +5 -0
  546. numpy/lib/recfunctions.py +1681 -0
  547. numpy/lib/recfunctions.pyi +436 -0
  548. numpy/lib/scimath.py +13 -0
  549. numpy/lib/scimath.pyi +12 -0
  550. numpy/lib/stride_tricks.py +1 -0
  551. numpy/lib/stride_tricks.pyi +4 -0
  552. numpy/lib/tests/__init__.py +0 -0
  553. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  554. numpy/lib/tests/data/py2-objarr.npy +0 -0
  555. numpy/lib/tests/data/py2-objarr.npz +0 -0
  556. numpy/lib/tests/data/py3-objarr.npy +0 -0
  557. numpy/lib/tests/data/py3-objarr.npz +0 -0
  558. numpy/lib/tests/data/python3.npy +0 -0
  559. numpy/lib/tests/data/win64python2.npy +0 -0
  560. numpy/lib/tests/test__datasource.py +328 -0
  561. numpy/lib/tests/test__iotools.py +358 -0
  562. numpy/lib/tests/test__version.py +64 -0
  563. numpy/lib/tests/test_array_utils.py +32 -0
  564. numpy/lib/tests/test_arraypad.py +1427 -0
  565. numpy/lib/tests/test_arraysetops.py +1304 -0
  566. numpy/lib/tests/test_arrayterator.py +45 -0
  567. numpy/lib/tests/test_format.py +1043 -0
  568. numpy/lib/tests/test_function_base.py +4787 -0
  569. numpy/lib/tests/test_histograms.py +855 -0
  570. numpy/lib/tests/test_index_tricks.py +703 -0
  571. numpy/lib/tests/test_io.py +2733 -0
  572. numpy/lib/tests/test_loadtxt.py +1077 -0
  573. numpy/lib/tests/test_mixins.py +215 -0
  574. numpy/lib/tests/test_nanfunctions.py +1449 -0
  575. numpy/lib/tests/test_packbits.py +374 -0
  576. numpy/lib/tests/test_polynomial.py +333 -0
  577. numpy/lib/tests/test_recfunctions.py +1042 -0
  578. numpy/lib/tests/test_regression.py +231 -0
  579. numpy/lib/tests/test_shape_base.py +813 -0
  580. numpy/lib/tests/test_stride_tricks.py +890 -0
  581. numpy/lib/tests/test_twodim_base.py +564 -0
  582. numpy/lib/tests/test_type_check.py +473 -0
  583. numpy/lib/tests/test_ufunclike.py +121 -0
  584. numpy/lib/tests/test_utils.py +80 -0
  585. numpy/lib/user_array.py +1 -0
  586. numpy/lib/user_array.pyi +1 -0
  587. numpy/linalg/__init__.py +95 -0
  588. numpy/linalg/__init__.pyi +71 -0
  589. numpy/linalg/_linalg.py +3649 -0
  590. numpy/linalg/_linalg.pyi +1230 -0
  591. numpy/linalg/_umath_linalg.cp315-win32.lib +0 -0
  592. numpy/linalg/_umath_linalg.cp315-win32.pyd +0 -0
  593. numpy/linalg/_umath_linalg.pyi +60 -0
  594. numpy/linalg/lapack_lite.cp315-win32.lib +0 -0
  595. numpy/linalg/lapack_lite.cp315-win32.pyd +0 -0
  596. numpy/linalg/lapack_lite.pyi +143 -0
  597. numpy/linalg/tests/__init__.py +0 -0
  598. numpy/linalg/tests/test_deprecations.py +21 -0
  599. numpy/linalg/tests/test_linalg.py +2492 -0
  600. numpy/linalg/tests/test_regression.py +191 -0
  601. numpy/ma/API_CHANGES.txt +135 -0
  602. numpy/ma/LICENSE +24 -0
  603. numpy/ma/README.rst +236 -0
  604. numpy/ma/__init__.py +53 -0
  605. numpy/ma/__init__.pyi +458 -0
  606. numpy/ma/core.py +9000 -0
  607. numpy/ma/core.pyi +4767 -0
  608. numpy/ma/extras.py +2266 -0
  609. numpy/ma/extras.pyi +770 -0
  610. numpy/ma/mrecords.py +739 -0
  611. numpy/ma/mrecords.pyi +313 -0
  612. numpy/ma/tests/__init__.py +0 -0
  613. numpy/ma/tests/test_arrayobject.py +40 -0
  614. numpy/ma/tests/test_core.py +6112 -0
  615. numpy/ma/tests/test_deprecations.py +73 -0
  616. numpy/ma/tests/test_extras.py +1945 -0
  617. numpy/ma/tests/test_mrecords.py +495 -0
  618. numpy/ma/tests/test_old_ma.py +939 -0
  619. numpy/ma/tests/test_regression.py +83 -0
  620. numpy/ma/tests/test_subclassing.py +469 -0
  621. numpy/ma/testutils.py +294 -0
  622. numpy/ma/testutils.pyi +69 -0
  623. numpy/matlib.py +380 -0
  624. numpy/matlib.pyi +580 -0
  625. numpy/matrixlib/__init__.py +12 -0
  626. numpy/matrixlib/__init__.pyi +3 -0
  627. numpy/matrixlib/defmatrix.py +1117 -0
  628. numpy/matrixlib/defmatrix.pyi +211 -0
  629. numpy/matrixlib/tests/__init__.py +0 -0
  630. numpy/matrixlib/tests/test_defmatrix.py +475 -0
  631. numpy/matrixlib/tests/test_interaction.py +360 -0
  632. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  633. numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
  634. numpy/matrixlib/tests/test_multiarray.py +17 -0
  635. numpy/matrixlib/tests/test_numeric.py +18 -0
  636. numpy/matrixlib/tests/test_regression.py +31 -0
  637. numpy/polynomial/__init__.py +187 -0
  638. numpy/polynomial/__init__.pyi +31 -0
  639. numpy/polynomial/_polybase.py +1191 -0
  640. numpy/polynomial/_polybase.pyi +255 -0
  641. numpy/polynomial/_polytypes.pyi +536 -0
  642. numpy/polynomial/chebyshev.py +2053 -0
  643. numpy/polynomial/chebyshev.pyi +173 -0
  644. numpy/polynomial/hermite.py +1794 -0
  645. numpy/polynomial/hermite.pyi +110 -0
  646. numpy/polynomial/hermite_e.py +1692 -0
  647. numpy/polynomial/hermite_e.pyi +110 -0
  648. numpy/polynomial/laguerre.py +1729 -0
  649. numpy/polynomial/laguerre.pyi +103 -0
  650. numpy/polynomial/legendre.py +1655 -0
  651. numpy/polynomial/legendre.pyi +103 -0
  652. numpy/polynomial/polynomial.py +1683 -0
  653. numpy/polynomial/polynomial.pyi +112 -0
  654. numpy/polynomial/polyutils.py +759 -0
  655. numpy/polynomial/polyutils.pyi +295 -0
  656. numpy/polynomial/tests/__init__.py +0 -0
  657. numpy/polynomial/tests/test_chebyshev.py +639 -0
  658. numpy/polynomial/tests/test_classes.py +625 -0
  659. numpy/polynomial/tests/test_hermite.py +574 -0
  660. numpy/polynomial/tests/test_hermite_e.py +575 -0
  661. numpy/polynomial/tests/test_laguerre.py +556 -0
  662. numpy/polynomial/tests/test_legendre.py +587 -0
  663. numpy/polynomial/tests/test_polynomial.py +713 -0
  664. numpy/polynomial/tests/test_polyutils.py +123 -0
  665. numpy/polynomial/tests/test_printing.py +562 -0
  666. numpy/polynomial/tests/test_symbol.py +217 -0
  667. numpy/py.typed +0 -0
  668. numpy/random/LICENSE.md +71 -0
  669. numpy/random/__init__.pxd +14 -0
  670. numpy/random/__init__.py +213 -0
  671. numpy/random/__init__.pyi +124 -0
  672. numpy/random/_bounded_integers.cp315-win32.lib +0 -0
  673. numpy/random/_bounded_integers.cp315-win32.pyd +0 -0
  674. numpy/random/_bounded_integers.pxd +38 -0
  675. numpy/random/_bounded_integers.pyi +1 -0
  676. numpy/random/_common.cp315-win32.lib +0 -0
  677. numpy/random/_common.cp315-win32.pyd +0 -0
  678. numpy/random/_common.pxd +110 -0
  679. numpy/random/_common.pyi +17 -0
  680. numpy/random/_examples/cffi/extending.py +44 -0
  681. numpy/random/_examples/cffi/parse.py +53 -0
  682. numpy/random/_examples/cython/extending.pyx +77 -0
  683. numpy/random/_examples/cython/extending_distributions.pyx +117 -0
  684. numpy/random/_examples/cython/meson.build +53 -0
  685. numpy/random/_examples/numba/extending.py +86 -0
  686. numpy/random/_examples/numba/extending_distributions.py +67 -0
  687. numpy/random/_generator.cp315-win32.lib +0 -0
  688. numpy/random/_generator.cp315-win32.pyd +0 -0
  689. numpy/random/_generator.pyi +769 -0
  690. numpy/random/_mt19937.cp315-win32.lib +0 -0
  691. numpy/random/_mt19937.cp315-win32.pyd +0 -0
  692. numpy/random/_mt19937.pyi +27 -0
  693. numpy/random/_pcg64.cp315-win32.lib +0 -0
  694. numpy/random/_pcg64.cp315-win32.pyd +0 -0
  695. numpy/random/_pcg64.pyi +36 -0
  696. numpy/random/_philox.cp315-win32.lib +0 -0
  697. numpy/random/_philox.cp315-win32.pyd +0 -0
  698. numpy/random/_philox.pyi +36 -0
  699. numpy/random/_pickle.py +88 -0
  700. numpy/random/_pickle.pyi +43 -0
  701. numpy/random/_sfc64.cp315-win32.lib +0 -0
  702. numpy/random/_sfc64.cp315-win32.pyd +0 -0
  703. numpy/random/_sfc64.pyi +25 -0
  704. numpy/random/bit_generator.cp315-win32.lib +0 -0
  705. numpy/random/bit_generator.cp315-win32.pyd +0 -0
  706. numpy/random/bit_generator.pxd +35 -0
  707. numpy/random/bit_generator.pyi +122 -0
  708. numpy/random/c_distributions.pxd +119 -0
  709. numpy/random/lib/npyrandom.lib +0 -0
  710. numpy/random/mtrand.cp315-win32.lib +0 -0
  711. numpy/random/mtrand.cp315-win32.pyd +0 -0
  712. numpy/random/mtrand.pyi +996 -0
  713. numpy/random/tests/__init__.py +0 -0
  714. numpy/random/tests/data/__init__.py +0 -0
  715. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  716. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  717. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  718. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  719. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  720. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  721. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  722. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  723. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  724. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  725. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  726. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  727. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  728. numpy/random/tests/test_direct.py +620 -0
  729. numpy/random/tests/test_extending.py +129 -0
  730. numpy/random/tests/test_generator_mt19937.py +2830 -0
  731. numpy/random/tests/test_generator_mt19937_regressions.py +240 -0
  732. numpy/random/tests/test_random.py +1723 -0
  733. numpy/random/tests/test_randomstate.py +2107 -0
  734. numpy/random/tests/test_randomstate_regression.py +249 -0
  735. numpy/random/tests/test_regression.py +174 -0
  736. numpy/random/tests/test_seed_sequence.py +103 -0
  737. numpy/random/tests/test_smoke.py +882 -0
  738. numpy/rec/__init__.py +2 -0
  739. numpy/rec/__init__.pyi +23 -0
  740. numpy/strings/__init__.py +2 -0
  741. numpy/strings/__init__.pyi +97 -0
  742. numpy/testing/__init__.py +22 -0
  743. numpy/testing/__init__.pyi +107 -0
  744. numpy/testing/_private/__init__.py +0 -0
  745. numpy/testing/_private/__init__.pyi +0 -0
  746. numpy/testing/_private/extbuild.py +247 -0
  747. numpy/testing/_private/extbuild.pyi +25 -0
  748. numpy/testing/_private/utils.py +2899 -0
  749. numpy/testing/_private/utils.pyi +501 -0
  750. numpy/testing/overrides.py +84 -0
  751. numpy/testing/overrides.pyi +10 -0
  752. numpy/testing/print_coercion_tables.py +207 -0
  753. numpy/testing/print_coercion_tables.pyi +26 -0
  754. numpy/testing/tests/__init__.py +0 -0
  755. numpy/testing/tests/test_utils.py +2147 -0
  756. numpy/tests/__init__.py +0 -0
  757. numpy/tests/test__all__.py +10 -0
  758. numpy/tests/test_configtool.py +51 -0
  759. numpy/tests/test_ctypeslib.py +406 -0
  760. numpy/tests/test_lazyloading.py +35 -0
  761. numpy/tests/test_matlib.py +59 -0
  762. numpy/tests/test_numpy_config.py +47 -0
  763. numpy/tests/test_numpy_version.py +54 -0
  764. numpy/tests/test_public_api.py +723 -0
  765. numpy/tests/test_reloading.py +69 -0
  766. numpy/tests/test_scripts.py +45 -0
  767. numpy/tests/test_warnings.py +81 -0
  768. numpy/typing/__init__.py +225 -0
  769. numpy/typing/__init__.pyi +8 -0
  770. numpy/typing/mypy_plugin.py +200 -0
  771. numpy/typing/tests/__init__.py +0 -0
  772. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  773. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  774. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  775. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  776. numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
  777. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  778. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  779. numpy/typing/tests/data/fail/char.pyi +60 -0
  780. numpy/typing/tests/data/fail/chararray.pyi +61 -0
  781. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  782. numpy/typing/tests/data/fail/constants.pyi +3 -0
  783. numpy/typing/tests/data/fail/datasource.pyi +16 -0
  784. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  785. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  786. numpy/typing/tests/data/fail/flatiter.pyi +38 -0
  787. numpy/typing/tests/data/fail/fromnumeric.pyi +149 -0
  788. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  789. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  790. numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
  791. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  792. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  793. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  794. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  795. numpy/typing/tests/data/fail/ma.pyi +152 -0
  796. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  797. numpy/typing/tests/data/fail/modules.pyi +17 -0
  798. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  799. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  800. numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
  801. numpy/typing/tests/data/fail/nditer.pyi +7 -0
  802. numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
  803. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  804. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  805. numpy/typing/tests/data/fail/random.pyi +62 -0
  806. numpy/typing/tests/data/fail/rec.pyi +17 -0
  807. numpy/typing/tests/data/fail/scalars.pyi +86 -0
  808. numpy/typing/tests/data/fail/shape.pyi +7 -0
  809. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  810. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  811. numpy/typing/tests/data/fail/strings.pyi +41 -0
  812. numpy/typing/tests/data/fail/testing.pyi +28 -0
  813. numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
  814. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  815. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  816. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  817. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  818. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  819. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  820. numpy/typing/tests/data/mypy.ini +8 -0
  821. numpy/typing/tests/data/pass/arithmetic.py +614 -0
  822. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  823. numpy/typing/tests/data/pass/array_like.py +37 -0
  824. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  825. numpy/typing/tests/data/pass/arrayterator.py +28 -0
  826. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  827. numpy/typing/tests/data/pass/comparisons.py +316 -0
  828. numpy/typing/tests/data/pass/dtype.py +57 -0
  829. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  830. numpy/typing/tests/data/pass/flatiter.py +26 -0
  831. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  832. numpy/typing/tests/data/pass/index_tricks.py +62 -0
  833. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  834. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  835. numpy/typing/tests/data/pass/lib_version.py +18 -0
  836. numpy/typing/tests/data/pass/literal.py +52 -0
  837. numpy/typing/tests/data/pass/ma.py +199 -0
  838. numpy/typing/tests/data/pass/mod.py +149 -0
  839. numpy/typing/tests/data/pass/modules.py +45 -0
  840. numpy/typing/tests/data/pass/multiarray.py +77 -0
  841. numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
  842. numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
  843. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  844. numpy/typing/tests/data/pass/nditer.py +4 -0
  845. numpy/typing/tests/data/pass/numeric.py +90 -0
  846. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  847. numpy/typing/tests/data/pass/random.py +1498 -0
  848. numpy/typing/tests/data/pass/recfunctions.py +164 -0
  849. numpy/typing/tests/data/pass/scalars.py +262 -0
  850. numpy/typing/tests/data/pass/shape.py +19 -0
  851. numpy/typing/tests/data/pass/simple.py +170 -0
  852. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  853. numpy/typing/tests/data/pass/ufunclike.py +52 -0
  854. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  855. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  856. numpy/typing/tests/data/reveal/arithmetic.pyi +726 -0
  857. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  858. numpy/typing/tests/data/reveal/array_constructors.pyi +331 -0
  859. numpy/typing/tests/data/reveal/arraypad.pyi +32 -0
  860. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  861. numpy/typing/tests/data/reveal/arraysetops.pyi +80 -0
  862. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  863. numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
  864. numpy/typing/tests/data/reveal/char.pyi +228 -0
  865. numpy/typing/tests/data/reveal/chararray.pyi +138 -0
  866. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  867. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  868. numpy/typing/tests/data/reveal/ctypeslib.pyi +86 -0
  869. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  870. numpy/typing/tests/data/reveal/dtype.pyi +166 -0
  871. numpy/typing/tests/data/reveal/einsumfunc.pyi +46 -0
  872. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  873. numpy/typing/tests/data/reveal/fft.pyi +189 -0
  874. numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
  875. numpy/typing/tests/data/reveal/fromnumeric.pyi +574 -0
  876. numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
  877. numpy/typing/tests/data/reveal/histograms.pyi +69 -0
  878. numpy/typing/tests/data/reveal/index_tricks.pyi +148 -0
  879. numpy/typing/tests/data/reveal/lib_function_base.pyi +413 -0
  880. numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
  881. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  882. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  883. numpy/typing/tests/data/reveal/linalg.pyi +517 -0
  884. numpy/typing/tests/data/reveal/ma.pyi +1103 -0
  885. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  886. numpy/typing/tests/data/reveal/memmap.pyi +21 -0
  887. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  888. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  889. numpy/typing/tests/data/reveal/multiarray.pyi +336 -0
  890. numpy/typing/tests/data/reveal/nbit_base_example.pyi +17 -0
  891. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +79 -0
  892. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
  893. numpy/typing/tests/data/reveal/ndarray_misc.pyi +428 -0
  894. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
  895. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  896. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  897. numpy/typing/tests/data/reveal/npyio.pyi +85 -0
  898. numpy/typing/tests/data/reveal/numeric.pyi +176 -0
  899. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  900. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +216 -0
  901. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
  902. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  903. numpy/typing/tests/data/reveal/random.pyi +1357 -0
  904. numpy/typing/tests/data/reveal/rec.pyi +177 -0
  905. numpy/typing/tests/data/reveal/scalars.pyi +288 -0
  906. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  907. numpy/typing/tests/data/reveal/shape_base.pyi +84 -0
  908. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  909. numpy/typing/tests/data/reveal/strings.pyi +198 -0
  910. numpy/typing/tests/data/reveal/testing.pyi +196 -0
  911. numpy/typing/tests/data/reveal/twodim_base.pyi +231 -0
  912. numpy/typing/tests/data/reveal/type_check.pyi +94 -0
  913. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  914. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  915. numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
  916. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  917. numpy/typing/tests/test_isfile.py +35 -0
  918. numpy/typing/tests/test_runtime.py +103 -0
  919. numpy/typing/tests/test_typing.py +207 -0
  920. numpy/version.py +11 -0
  921. numpy/version.pyi +9 -0
  922. numpy-2.5.2.dist-info/METADATA +139 -0
  923. numpy-2.5.2.dist-info/RECORD +942 -0
  924. numpy-2.5.2.dist-info/WHEEL +4 -0
  925. numpy-2.5.2.dist-info/entry_points.txt +13 -0
  926. numpy-2.5.2.dist-info/licenses/LICENSE.txt +914 -0
  927. numpy-2.5.2.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
  928. numpy-2.5.2.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
  929. numpy-2.5.2.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
  930. numpy-2.5.2.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
  931. numpy-2.5.2.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
  932. numpy-2.5.2.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
  933. numpy-2.5.2.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
  934. numpy-2.5.2.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
  935. numpy-2.5.2.dist-info/licenses/numpy/ma/LICENSE +24 -0
  936. numpy-2.5.2.dist-info/licenses/numpy/random/LICENSE.md +71 -0
  937. numpy-2.5.2.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
  938. numpy-2.5.2.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
  939. numpy-2.5.2.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
  940. numpy-2.5.2.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
  941. numpy-2.5.2.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
  942. numpy-2.5.2.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
@@ -0,0 +1,3690 @@
1
+ import inspect
2
+ import subprocess
3
+ import sys
4
+ import textwrap
5
+ import warnings
6
+
7
+ import pytest
8
+
9
+ import numpy as np
10
+ import numpy._core._multiarray_tests as _multiarray_tests
11
+ import numpy._core.umath as ncu
12
+ from numpy import all, arange, array, nditer
13
+ from numpy.testing import (
14
+ HAS_REFCOUNT,
15
+ IS_64BIT,
16
+ IS_WASM,
17
+ assert_,
18
+ assert_array_equal,
19
+ assert_equal,
20
+ assert_raises,
21
+ )
22
+ from numpy.testing._private.utils import requires_memory
23
+
24
+
25
+ def iter_multi_index(i):
26
+ ret = []
27
+ while not i.finished:
28
+ ret.append(i.multi_index)
29
+ i.iternext()
30
+ return ret
31
+
32
+ def iter_indices(i):
33
+ ret = []
34
+ while not i.finished:
35
+ ret.append(i.index)
36
+ i.iternext()
37
+ return ret
38
+
39
+ def iter_iterindices(i):
40
+ ret = []
41
+ while not i.finished:
42
+ ret.append(i.iterindex)
43
+ i.iternext()
44
+ return ret
45
+
46
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
47
+ def test_iter_refcount():
48
+ # Make sure the iterator doesn't leak
49
+
50
+ # Basic
51
+ a = arange(6)
52
+ dt = np.dtype('f4').newbyteorder()
53
+ rc_a = sys.getrefcount(a)
54
+ rc_dt = sys.getrefcount(dt)
55
+ with nditer(a, [],
56
+ [['readwrite', 'updateifcopy']],
57
+ casting='unsafe',
58
+ op_dtypes=[dt]) as it:
59
+ assert_(not it.iterationneedsapi)
60
+ assert_(sys.getrefcount(a) > rc_a)
61
+ assert_(sys.getrefcount(dt) > rc_dt)
62
+ # del 'it'
63
+ it = None
64
+ assert_equal(sys.getrefcount(a), rc_a)
65
+ assert_equal(sys.getrefcount(dt), rc_dt)
66
+
67
+ # With a copy
68
+ a = arange(6, dtype='f4')
69
+ dt = np.dtype('f4')
70
+ rc_a = sys.getrefcount(a)
71
+ rc_dt = sys.getrefcount(dt)
72
+ it = nditer(a, [],
73
+ [['readwrite']],
74
+ op_dtypes=[dt])
75
+ rc2_a = sys.getrefcount(a)
76
+ rc2_dt = sys.getrefcount(dt)
77
+ it2 = it.copy()
78
+ assert_(sys.getrefcount(a) > rc2_a)
79
+ if sys.version_info < (3, 13):
80
+ # np.dtype('f4') is immortal after Python 3.13
81
+ assert_(sys.getrefcount(dt) > rc2_dt)
82
+ it = None
83
+ assert_equal(sys.getrefcount(a), rc2_a)
84
+ assert_equal(sys.getrefcount(dt), rc2_dt)
85
+ it2 = None
86
+ assert_equal(sys.getrefcount(a), rc_a)
87
+ assert_equal(sys.getrefcount(dt), rc_dt)
88
+
89
+ def test_iter_best_order():
90
+ # The iterator should always find the iteration order
91
+ # with increasing memory addresses
92
+
93
+ # Test the ordering for 1-D to 5-D shapes
94
+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
95
+ a = arange(np.prod(shape))
96
+ # Test each combination of positive and negative strides
97
+ for dirs in range(2**len(shape)):
98
+ dirs_index = [slice(None)] * len(shape)
99
+ for bit in range(len(shape)):
100
+ if ((2**bit) & dirs):
101
+ dirs_index[bit] = slice(None, None, -1)
102
+ dirs_index = tuple(dirs_index)
103
+
104
+ aview = a.reshape(shape)[dirs_index]
105
+ # C-order
106
+ i = nditer(aview, [], [['readonly']])
107
+ assert_equal(list(i), a)
108
+ # Fortran-order
109
+ i = nditer(aview.T, [], [['readonly']])
110
+ assert_equal(list(i), a)
111
+ # Other order
112
+ if len(shape) > 2:
113
+ i = nditer(aview.swapaxes(0, 1), [], [['readonly']])
114
+ assert_equal(list(i), a)
115
+
116
+ def test_iter_c_order():
117
+ # Test forcing C order
118
+
119
+ # Test the ordering for 1-D to 5-D shapes
120
+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
121
+ a = arange(np.prod(shape))
122
+ # Test each combination of positive and negative strides
123
+ for dirs in range(2**len(shape)):
124
+ dirs_index = [slice(None)] * len(shape)
125
+ for bit in range(len(shape)):
126
+ if ((2**bit) & dirs):
127
+ dirs_index[bit] = slice(None, None, -1)
128
+ dirs_index = tuple(dirs_index)
129
+
130
+ aview = a.reshape(shape)[dirs_index]
131
+ # C-order
132
+ i = nditer(aview, order='C')
133
+ assert_equal(list(i), aview.ravel(order='C'))
134
+ # Fortran-order
135
+ i = nditer(aview.T, order='C')
136
+ assert_equal(list(i), aview.T.ravel(order='C'))
137
+ # Other order
138
+ if len(shape) > 2:
139
+ i = nditer(aview.swapaxes(0, 1), order='C')
140
+ assert_equal(list(i),
141
+ aview.swapaxes(0, 1).ravel(order='C'))
142
+
143
+ def test_iter_f_order():
144
+ # Test forcing F order
145
+
146
+ # Test the ordering for 1-D to 5-D shapes
147
+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
148
+ a = arange(np.prod(shape))
149
+ # Test each combination of positive and negative strides
150
+ for dirs in range(2**len(shape)):
151
+ dirs_index = [slice(None)] * len(shape)
152
+ for bit in range(len(shape)):
153
+ if ((2**bit) & dirs):
154
+ dirs_index[bit] = slice(None, None, -1)
155
+ dirs_index = tuple(dirs_index)
156
+
157
+ aview = a.reshape(shape)[dirs_index]
158
+ # C-order
159
+ i = nditer(aview, order='F')
160
+ assert_equal(list(i), aview.ravel(order='F'))
161
+ # Fortran-order
162
+ i = nditer(aview.T, order='F')
163
+ assert_equal(list(i), aview.T.ravel(order='F'))
164
+ # Other order
165
+ if len(shape) > 2:
166
+ i = nditer(aview.swapaxes(0, 1), order='F')
167
+ assert_equal(list(i),
168
+ aview.swapaxes(0, 1).ravel(order='F'))
169
+
170
+ def test_iter_c_or_f_order():
171
+ # Test forcing any contiguous (C or F) order
172
+
173
+ # Test the ordering for 1-D to 5-D shapes
174
+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
175
+ a = arange(np.prod(shape))
176
+ # Test each combination of positive and negative strides
177
+ for dirs in range(2**len(shape)):
178
+ dirs_index = [slice(None)] * len(shape)
179
+ for bit in range(len(shape)):
180
+ if ((2**bit) & dirs):
181
+ dirs_index[bit] = slice(None, None, -1)
182
+ dirs_index = tuple(dirs_index)
183
+
184
+ aview = a.reshape(shape)[dirs_index]
185
+ # C-order
186
+ i = nditer(aview, order='A')
187
+ assert_equal(list(i), aview.ravel(order='A'))
188
+ # Fortran-order
189
+ i = nditer(aview.T, order='A')
190
+ assert_equal(list(i), aview.T.ravel(order='A'))
191
+ # Other order
192
+ if len(shape) > 2:
193
+ i = nditer(aview.swapaxes(0, 1), order='A')
194
+ assert_equal(list(i),
195
+ aview.swapaxes(0, 1).ravel(order='A'))
196
+
197
+ def test_nditer_multi_index_set():
198
+ # Test the multi_index set
199
+ a = np.arange(6).reshape(2, 3)
200
+ it = np.nditer(a, flags=['multi_index'])
201
+
202
+ # Removes the iteration on two first elements of a[0]
203
+ it.multi_index = (0, 2,)
204
+
205
+ assert_equal(list(it), [2, 3, 4, 5])
206
+
207
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
208
+ def test_nditer_multi_index_set_refcount():
209
+ # Test if the reference count on index variable is decreased
210
+
211
+ index = 0
212
+ i = np.nditer(np.array([111, 222, 333, 444]), flags=['multi_index'])
213
+
214
+ start_count = sys.getrefcount(index)
215
+ i.multi_index = (index,)
216
+ end_count = sys.getrefcount(index)
217
+
218
+ assert_equal(start_count, end_count)
219
+
220
+ def test_iter_best_order_multi_index_1d():
221
+ # The multi-indices should be correct with any reordering
222
+
223
+ a = arange(4)
224
+ # 1D order
225
+ i = nditer(a, ['multi_index'], [['readonly']])
226
+ assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)])
227
+ # 1D reversed order
228
+ i = nditer(a[::-1], ['multi_index'], [['readonly']])
229
+ assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)])
230
+
231
+ def test_iter_best_order_multi_index_2d():
232
+ # The multi-indices should be correct with any reordering
233
+
234
+ a = arange(6)
235
+ # 2D C-order
236
+ i = nditer(a.reshape(2, 3), ['multi_index'], [['readonly']])
237
+ assert_equal(iter_multi_index(i), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)])
238
+ # 2D Fortran-order
239
+ i = nditer(a.reshape(2, 3).copy(order='F'), ['multi_index'], [['readonly']])
240
+ assert_equal(iter_multi_index(i), [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)])
241
+ # 2D reversed C-order
242
+ i = nditer(a.reshape(2, 3)[::-1], ['multi_index'], [['readonly']])
243
+ assert_equal(iter_multi_index(i), [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)])
244
+ i = nditer(a.reshape(2, 3)[:, ::-1], ['multi_index'], [['readonly']])
245
+ assert_equal(iter_multi_index(i), [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)])
246
+ i = nditer(a.reshape(2, 3)[::-1, ::-1], ['multi_index'], [['readonly']])
247
+ assert_equal(iter_multi_index(i), [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)])
248
+ # 2D reversed Fortran-order
249
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['multi_index'], [['readonly']])
250
+ assert_equal(iter_multi_index(i), [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)])
251
+ i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
252
+ ['multi_index'], [['readonly']])
253
+ assert_equal(iter_multi_index(i), [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)])
254
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
255
+ ['multi_index'], [['readonly']])
256
+ assert_equal(iter_multi_index(i), [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)])
257
+
258
+ def test_iter_best_order_multi_index_3d():
259
+ # The multi-indices should be correct with any reordering
260
+
261
+ a = arange(12)
262
+ # 3D C-order
263
+ i = nditer(a.reshape(2, 3, 2), ['multi_index'], [['readonly']])
264
+ assert_equal(
265
+ iter_multi_index(i),
266
+ [
267
+ (0, 0, 0),
268
+ (0, 0, 1),
269
+ (0, 1, 0),
270
+ (0, 1, 1),
271
+ (0, 2, 0),
272
+ (0, 2, 1),
273
+ (1, 0, 0),
274
+ (1, 0, 1),
275
+ (1, 1, 0),
276
+ (1, 1, 1),
277
+ (1, 2, 0),
278
+ (1, 2, 1),
279
+ ],
280
+ )
281
+ # 3D Fortran-order
282
+ i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['multi_index'], [['readonly']])
283
+ assert_equal(
284
+ iter_multi_index(i),
285
+ [
286
+ (0, 0, 0),
287
+ (1, 0, 0),
288
+ (0, 1, 0),
289
+ (1, 1, 0),
290
+ (0, 2, 0),
291
+ (1, 2, 0),
292
+ (0, 0, 1),
293
+ (1, 0, 1),
294
+ (0, 1, 1),
295
+ (1, 1, 1),
296
+ (0, 2, 1),
297
+ (1, 2, 1),
298
+ ],
299
+ )
300
+ # 3D reversed C-order
301
+ i = nditer(a.reshape(2, 3, 2)[::-1], ['multi_index'], [['readonly']])
302
+ assert_equal(
303
+ iter_multi_index(i),
304
+ [
305
+ (1, 0, 0),
306
+ (1, 0, 1),
307
+ (1, 1, 0),
308
+ (1, 1, 1),
309
+ (1, 2, 0),
310
+ (1, 2, 1),
311
+ (0, 0, 0),
312
+ (0, 0, 1),
313
+ (0, 1, 0),
314
+ (0, 1, 1),
315
+ (0, 2, 0),
316
+ (0, 2, 1),
317
+ ],
318
+ )
319
+ i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['multi_index'], [['readonly']])
320
+ assert_equal(
321
+ iter_multi_index(i),
322
+ [
323
+ (0, 2, 0),
324
+ (0, 2, 1),
325
+ (0, 1, 0),
326
+ (0, 1, 1),
327
+ (0, 0, 0),
328
+ (0, 0, 1),
329
+ (1, 2, 0),
330
+ (1, 2, 1),
331
+ (1, 1, 0),
332
+ (1, 1, 1),
333
+ (1, 0, 0),
334
+ (1, 0, 1),
335
+ ],
336
+ )
337
+ i = nditer(a.reshape(2, 3, 2)[:, :, ::-1], ['multi_index'], [['readonly']])
338
+ assert_equal(
339
+ iter_multi_index(i),
340
+ [
341
+ (0, 0, 1),
342
+ (0, 0, 0),
343
+ (0, 1, 1),
344
+ (0, 1, 0),
345
+ (0, 2, 1),
346
+ (0, 2, 0),
347
+ (1, 0, 1),
348
+ (1, 0, 0),
349
+ (1, 1, 1),
350
+ (1, 1, 0),
351
+ (1, 2, 1),
352
+ (1, 2, 0),
353
+ ],
354
+ )
355
+ # 3D reversed Fortran-order
356
+ i = nditer(
357
+ a.reshape(2, 3, 2).copy(order='F')[::-1],
358
+ ['multi_index'],
359
+ [['readonly']],
360
+ )
361
+ assert_equal(
362
+ iter_multi_index(i),
363
+ [
364
+ (1, 0, 0),
365
+ (0, 0, 0),
366
+ (1, 1, 0),
367
+ (0, 1, 0),
368
+ (1, 2, 0),
369
+ (0, 2, 0),
370
+ (1, 0, 1),
371
+ (0, 0, 1),
372
+ (1, 1, 1),
373
+ (0, 1, 1),
374
+ (1, 2, 1),
375
+ (0, 2, 1),
376
+ ],
377
+ )
378
+ i = nditer(
379
+ a.reshape(2, 3, 2).copy(order="F")[:, ::-1],
380
+ ["multi_index"],
381
+ [["readonly"]],
382
+ )
383
+ assert_equal(
384
+ iter_multi_index(i),
385
+ [
386
+ (0, 2, 0),
387
+ (1, 2, 0),
388
+ (0, 1, 0),
389
+ (1, 1, 0),
390
+ (0, 0, 0),
391
+ (1, 0, 0),
392
+ (0, 2, 1),
393
+ (1, 2, 1),
394
+ (0, 1, 1),
395
+ (1, 1, 1),
396
+ (0, 0, 1),
397
+ (1, 0, 1),
398
+ ],
399
+ )
400
+ i = nditer(
401
+ a.reshape(2, 3, 2).copy(order="F")[:, :, ::-1],
402
+ ["multi_index"],
403
+ [["readonly"]],
404
+ )
405
+ assert_equal(
406
+ iter_multi_index(i),
407
+ [
408
+ (0, 0, 1),
409
+ (1, 0, 1),
410
+ (0, 1, 1),
411
+ (1, 1, 1),
412
+ (0, 2, 1),
413
+ (1, 2, 1),
414
+ (0, 0, 0),
415
+ (1, 0, 0),
416
+ (0, 1, 0),
417
+ (1, 1, 0),
418
+ (0, 2, 0),
419
+ (1, 2, 0),
420
+ ],
421
+ )
422
+
423
+ def test_iter_best_order_c_index_1d():
424
+ # The C index should be correct with any reordering
425
+
426
+ a = arange(4)
427
+ # 1D order
428
+ i = nditer(a, ['c_index'], [['readonly']])
429
+ assert_equal(iter_indices(i), [0, 1, 2, 3])
430
+ # 1D reversed order
431
+ i = nditer(a[::-1], ['c_index'], [['readonly']])
432
+ assert_equal(iter_indices(i), [3, 2, 1, 0])
433
+
434
+ def test_iter_best_order_c_index_2d():
435
+ # The C index should be correct with any reordering
436
+
437
+ a = arange(6)
438
+ # 2D C-order
439
+ i = nditer(a.reshape(2, 3), ['c_index'], [['readonly']])
440
+ assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5])
441
+ # 2D Fortran-order
442
+ i = nditer(a.reshape(2, 3).copy(order='F'),
443
+ ['c_index'], [['readonly']])
444
+ assert_equal(iter_indices(i), [0, 3, 1, 4, 2, 5])
445
+ # 2D reversed C-order
446
+ i = nditer(a.reshape(2, 3)[::-1], ['c_index'], [['readonly']])
447
+ assert_equal(iter_indices(i), [3, 4, 5, 0, 1, 2])
448
+ i = nditer(a.reshape(2, 3)[:, ::-1], ['c_index'], [['readonly']])
449
+ assert_equal(iter_indices(i), [2, 1, 0, 5, 4, 3])
450
+ i = nditer(a.reshape(2, 3)[::-1, ::-1], ['c_index'], [['readonly']])
451
+ assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0])
452
+ # 2D reversed Fortran-order
453
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1],
454
+ ['c_index'], [['readonly']])
455
+ assert_equal(iter_indices(i), [3, 0, 4, 1, 5, 2])
456
+ i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
457
+ ['c_index'], [['readonly']])
458
+ assert_equal(iter_indices(i), [2, 5, 1, 4, 0, 3])
459
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
460
+ ['c_index'], [['readonly']])
461
+ assert_equal(iter_indices(i), [5, 2, 4, 1, 3, 0])
462
+
463
+ def test_iter_best_order_c_index_3d():
464
+ # The C index should be correct with any reordering
465
+
466
+ a = arange(12)
467
+ # 3D C-order
468
+ i = nditer(a.reshape(2, 3, 2), ['c_index'], [['readonly']])
469
+ assert_equal(iter_indices(i),
470
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
471
+ # 3D Fortran-order
472
+ i = nditer(a.reshape(2, 3, 2).copy(order='F'),
473
+ ['c_index'], [['readonly']])
474
+ assert_equal(iter_indices(i),
475
+ [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11])
476
+ # 3D reversed C-order
477
+ i = nditer(a.reshape(2, 3, 2)[::-1], ['c_index'], [['readonly']])
478
+ assert_equal(iter_indices(i),
479
+ [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5])
480
+ i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['c_index'], [['readonly']])
481
+ assert_equal(iter_indices(i),
482
+ [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7])
483
+ i = nditer(a.reshape(2, 3, 2)[:, :, ::-1], ['c_index'], [['readonly']])
484
+ assert_equal(iter_indices(i),
485
+ [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10])
486
+ # 3D reversed Fortran-order
487
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1],
488
+ ['c_index'], [['readonly']])
489
+ assert_equal(iter_indices(i),
490
+ [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5])
491
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1],
492
+ ['c_index'], [['readonly']])
493
+ assert_equal(iter_indices(i),
494
+ [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7])
495
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, :, ::-1],
496
+ ['c_index'], [['readonly']])
497
+ assert_equal(iter_indices(i),
498
+ [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10])
499
+
500
+ def test_iter_best_order_f_index_1d():
501
+ # The Fortran index should be correct with any reordering
502
+
503
+ a = arange(4)
504
+ # 1D order
505
+ i = nditer(a, ['f_index'], [['readonly']])
506
+ assert_equal(iter_indices(i), [0, 1, 2, 3])
507
+ # 1D reversed order
508
+ i = nditer(a[::-1], ['f_index'], [['readonly']])
509
+ assert_equal(iter_indices(i), [3, 2, 1, 0])
510
+
511
+ def test_iter_best_order_f_index_2d():
512
+ # The Fortran index should be correct with any reordering
513
+
514
+ a = arange(6)
515
+ # 2D C-order
516
+ i = nditer(a.reshape(2, 3), ['f_index'], [['readonly']])
517
+ assert_equal(iter_indices(i), [0, 2, 4, 1, 3, 5])
518
+ # 2D Fortran-order
519
+ i = nditer(a.reshape(2, 3).copy(order='F'),
520
+ ['f_index'], [['readonly']])
521
+ assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5])
522
+ # 2D reversed C-order
523
+ i = nditer(a.reshape(2, 3)[::-1], ['f_index'], [['readonly']])
524
+ assert_equal(iter_indices(i), [1, 3, 5, 0, 2, 4])
525
+ i = nditer(a.reshape(2, 3)[:, ::-1], ['f_index'], [['readonly']])
526
+ assert_equal(iter_indices(i), [4, 2, 0, 5, 3, 1])
527
+ i = nditer(a.reshape(2, 3)[::-1, ::-1], ['f_index'], [['readonly']])
528
+ assert_equal(iter_indices(i), [5, 3, 1, 4, 2, 0])
529
+ # 2D reversed Fortran-order
530
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1],
531
+ ['f_index'], [['readonly']])
532
+ assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4])
533
+ i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1],
534
+ ['f_index'], [['readonly']])
535
+ assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1])
536
+ i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1],
537
+ ['f_index'], [['readonly']])
538
+ assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0])
539
+
540
+ def test_iter_best_order_f_index_3d():
541
+ # The Fortran index should be correct with any reordering
542
+
543
+ a = arange(12)
544
+ # 3D C-order
545
+ i = nditer(a.reshape(2, 3, 2), ['f_index'], [['readonly']])
546
+ assert_equal(iter_indices(i),
547
+ [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11])
548
+ # 3D Fortran-order
549
+ i = nditer(a.reshape(2, 3, 2).copy(order='F'),
550
+ ['f_index'], [['readonly']])
551
+ assert_equal(iter_indices(i),
552
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
553
+ # 3D reversed C-order
554
+ i = nditer(a.reshape(2, 3, 2)[::-1], ['f_index'], [['readonly']])
555
+ assert_equal(iter_indices(i),
556
+ [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10])
557
+ i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['f_index'], [['readonly']])
558
+ assert_equal(iter_indices(i),
559
+ [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7])
560
+ i = nditer(a.reshape(2, 3, 2)[:, :, ::-1], ['f_index'], [['readonly']])
561
+ assert_equal(iter_indices(i),
562
+ [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5])
563
+ # 3D reversed Fortran-order
564
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1],
565
+ ['f_index'], [['readonly']])
566
+ assert_equal(iter_indices(i),
567
+ [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10])
568
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1],
569
+ ['f_index'], [['readonly']])
570
+ assert_equal(iter_indices(i),
571
+ [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7])
572
+ i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, :, ::-1],
573
+ ['f_index'], [['readonly']])
574
+ assert_equal(iter_indices(i),
575
+ [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5])
576
+
577
+ def test_iter_no_inner_full_coalesce():
578
+ # Check no_inner iterators which coalesce into a single inner loop
579
+
580
+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]:
581
+ size = np.prod(shape)
582
+ a = arange(size)
583
+ # Test each combination of forward and backwards indexing
584
+ for dirs in range(2**len(shape)):
585
+ dirs_index = [slice(None)] * len(shape)
586
+ for bit in range(len(shape)):
587
+ if ((2**bit) & dirs):
588
+ dirs_index[bit] = slice(None, None, -1)
589
+ dirs_index = tuple(dirs_index)
590
+
591
+ aview = a.reshape(shape)[dirs_index]
592
+ # C-order
593
+ i = nditer(aview, ['external_loop'], [['readonly']])
594
+ assert_equal(i.ndim, 1)
595
+ assert_equal(i[0].shape, (size,))
596
+ # Fortran-order
597
+ i = nditer(aview.T, ['external_loop'], [['readonly']])
598
+ assert_equal(i.ndim, 1)
599
+ assert_equal(i[0].shape, (size,))
600
+ # Other order
601
+ if len(shape) > 2:
602
+ i = nditer(aview.swapaxes(0, 1),
603
+ ['external_loop'], [['readonly']])
604
+ assert_equal(i.ndim, 1)
605
+ assert_equal(i[0].shape, (size,))
606
+
607
+ def test_iter_no_inner_dim_coalescing():
608
+ # Check no_inner iterators whose dimensions may not coalesce completely
609
+
610
+ # Skipping the last element in a dimension prevents coalescing
611
+ # with the next-bigger dimension
612
+ a = arange(24).reshape(2, 3, 4)[:, :, :-1]
613
+ i = nditer(a, ['external_loop'], [['readonly']])
614
+ assert_equal(i.ndim, 2)
615
+ assert_equal(i[0].shape, (3,))
616
+ a = arange(24).reshape(2, 3, 4)[:, :-1, :]
617
+ i = nditer(a, ['external_loop'], [['readonly']])
618
+ assert_equal(i.ndim, 2)
619
+ assert_equal(i[0].shape, (8,))
620
+ a = arange(24).reshape(2, 3, 4)[:-1, :, :]
621
+ i = nditer(a, ['external_loop'], [['readonly']])
622
+ assert_equal(i.ndim, 1)
623
+ assert_equal(i[0].shape, (12,))
624
+
625
+ # Even with lots of 1-sized dimensions, should still coalesce
626
+ a = arange(24).reshape(1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1)
627
+ i = nditer(a, ['external_loop'], [['readonly']])
628
+ assert_equal(i.ndim, 1)
629
+ assert_equal(i[0].shape, (24,))
630
+
631
+ def test_iter_dim_coalescing():
632
+ # Check that the correct number of dimensions are coalesced
633
+
634
+ # Tracking a multi-index disables coalescing
635
+ a = arange(24).reshape(2, 3, 4)
636
+ i = nditer(a, ['multi_index'], [['readonly']])
637
+ assert_equal(i.ndim, 3)
638
+
639
+ # A tracked index can allow coalescing if it's compatible with the array
640
+ a3d = arange(24).reshape(2, 3, 4)
641
+ i = nditer(a3d, ['c_index'], [['readonly']])
642
+ assert_equal(i.ndim, 1)
643
+ i = nditer(a3d.swapaxes(0, 1), ['c_index'], [['readonly']])
644
+ assert_equal(i.ndim, 3)
645
+ i = nditer(a3d.T, ['c_index'], [['readonly']])
646
+ assert_equal(i.ndim, 3)
647
+ i = nditer(a3d.T, ['f_index'], [['readonly']])
648
+ assert_equal(i.ndim, 1)
649
+ i = nditer(a3d.T.swapaxes(0, 1), ['f_index'], [['readonly']])
650
+ assert_equal(i.ndim, 3)
651
+
652
+ # When C or F order is forced, coalescing may still occur
653
+ a3d = arange(24).reshape(2, 3, 4)
654
+ i = nditer(a3d, order='C')
655
+ assert_equal(i.ndim, 1)
656
+ i = nditer(a3d.T, order='C')
657
+ assert_equal(i.ndim, 3)
658
+ i = nditer(a3d, order='F')
659
+ assert_equal(i.ndim, 3)
660
+ i = nditer(a3d.T, order='F')
661
+ assert_equal(i.ndim, 1)
662
+ i = nditer(a3d, order='A')
663
+ assert_equal(i.ndim, 1)
664
+ i = nditer(a3d.T, order='A')
665
+ assert_equal(i.ndim, 1)
666
+
667
+ def test_iter_broadcasting():
668
+ # Standard NumPy broadcasting rules
669
+
670
+ # 1D with scalar
671
+ i = nditer([arange(6), np.int32(2)], ['multi_index'], [['readonly']] * 2)
672
+ assert_equal(i.itersize, 6)
673
+ assert_equal(i.shape, (6,))
674
+
675
+ # 2D with scalar
676
+ i = nditer([arange(6).reshape(2, 3), np.int32(2)],
677
+ ['multi_index'], [['readonly']] * 2)
678
+ assert_equal(i.itersize, 6)
679
+ assert_equal(i.shape, (2, 3))
680
+ # 2D with 1D
681
+ i = nditer([arange(6).reshape(2, 3), arange(3)],
682
+ ['multi_index'], [['readonly']] * 2)
683
+ assert_equal(i.itersize, 6)
684
+ assert_equal(i.shape, (2, 3))
685
+ i = nditer([arange(2).reshape(2, 1), arange(3)],
686
+ ['multi_index'], [['readonly']] * 2)
687
+ assert_equal(i.itersize, 6)
688
+ assert_equal(i.shape, (2, 3))
689
+ # 2D with 2D
690
+ i = nditer([arange(2).reshape(2, 1), arange(3).reshape(1, 3)],
691
+ ['multi_index'], [['readonly']] * 2)
692
+ assert_equal(i.itersize, 6)
693
+ assert_equal(i.shape, (2, 3))
694
+
695
+ # 3D with scalar
696
+ i = nditer([np.int32(2), arange(24).reshape(4, 2, 3)],
697
+ ['multi_index'], [['readonly']] * 2)
698
+ assert_equal(i.itersize, 24)
699
+ assert_equal(i.shape, (4, 2, 3))
700
+ # 3D with 1D
701
+ i = nditer([arange(3), arange(24).reshape(4, 2, 3)],
702
+ ['multi_index'], [['readonly']] * 2)
703
+ assert_equal(i.itersize, 24)
704
+ assert_equal(i.shape, (4, 2, 3))
705
+ i = nditer([arange(3), arange(8).reshape(4, 2, 1)],
706
+ ['multi_index'], [['readonly']] * 2)
707
+ assert_equal(i.itersize, 24)
708
+ assert_equal(i.shape, (4, 2, 3))
709
+ # 3D with 2D
710
+ i = nditer([arange(6).reshape(2, 3), arange(24).reshape(4, 2, 3)],
711
+ ['multi_index'], [['readonly']] * 2)
712
+ assert_equal(i.itersize, 24)
713
+ assert_equal(i.shape, (4, 2, 3))
714
+ i = nditer([arange(2).reshape(2, 1), arange(24).reshape(4, 2, 3)],
715
+ ['multi_index'], [['readonly']] * 2)
716
+ assert_equal(i.itersize, 24)
717
+ assert_equal(i.shape, (4, 2, 3))
718
+ i = nditer([arange(3).reshape(1, 3), arange(8).reshape(4, 2, 1)],
719
+ ['multi_index'], [['readonly']] * 2)
720
+ assert_equal(i.itersize, 24)
721
+ assert_equal(i.shape, (4, 2, 3))
722
+ # 3D with 3D
723
+ i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 1, 3),
724
+ arange(4).reshape(4, 1, 1)],
725
+ ['multi_index'], [['readonly']] * 3)
726
+ assert_equal(i.itersize, 24)
727
+ assert_equal(i.shape, (4, 2, 3))
728
+ i = nditer([arange(6).reshape(1, 2, 3), arange(4).reshape(4, 1, 1)],
729
+ ['multi_index'], [['readonly']] * 2)
730
+ assert_equal(i.itersize, 24)
731
+ assert_equal(i.shape, (4, 2, 3))
732
+ i = nditer([arange(24).reshape(4, 2, 3), arange(12).reshape(4, 1, 3)],
733
+ ['multi_index'], [['readonly']] * 2)
734
+ assert_equal(i.itersize, 24)
735
+ assert_equal(i.shape, (4, 2, 3))
736
+
737
+ def test_iter_itershape():
738
+ # Check that allocated outputs work with a specified shape
739
+ a = np.arange(6, dtype='i2').reshape(2, 3)
740
+ i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
741
+ op_axes=[[0, 1, None], None],
742
+ itershape=(-1, -1, 4))
743
+ assert_equal(i.operands[1].shape, (2, 3, 4))
744
+ assert_equal(i.operands[1].strides, (24, 8, 2))
745
+
746
+ i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']],
747
+ op_axes=[[0, 1, None], None],
748
+ itershape=(-1, -1, 4))
749
+ assert_equal(i.operands[1].shape, (3, 2, 4))
750
+ assert_equal(i.operands[1].strides, (8, 24, 2))
751
+
752
+ i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']],
753
+ order='F',
754
+ op_axes=[[0, 1, None], None],
755
+ itershape=(-1, -1, 4))
756
+ assert_equal(i.operands[1].shape, (3, 2, 4))
757
+ assert_equal(i.operands[1].strides, (2, 6, 12))
758
+
759
+ # If we specify 1 in the itershape, it shouldn't allow broadcasting
760
+ # of that dimension to a bigger value
761
+ assert_raises(ValueError, nditer, [a, None], [],
762
+ [['readonly'], ['writeonly', 'allocate']],
763
+ op_axes=[[0, 1, None], None],
764
+ itershape=(-1, 1, 4))
765
+ # Test bug that for no op_axes but itershape, they are NULLed correctly
766
+ i = np.nditer([np.ones(2), None, None], itershape=(2,))
767
+
768
+ def test_iter_broadcasting_errors():
769
+ # Check that errors are thrown for bad broadcasting shapes
770
+
771
+ # 1D with 1D
772
+ assert_raises(ValueError, nditer, [arange(2), arange(3)],
773
+ [], [['readonly']] * 2)
774
+ # 2D with 1D
775
+ assert_raises(ValueError, nditer,
776
+ [arange(6).reshape(2, 3), arange(2)],
777
+ [], [['readonly']] * 2)
778
+ # 2D with 2D
779
+ assert_raises(ValueError, nditer,
780
+ [arange(6).reshape(2, 3), arange(9).reshape(3, 3)],
781
+ [], [['readonly']] * 2)
782
+ assert_raises(ValueError, nditer,
783
+ [arange(6).reshape(2, 3), arange(4).reshape(2, 2)],
784
+ [], [['readonly']] * 2)
785
+ # 3D with 3D
786
+ assert_raises(ValueError, nditer,
787
+ [arange(36).reshape(3, 3, 4), arange(24).reshape(2, 3, 4)],
788
+ [], [['readonly']] * 2)
789
+ assert_raises(ValueError, nditer,
790
+ [arange(8).reshape(2, 4, 1), arange(24).reshape(2, 3, 4)],
791
+ [], [['readonly']] * 2)
792
+
793
+ # Verify that the error message mentions the right shapes
794
+ try:
795
+ nditer([arange(2).reshape(1, 2, 1),
796
+ arange(3).reshape(1, 3),
797
+ arange(6).reshape(2, 3)],
798
+ [],
799
+ [['readonly'], ['readonly'], ['writeonly', 'no_broadcast']])
800
+ raise AssertionError('Should have raised a broadcast error')
801
+ except ValueError as e:
802
+ msg = str(e)
803
+ # The message should contain the shape of the 3rd operand
804
+ assert_(msg.find('(2,3)') >= 0,
805
+ f'Message "{msg}" doesn\'t contain operand shape (2,3)')
806
+ # The message should contain the broadcast shape
807
+ assert_(msg.find('(1,2,3)') >= 0,
808
+ f'Message "{msg}" doesn\'t contain broadcast shape (1,2,3)')
809
+
810
+ try:
811
+ nditer([arange(6).reshape(2, 3), arange(2)],
812
+ [],
813
+ [['readonly'], ['readonly']],
814
+ op_axes=[[0, 1], [0, np.newaxis]],
815
+ itershape=(4, 3))
816
+ raise AssertionError('Should have raised a broadcast error')
817
+ except ValueError as e:
818
+ msg = str(e)
819
+ # The message should contain "shape->remappedshape" for each operand
820
+ assert_(msg.find('(2,3)->(2,3)') >= 0,
821
+ f'Message "{msg}" doesn\'t contain operand shape (2,3)->(2,3)')
822
+ assert_(msg.find('(2,)->(2,newaxis)') >= 0,
823
+ f'Message "{msg}" doesn\'t contain remapped operand shape'
824
+ '(2,)->(2,newaxis)')
825
+ # The message should contain the itershape parameter
826
+ assert_(msg.find('(4,3)') >= 0,
827
+ f'Message "{msg}" doesn\'t contain itershape parameter (4,3)')
828
+
829
+ try:
830
+ nditer([np.zeros((2, 1, 1)), np.zeros((2,))],
831
+ [],
832
+ [['writeonly', 'no_broadcast'], ['readonly']])
833
+ raise AssertionError('Should have raised a broadcast error')
834
+ except ValueError as e:
835
+ msg = str(e)
836
+ # The message should contain the shape of the bad operand
837
+ assert_(msg.find('(2,1,1)') >= 0,
838
+ f'Message "{msg}" doesn\'t contain operand shape (2,1,1)')
839
+ # The message should contain the broadcast shape
840
+ assert_(msg.find('(2,1,2)') >= 0,
841
+ f'Message "{msg}" doesn\'t contain the broadcast shape (2,1,2)')
842
+
843
+ def test_iter_flags_errors():
844
+ # Check that bad combinations of flags produce errors
845
+
846
+ a = arange(6)
847
+
848
+ # Not enough operands
849
+ assert_raises(ValueError, nditer, [], [], [])
850
+ # Bad global flag
851
+ assert_raises(ValueError, nditer, [a], ['bad flag'], [['readonly']])
852
+ # Bad op flag
853
+ assert_raises(ValueError, nditer, [a], [], [['readonly', 'bad flag']])
854
+ # Bad order parameter
855
+ assert_raises(ValueError, nditer, [a], [], [['readonly']], order='G')
856
+ # Bad casting parameter
857
+ assert_raises(ValueError, nditer, [a], [], [['readonly']], casting='noon')
858
+ # op_flags must match ops
859
+ assert_raises(ValueError, nditer, [a] * 3, [], [['readonly']] * 2)
860
+ # Cannot track both a C and an F index
861
+ assert_raises(ValueError, nditer, a,
862
+ ['c_index', 'f_index'], [['readonly']])
863
+ # Inner iteration and multi-indices/indices are incompatible
864
+ assert_raises(ValueError, nditer, a,
865
+ ['external_loop', 'multi_index'], [['readonly']])
866
+ assert_raises(ValueError, nditer, a,
867
+ ['external_loop', 'c_index'], [['readonly']])
868
+ assert_raises(ValueError, nditer, a,
869
+ ['external_loop', 'f_index'], [['readonly']])
870
+ # Must specify exactly one of readwrite/readonly/writeonly per operand
871
+ assert_raises(ValueError, nditer, a, [], [[]])
872
+ assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly']])
873
+ assert_raises(ValueError, nditer, a, [], [['readonly', 'readwrite']])
874
+ assert_raises(ValueError, nditer, a, [], [['writeonly', 'readwrite']])
875
+ assert_raises(ValueError, nditer, a,
876
+ [], [['readonly', 'writeonly', 'readwrite']])
877
+ # Python scalars are always readonly
878
+ assert_raises(TypeError, nditer, 1.5, [], [['writeonly']])
879
+ assert_raises(TypeError, nditer, 1.5, [], [['readwrite']])
880
+ # Array scalars are always readonly
881
+ assert_raises(TypeError, nditer, np.int32(1), [], [['writeonly']])
882
+ assert_raises(TypeError, nditer, np.int32(1), [], [['readwrite']])
883
+ # Check readonly array
884
+ a.flags.writeable = False
885
+ assert_raises(ValueError, nditer, a, [], [['writeonly']])
886
+ assert_raises(ValueError, nditer, a, [], [['readwrite']])
887
+ a.flags.writeable = True
888
+ # Multi-indices available only with the multi_index flag
889
+ i = nditer(arange(6), [], [['readonly']])
890
+ assert_raises(ValueError, lambda i: i.multi_index, i)
891
+ # Index available only with an index flag
892
+ assert_raises(ValueError, lambda i: i.index, i)
893
+ # GotoCoords and GotoIndex incompatible with buffering or no_inner
894
+
895
+ def assign_multi_index(i):
896
+ i.multi_index = (0,)
897
+
898
+ def assign_index(i):
899
+ i.index = 0
900
+
901
+ def assign_iterindex(i):
902
+ i.iterindex = 0
903
+
904
+ def assign_iterrange(i):
905
+ i.iterrange = (0, 1)
906
+ i = nditer(arange(6), ['external_loop'])
907
+ assert_raises(ValueError, assign_multi_index, i)
908
+ assert_raises(ValueError, assign_index, i)
909
+ assert_raises(ValueError, assign_iterindex, i)
910
+ assert_raises(ValueError, assign_iterrange, i)
911
+ i = nditer(arange(6), ['buffered'])
912
+ assert_raises(ValueError, assign_multi_index, i)
913
+ assert_raises(ValueError, assign_index, i)
914
+ assert_raises(ValueError, assign_iterrange, i)
915
+ # Can't iterate if size is zero
916
+ assert_raises(ValueError, nditer, np.array([]))
917
+
918
+ def test_iter_slice():
919
+ a, b, c = np.arange(3), np.arange(3), np.arange(3.)
920
+ i = nditer([a, b, c], [], ['readwrite'])
921
+ with i:
922
+ i[0:2] = (3, 3)
923
+ assert_equal(a, [3, 1, 2])
924
+ assert_equal(b, [3, 1, 2])
925
+ assert_equal(c, [0, 1, 2])
926
+ i[1] = 12
927
+ assert_equal(i[0:2], [3, 12])
928
+
929
+ def test_iter_assign_mapping():
930
+ a = np.arange(24, dtype='f8').reshape(2, 3, 4).T
931
+ it = np.nditer(a, [], [['readwrite', 'updateifcopy']],
932
+ casting='same_kind', op_dtypes=[np.dtype('f4')])
933
+ with it:
934
+ it.operands[0][...] = 3
935
+ it.operands[0][...] = 14
936
+ assert_equal(a, 14)
937
+ it = np.nditer(a, [], [['readwrite', 'updateifcopy']],
938
+ casting='same_kind', op_dtypes=[np.dtype('f4')])
939
+ with it:
940
+ x = it.operands[0][-1:1]
941
+ x[...] = 14
942
+ it.operands[0][...] = -1234
943
+ assert_equal(a, -1234)
944
+ # check for no warnings on dealloc
945
+ x = None
946
+ it = None
947
+
948
+ def test_iter_nbo_align_contig():
949
+ # Check that byte order, alignment, and contig changes work
950
+
951
+ # Byte order change by requesting a specific dtype
952
+ a = np.arange(6, dtype='f4')
953
+ au = a.byteswap()
954
+ au = au.view(au.dtype.newbyteorder())
955
+ assert_(a.dtype.byteorder != au.dtype.byteorder)
956
+ i = nditer(au, [], [['readwrite', 'updateifcopy']],
957
+ casting='equiv',
958
+ op_dtypes=[np.dtype('f4')])
959
+ with i:
960
+ # context manager triggers WRITEBACKIFCOPY on i at exit
961
+ assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder)
962
+ assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder)
963
+ assert_equal(i.operands[0], a)
964
+ i.operands[0][:] = 2
965
+ assert_equal(au, [2] * 6)
966
+ del i # should not raise a warning
967
+ # Byte order change by requesting NBO
968
+ a = np.arange(6, dtype='f4')
969
+ au = a.byteswap()
970
+ au = au.view(au.dtype.newbyteorder())
971
+ assert_(a.dtype.byteorder != au.dtype.byteorder)
972
+ with nditer(au, [], [['readwrite', 'updateifcopy', 'nbo']],
973
+ casting='equiv') as i:
974
+ # context manager triggers UPDATEIFCOPY on i at exit
975
+ assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder)
976
+ assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder)
977
+ assert_equal(i.operands[0], a)
978
+ i.operands[0][:] = 12345
979
+ i.operands[0][:] = 2
980
+ assert_equal(au, [2] * 6)
981
+
982
+ # Unaligned input
983
+ a = np.zeros((6 * 4 + 1,), dtype='i1')[1:]
984
+ a = a.view('f4')
985
+ a[:] = np.arange(6, dtype='f4')
986
+ assert_(not a.flags.aligned)
987
+ # Without 'aligned', shouldn't copy
988
+ i = nditer(a, [], [['readonly']])
989
+ assert_(not i.operands[0].flags.aligned)
990
+ assert_equal(i.operands[0], a)
991
+ # With 'aligned', should make a copy
992
+ with nditer(a, [], [['readwrite', 'updateifcopy', 'aligned']]) as i:
993
+ assert_(i.operands[0].flags.aligned)
994
+ # context manager triggers UPDATEIFCOPY on i at exit
995
+ assert_equal(i.operands[0], a)
996
+ i.operands[0][:] = 3
997
+ assert_equal(a, [3] * 6)
998
+
999
+ # Discontiguous input
1000
+ a = arange(12)
1001
+ # If it is contiguous, shouldn't copy
1002
+ i = nditer(a[:6], [], [['readonly']])
1003
+ assert_(i.operands[0].flags.contiguous)
1004
+ assert_equal(i.operands[0], a[:6])
1005
+ # If it isn't contiguous, should buffer
1006
+ i = nditer(a[::2], ['buffered', 'external_loop'],
1007
+ [['readonly', 'contig']],
1008
+ buffersize=10)
1009
+ assert_(i[0].flags.contiguous)
1010
+ assert_equal(i[0], a[::2])
1011
+
1012
+ def test_iter_array_cast():
1013
+ # Check that arrays are cast as requested
1014
+
1015
+ # No cast 'f4' -> 'f4'
1016
+ a = np.arange(6, dtype='f4').reshape(2, 3)
1017
+ i = nditer(a, [], [['readwrite']], op_dtypes=[np.dtype('f4')])
1018
+ with i:
1019
+ assert_equal(i.operands[0], a)
1020
+ assert_equal(i.operands[0].dtype, np.dtype('f4'))
1021
+
1022
+ # Byte-order cast '<f4' -> '>f4'
1023
+ a = np.arange(6, dtype='<f4').reshape(2, 3)
1024
+ with nditer(a, [], [['readwrite', 'updateifcopy']],
1025
+ casting='equiv',
1026
+ op_dtypes=[np.dtype('>f4')]) as i:
1027
+ assert_equal(i.operands[0], a)
1028
+ assert_equal(i.operands[0].dtype, np.dtype('>f4'))
1029
+
1030
+ # Safe case 'f4' -> 'f8'
1031
+ a = np.arange(24, dtype='f4').reshape(2, 3, 4).swapaxes(1, 2)
1032
+ i = nditer(a, [], [['readonly', 'copy']],
1033
+ casting='safe',
1034
+ op_dtypes=[np.dtype('f8')])
1035
+ assert_equal(i.operands[0], a)
1036
+ assert_equal(i.operands[0].dtype, np.dtype('f8'))
1037
+ # The memory layout of the temporary should match a (a is (48,4,16))
1038
+ # except negative strides get flipped to positive strides.
1039
+ assert_equal(i.operands[0].strides, (96, 8, 32))
1040
+ a = a[::-1, :, ::-1]
1041
+ i = nditer(a, [], [['readonly', 'copy']],
1042
+ casting='safe',
1043
+ op_dtypes=[np.dtype('f8')])
1044
+ assert_equal(i.operands[0], a)
1045
+ assert_equal(i.operands[0].dtype, np.dtype('f8'))
1046
+ assert_equal(i.operands[0].strides, (96, 8, 32))
1047
+
1048
+ # Same-kind cast 'f8' -> 'f4' -> 'f8'
1049
+ a = np.arange(24, dtype='f8').reshape(2, 3, 4).T
1050
+ with nditer(a, [],
1051
+ [['readwrite', 'updateifcopy']],
1052
+ casting='same_kind',
1053
+ op_dtypes=[np.dtype('f4')]) as i:
1054
+ assert_equal(i.operands[0], a)
1055
+ assert_equal(i.operands[0].dtype, np.dtype('f4'))
1056
+ assert_equal(i.operands[0].strides, (4, 16, 48))
1057
+ # Check that WRITEBACKIFCOPY is activated at exit
1058
+ i.operands[0][2, 1, 1] = -12.5
1059
+ assert_(a[2, 1, 1] != -12.5)
1060
+ assert_equal(a[2, 1, 1], -12.5)
1061
+
1062
+ a = np.arange(6, dtype='i4')[::-2]
1063
+ with nditer(a, [],
1064
+ [['writeonly', 'updateifcopy']],
1065
+ casting='unsafe',
1066
+ op_dtypes=[np.dtype('f4')]) as i:
1067
+ assert_equal(i.operands[0].dtype, np.dtype('f4'))
1068
+ # Even though the stride was negative in 'a', it
1069
+ # becomes positive in the temporary
1070
+ assert_equal(i.operands[0].strides, (4,))
1071
+ i.operands[0][:] = [1, 2, 3]
1072
+ assert_equal(a, [1, 2, 3])
1073
+
1074
+ def test_iter_array_cast_errors():
1075
+ # Check that invalid casts are caught
1076
+
1077
+ # Need to enable copying for casts to occur
1078
+ assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
1079
+ [['readonly']], op_dtypes=[np.dtype('f8')])
1080
+ # Also need to allow casting for casts to occur
1081
+ assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
1082
+ [['readonly', 'copy']], casting='no',
1083
+ op_dtypes=[np.dtype('f8')])
1084
+ assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
1085
+ [['readonly', 'copy']], casting='equiv',
1086
+ op_dtypes=[np.dtype('f8')])
1087
+ assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
1088
+ [['writeonly', 'updateifcopy']],
1089
+ casting='no',
1090
+ op_dtypes=[np.dtype('f4')])
1091
+ assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
1092
+ [['writeonly', 'updateifcopy']],
1093
+ casting='equiv',
1094
+ op_dtypes=[np.dtype('f4')])
1095
+ # '<f4' -> '>f4' should not work with casting='no'
1096
+ assert_raises(TypeError, nditer, arange(2, dtype='<f4'), [],
1097
+ [['readonly', 'copy']], casting='no',
1098
+ op_dtypes=[np.dtype('>f4')])
1099
+ # 'f4' -> 'f8' is a safe cast, but 'f8' -> 'f4' isn't
1100
+ assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
1101
+ [['readwrite', 'updateifcopy']],
1102
+ casting='safe',
1103
+ op_dtypes=[np.dtype('f8')])
1104
+ assert_raises(TypeError, nditer, arange(2, dtype='f8'), [],
1105
+ [['readwrite', 'updateifcopy']],
1106
+ casting='safe',
1107
+ op_dtypes=[np.dtype('f4')])
1108
+ # 'f4' -> 'i4' is neither a safe nor a same-kind cast
1109
+ assert_raises(TypeError, nditer, arange(2, dtype='f4'), [],
1110
+ [['readonly', 'copy']],
1111
+ casting='same_kind',
1112
+ op_dtypes=[np.dtype('i4')])
1113
+ assert_raises(TypeError, nditer, arange(2, dtype='i4'), [],
1114
+ [['writeonly', 'updateifcopy']],
1115
+ casting='same_kind',
1116
+ op_dtypes=[np.dtype('f4')])
1117
+
1118
+ def test_iter_scalar_cast():
1119
+ # Check that scalars are cast as requested
1120
+
1121
+ # No cast 'f4' -> 'f4'
1122
+ i = nditer(np.float32(2.5), [], [['readonly']],
1123
+ op_dtypes=[np.dtype('f4')])
1124
+ assert_equal(i.dtypes[0], np.dtype('f4'))
1125
+ assert_equal(i.value.dtype, np.dtype('f4'))
1126
+ assert_equal(i.value, 2.5)
1127
+ # Safe cast 'f4' -> 'f8'
1128
+ i = nditer(np.float32(2.5), [],
1129
+ [['readonly', 'copy']],
1130
+ casting='safe',
1131
+ op_dtypes=[np.dtype('f8')])
1132
+ assert_equal(i.dtypes[0], np.dtype('f8'))
1133
+ assert_equal(i.value.dtype, np.dtype('f8'))
1134
+ assert_equal(i.value, 2.5)
1135
+ # Same-kind cast 'f8' -> 'f4'
1136
+ i = nditer(np.float64(2.5), [],
1137
+ [['readonly', 'copy']],
1138
+ casting='same_kind',
1139
+ op_dtypes=[np.dtype('f4')])
1140
+ assert_equal(i.dtypes[0], np.dtype('f4'))
1141
+ assert_equal(i.value.dtype, np.dtype('f4'))
1142
+ assert_equal(i.value, 2.5)
1143
+ # Unsafe cast 'f8' -> 'i4'
1144
+ i = nditer(np.float64(3.0), [],
1145
+ [['readonly', 'copy']],
1146
+ casting='unsafe',
1147
+ op_dtypes=[np.dtype('i4')])
1148
+ assert_equal(i.dtypes[0], np.dtype('i4'))
1149
+ assert_equal(i.value.dtype, np.dtype('i4'))
1150
+ assert_equal(i.value, 3)
1151
+ # Readonly scalars may be cast even without setting COPY or BUFFERED
1152
+ i = nditer(3, [], [['readonly']], op_dtypes=[np.dtype('f8')])
1153
+ assert_equal(i[0].dtype, np.dtype('f8'))
1154
+ assert_equal(i[0], 3.)
1155
+
1156
+ def test_iter_scalar_cast_errors():
1157
+ # Check that invalid casts are caught
1158
+
1159
+ # Need to allow copying/buffering for write casts of scalars to occur
1160
+ assert_raises(TypeError, nditer, np.float32(2), [],
1161
+ [['readwrite']], op_dtypes=[np.dtype('f8')])
1162
+ assert_raises(TypeError, nditer, 2.5, [],
1163
+ [['readwrite']], op_dtypes=[np.dtype('f4')])
1164
+ # 'f8' -> 'f4' isn't a safe cast if the value would overflow
1165
+ assert_raises(TypeError, nditer, np.float64(1e60), [],
1166
+ [['readonly']],
1167
+ casting='safe',
1168
+ op_dtypes=[np.dtype('f4')])
1169
+ # 'f4' -> 'i4' is neither a safe nor a same-kind cast
1170
+ assert_raises(TypeError, nditer, np.float32(2), [],
1171
+ [['readonly']],
1172
+ casting='same_kind',
1173
+ op_dtypes=[np.dtype('i4')])
1174
+
1175
+ def test_iter_object_arrays_basic():
1176
+ # Check that object arrays work
1177
+
1178
+ obj = {'a': 3, 'b': 'd'}
1179
+ a = np.array([[1, 2, 3], None, obj, None], dtype='O')
1180
+ if HAS_REFCOUNT:
1181
+ rc = sys.getrefcount(obj)
1182
+
1183
+ # Need to allow references for object arrays
1184
+ assert_raises(TypeError, nditer, a)
1185
+ if HAS_REFCOUNT:
1186
+ assert_equal(sys.getrefcount(obj), rc)
1187
+
1188
+ i = nditer(a, ['refs_ok'], ['readonly'])
1189
+ vals = [x_[()] for x_ in i]
1190
+ assert_equal(np.array(vals, dtype='O'), a)
1191
+ vals, i, x = [None] * 3
1192
+ if HAS_REFCOUNT:
1193
+ assert_equal(sys.getrefcount(obj), rc)
1194
+
1195
+ i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'],
1196
+ ['readonly'], order='C')
1197
+ assert_(i.iterationneedsapi)
1198
+ vals = [x_[()] for x_ in i]
1199
+ assert_equal(np.array(vals, dtype='O'), a.reshape(2, 2).ravel(order='F'))
1200
+ vals, i, x = [None] * 3
1201
+ if HAS_REFCOUNT:
1202
+ assert_equal(sys.getrefcount(obj), rc)
1203
+
1204
+ i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'],
1205
+ ['readwrite'], order='C')
1206
+ with i:
1207
+ for x in i:
1208
+ x[...] = None
1209
+ vals, i, x = [None] * 3
1210
+ if HAS_REFCOUNT:
1211
+ assert_(sys.getrefcount(obj) == rc - 1)
1212
+ assert_equal(a, np.array([None] * 4, dtype='O'))
1213
+
1214
+ def test_iter_object_arrays_conversions():
1215
+ # Conversions to/from objects
1216
+ a = np.arange(6, dtype='O')
1217
+ i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
1218
+ casting='unsafe', op_dtypes='i4')
1219
+ with i:
1220
+ for x in i:
1221
+ x[...] += 1
1222
+ assert_equal(a, np.arange(6) + 1)
1223
+
1224
+ a = np.arange(6, dtype='i4')
1225
+ i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
1226
+ casting='unsafe', op_dtypes='O')
1227
+ with i:
1228
+ for x in i:
1229
+ x[...] += 1
1230
+ assert_equal(a, np.arange(6) + 1)
1231
+
1232
+ # Non-contiguous object array
1233
+ a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'O')])
1234
+ a = a['a']
1235
+ a[:] = np.arange(6)
1236
+ i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
1237
+ casting='unsafe', op_dtypes='i4')
1238
+ with i:
1239
+ for x in i:
1240
+ x[...] += 1
1241
+ assert_equal(a, np.arange(6) + 1)
1242
+
1243
+ # Non-contiguous value array
1244
+ a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')])
1245
+ a = a['a']
1246
+ a[:] = np.arange(6) + 98172488
1247
+ i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'],
1248
+ casting='unsafe', op_dtypes='O')
1249
+ with i:
1250
+ ob = i[0][()]
1251
+ if HAS_REFCOUNT:
1252
+ rc = sys.getrefcount(ob)
1253
+ for x in i:
1254
+ x[...] += 1
1255
+ if HAS_REFCOUNT:
1256
+ newrc = sys.getrefcount(ob)
1257
+ assert_(newrc == rc - 1)
1258
+ assert_equal(a, np.arange(6) + 98172489)
1259
+
1260
+ def test_iter_common_dtype():
1261
+ # Check that the iterator finds a common data type correctly
1262
+ # (some checks are somewhat duplicate after adopting NEP 50)
1263
+
1264
+ i = nditer([array([3], dtype='f4'), array([0], dtype='f8')],
1265
+ ['common_dtype'],
1266
+ [['readonly', 'copy']] * 2,
1267
+ casting='safe')
1268
+ assert_equal(i.dtypes[0], np.dtype('f8'))
1269
+ assert_equal(i.dtypes[1], np.dtype('f8'))
1270
+ i = nditer([array([3], dtype='i4'), array([0], dtype='f4')],
1271
+ ['common_dtype'],
1272
+ [['readonly', 'copy']] * 2,
1273
+ casting='safe')
1274
+ assert_equal(i.dtypes[0], np.dtype('f8'))
1275
+ assert_equal(i.dtypes[1], np.dtype('f8'))
1276
+ i = nditer([array([3], dtype='f4'), array(0, dtype='f8')],
1277
+ ['common_dtype'],
1278
+ [['readonly', 'copy']] * 2,
1279
+ casting='same_kind')
1280
+ assert_equal(i.dtypes[0], np.dtype('f8'))
1281
+ assert_equal(i.dtypes[1], np.dtype('f8'))
1282
+ i = nditer([array([3], dtype='u4'), array(0, dtype='i4')],
1283
+ ['common_dtype'],
1284
+ [['readonly', 'copy']] * 2,
1285
+ casting='safe')
1286
+ assert_equal(i.dtypes[0], np.dtype('i8'))
1287
+ assert_equal(i.dtypes[1], np.dtype('i8'))
1288
+ i = nditer([array([3], dtype='u4'), array(-12, dtype='i4')],
1289
+ ['common_dtype'],
1290
+ [['readonly', 'copy']] * 2,
1291
+ casting='safe')
1292
+ assert_equal(i.dtypes[0], np.dtype('i8'))
1293
+ assert_equal(i.dtypes[1], np.dtype('i8'))
1294
+ i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'),
1295
+ array([2j], dtype='c8'), array([9], dtype='f8')],
1296
+ ['common_dtype'],
1297
+ [['readonly', 'copy']] * 4,
1298
+ casting='safe')
1299
+ assert_equal(i.dtypes[0], np.dtype('c16'))
1300
+ assert_equal(i.dtypes[1], np.dtype('c16'))
1301
+ assert_equal(i.dtypes[2], np.dtype('c16'))
1302
+ assert_equal(i.dtypes[3], np.dtype('c16'))
1303
+ assert_equal(i.value, (3, -12, 2j, 9))
1304
+
1305
+ # When allocating outputs, other outputs aren't factored in
1306
+ i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], [],
1307
+ [['readonly', 'copy'],
1308
+ ['writeonly', 'allocate'],
1309
+ ['writeonly']],
1310
+ casting='safe')
1311
+ assert_equal(i.dtypes[0], np.dtype('i4'))
1312
+ assert_equal(i.dtypes[1], np.dtype('i4'))
1313
+ assert_equal(i.dtypes[2], np.dtype('c16'))
1314
+ # But, if common data types are requested, they are
1315
+ i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')],
1316
+ ['common_dtype'],
1317
+ [['readonly', 'copy'],
1318
+ ['writeonly', 'allocate'],
1319
+ ['writeonly']],
1320
+ casting='safe')
1321
+ assert_equal(i.dtypes[0], np.dtype('c16'))
1322
+ assert_equal(i.dtypes[1], np.dtype('c16'))
1323
+ assert_equal(i.dtypes[2], np.dtype('c16'))
1324
+
1325
+ def test_iter_copy_if_overlap():
1326
+ # Ensure the iterator makes copies on read/write overlap, if requested
1327
+
1328
+ # Copy not needed, 1 op
1329
+ for flag in ['readonly', 'writeonly', 'readwrite']:
1330
+ a = arange(10)
1331
+ i = nditer([a], ['copy_if_overlap'], [[flag]])
1332
+ with i:
1333
+ assert_(i.operands[0] is a)
1334
+
1335
+ # Copy needed, 2 ops, read-write overlap
1336
+ x = arange(10)
1337
+ a = x[1:]
1338
+ b = x[:-1]
1339
+ with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['readwrite']]) as i:
1340
+ assert_(not np.shares_memory(*i.operands))
1341
+
1342
+ # Copy not needed with elementwise, 2 ops, exactly same arrays
1343
+ x = arange(10)
1344
+ a = x
1345
+ b = x
1346
+ i = nditer(
1347
+ [a, b],
1348
+ ["copy_if_overlap"],
1349
+ [
1350
+ ["readonly", "overlap_assume_elementwise"],
1351
+ ["readwrite", "overlap_assume_elementwise"],
1352
+ ],
1353
+ )
1354
+ with i:
1355
+ assert_(i.operands[0] is a and i.operands[1] is b)
1356
+ with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['readwrite']]) as i:
1357
+ assert_(i.operands[0] is a and not np.shares_memory(i.operands[1], b))
1358
+
1359
+ # Copy not needed, 2 ops, no overlap
1360
+ x = arange(10)
1361
+ a = x[::2]
1362
+ b = x[1::2]
1363
+ i = nditer([a, b], ['copy_if_overlap'], [['readonly'], ['writeonly']])
1364
+ assert_(i.operands[0] is a and i.operands[1] is b)
1365
+
1366
+ # Copy needed, 2 ops, read-write overlap
1367
+ x = arange(4, dtype=np.int8)
1368
+ a = x[3:]
1369
+ b = x.view(np.int32)[:1]
1370
+ with nditer([a, b], ['copy_if_overlap'], [['readonly'], ['writeonly']]) as i:
1371
+ assert_(not np.shares_memory(*i.operands))
1372
+
1373
+ # Copy needed, 3 ops, read-write overlap
1374
+ for flag in ['writeonly', 'readwrite']:
1375
+ x = np.ones([10, 10])
1376
+ a = x
1377
+ b = x.T
1378
+ c = x
1379
+ with nditer([a, b, c], ['copy_if_overlap'],
1380
+ [['readonly'], ['readonly'], [flag]]) as i:
1381
+ a2, b2, c2 = i.operands
1382
+ assert_(not np.shares_memory(a2, c2))
1383
+ assert_(not np.shares_memory(b2, c2))
1384
+
1385
+ # Copy not needed, 3 ops, read-only overlap
1386
+ x = np.ones([10, 10])
1387
+ a = x
1388
+ b = x.T
1389
+ c = x
1390
+ i = nditer([a, b, c], ['copy_if_overlap'],
1391
+ [['readonly'], ['readonly'], ['readonly']])
1392
+ a2, b2, c2 = i.operands
1393
+ assert_(a is a2)
1394
+ assert_(b is b2)
1395
+ assert_(c is c2)
1396
+
1397
+ # Copy not needed, 3 ops, read-only overlap
1398
+ x = np.ones([10, 10])
1399
+ a = x
1400
+ b = np.ones([10, 10])
1401
+ c = x.T
1402
+ i = nditer([a, b, c], ['copy_if_overlap'],
1403
+ [['readonly'], ['writeonly'], ['readonly']])
1404
+ a2, b2, c2 = i.operands
1405
+ assert_(a is a2)
1406
+ assert_(b is b2)
1407
+ assert_(c is c2)
1408
+
1409
+ # Copy not needed, 3 ops, write-only overlap
1410
+ x = np.arange(7)
1411
+ a = x[:3]
1412
+ b = x[3:6]
1413
+ c = x[4:7]
1414
+ i = nditer([a, b, c], ['copy_if_overlap'],
1415
+ [['readonly'], ['writeonly'], ['writeonly']])
1416
+ a2, b2, c2 = i.operands
1417
+ assert_(a is a2)
1418
+ assert_(b is b2)
1419
+ assert_(c is c2)
1420
+
1421
+ def test_iter_op_axes():
1422
+ # Check that custom axes work
1423
+
1424
+ # Reverse the axes
1425
+ a = arange(6).reshape(2, 3)
1426
+ i = nditer([a, a.T], [], [['readonly']] * 2, op_axes=[[0, 1], [1, 0]])
1427
+ assert_(all([x == y for (x, y) in i]))
1428
+ a = arange(24).reshape(2, 3, 4)
1429
+ i = nditer([a.T, a], [], [['readonly']] * 2, op_axes=[[2, 1, 0], None])
1430
+ assert_(all([x == y for (x, y) in i]))
1431
+
1432
+ # Broadcast 1D to any dimension
1433
+ a = arange(1, 31).reshape(2, 3, 5)
1434
+ b = arange(1, 3)
1435
+ i = nditer([a, b], [], [['readonly']] * 2, op_axes=[None, [0, -1, -1]])
1436
+ assert_equal([x * y for (x, y) in i], (a * b.reshape(2, 1, 1)).ravel())
1437
+ b = arange(1, 4)
1438
+ i = nditer([a, b], [], [['readonly']] * 2, op_axes=[None, [-1, 0, -1]])
1439
+ assert_equal([x * y for (x, y) in i], (a * b.reshape(1, 3, 1)).ravel())
1440
+ b = arange(1, 6)
1441
+ i = nditer([a, b], [], [['readonly']] * 2,
1442
+ op_axes=[None, [np.newaxis, np.newaxis, 0]])
1443
+ assert_equal([x * y for (x, y) in i], (a * b.reshape(1, 1, 5)).ravel())
1444
+
1445
+ # Inner product-style broadcasting
1446
+ a = arange(24).reshape(2, 3, 4)
1447
+ b = arange(40).reshape(5, 2, 4)
1448
+ i = nditer([a, b], ['multi_index'], [['readonly']] * 2,
1449
+ op_axes=[[0, 1, -1, -1], [-1, -1, 0, 1]])
1450
+ assert_equal(i.shape, (2, 3, 5, 2))
1451
+
1452
+ # Matrix product-style broadcasting
1453
+ a = arange(12).reshape(3, 4)
1454
+ b = arange(20).reshape(4, 5)
1455
+ i = nditer([a, b], ['multi_index'], [['readonly']] * 2,
1456
+ op_axes=[[0, -1], [-1, 1]])
1457
+ assert_equal(i.shape, (3, 5))
1458
+
1459
+ def test_iter_op_axes_errors():
1460
+ # Check that custom axes throws errors for bad inputs
1461
+
1462
+ # Wrong number of items in op_axes
1463
+ a = arange(6).reshape(2, 3)
1464
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1465
+ op_axes=[[0], [1], [0]])
1466
+ # Out of bounds items in op_axes
1467
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1468
+ op_axes=[[2, 1], [0, 1]])
1469
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1470
+ op_axes=[[0, 1], [2, -1]])
1471
+ # Duplicate items in op_axes
1472
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1473
+ op_axes=[[0, 0], [0, 1]])
1474
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1475
+ op_axes=[[0, 1], [1, 1]])
1476
+
1477
+ # Different sized arrays in op_axes
1478
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1479
+ op_axes=[[0, 1], [0, 1, 0]])
1480
+
1481
+ # Non-broadcastable dimensions in the result
1482
+ assert_raises(ValueError, nditer, [a, a], [], [['readonly']] * 2,
1483
+ op_axes=[[0, 1], [1, 0]])
1484
+
1485
+ def test_iter_copy():
1486
+ # Check that copying the iterator works correctly
1487
+ a = arange(24).reshape(2, 3, 4)
1488
+
1489
+ # Simple iterator
1490
+ i = nditer(a)
1491
+ j = i.copy()
1492
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1493
+
1494
+ i.iterindex = 3
1495
+ j = i.copy()
1496
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1497
+
1498
+ # Buffered iterator
1499
+ i = nditer(a, ['buffered', 'ranged'], order='F', buffersize=3)
1500
+ j = i.copy()
1501
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1502
+
1503
+ i.iterindex = 3
1504
+ j = i.copy()
1505
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1506
+
1507
+ i.iterrange = (3, 9)
1508
+ j = i.copy()
1509
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1510
+
1511
+ i.iterrange = (2, 18)
1512
+ next(i)
1513
+ next(i)
1514
+ j = i.copy()
1515
+ assert_equal([x[()] for x in i], [x[()] for x in j])
1516
+
1517
+ # Casting iterator
1518
+ with nditer(a, ['buffered'], order='F', casting='unsafe',
1519
+ op_dtypes='f8', buffersize=5) as i:
1520
+ j = i.copy()
1521
+ assert_equal([x[()] for x in j], a.ravel(order='F'))
1522
+
1523
+ a = arange(24, dtype='<i4').reshape(2, 3, 4)
1524
+ with nditer(a, ['buffered'], order='F', casting='unsafe',
1525
+ op_dtypes='>f8', buffersize=5) as i:
1526
+ j = i.copy()
1527
+ assert_equal([x[()] for x in j], a.ravel(order='F'))
1528
+
1529
+
1530
+ @pytest.mark.parametrize("dtype", np.typecodes["All"])
1531
+ @pytest.mark.parametrize("loop_dtype", np.typecodes["All"])
1532
+ @pytest.mark.filterwarnings(
1533
+ "ignore::numpy.exceptions.ComplexWarning",
1534
+ "ignore::DeprecationWarning",
1535
+ )
1536
+ def test_iter_copy_casts(dtype, loop_dtype):
1537
+ # Ensure the dtype is never flexible:
1538
+ if loop_dtype.lower() == "m":
1539
+ loop_dtype = loop_dtype + "[ms]"
1540
+ elif np.dtype(loop_dtype).itemsize == 0:
1541
+ loop_dtype = loop_dtype + "50"
1542
+
1543
+ # Make things a bit more interesting by requiring a byte-swap as well:
1544
+ arr = np.ones(1000, dtype=np.dtype(dtype).newbyteorder())
1545
+ try:
1546
+ expected = arr.astype(loop_dtype)
1547
+ except Exception:
1548
+ # Some casts are not possible, do not worry about them
1549
+ return
1550
+
1551
+ it = np.nditer((arr,), ["buffered", "external_loop", "refs_ok"],
1552
+ op_dtypes=[loop_dtype], casting="unsafe")
1553
+
1554
+ if np.issubdtype(np.dtype(loop_dtype), np.number):
1555
+ # Casting to strings may be strange, but for simple dtypes do not rely
1556
+ # on the cast being correct:
1557
+ assert_array_equal(expected, np.ones(1000, dtype=loop_dtype))
1558
+
1559
+ it_copy = it.copy()
1560
+ res = next(it)
1561
+ del it
1562
+ res_copy = next(it_copy)
1563
+ del it_copy
1564
+
1565
+ assert_array_equal(res, expected)
1566
+ assert_array_equal(res_copy, expected)
1567
+
1568
+
1569
+ def test_iter_copy_casts_structured():
1570
+ # Test a complicated structured dtype for casting, as it requires
1571
+ # both multiple steps and a more complex casting setup.
1572
+ # Includes a structured -> unstructured (any to object), and many other
1573
+ # casts, which cause this to require all steps in the casting machinery
1574
+ # one level down as well as the iterator copy (which uses NpyAuxData clone)
1575
+ in_dtype = np.dtype([("a", np.dtype("i,")),
1576
+ ("b", np.dtype(">i,<i,>d,S17,>d,3f,O,i1"))])
1577
+ out_dtype = np.dtype([("a", np.dtype("O")),
1578
+ ("b", np.dtype(">i,>i,S17,>d,>U3,3d,i1,O"))])
1579
+ arr = np.ones(1000, dtype=in_dtype)
1580
+
1581
+ it = np.nditer((arr,), ["buffered", "external_loop", "refs_ok"],
1582
+ op_dtypes=[out_dtype], casting="unsafe")
1583
+ it_copy = it.copy()
1584
+
1585
+ res1 = next(it)
1586
+ del it
1587
+ res2 = next(it_copy)
1588
+ del it_copy
1589
+
1590
+ expected = arr["a"].astype(out_dtype["a"])
1591
+ assert_array_equal(res1["a"], expected)
1592
+ assert_array_equal(res2["a"], expected)
1593
+
1594
+ for field in in_dtype["b"].names:
1595
+ # Note that the .base avoids the subarray field
1596
+ expected = arr["b"][field].astype(out_dtype["b"][field].base)
1597
+ assert_array_equal(res1["b"][field], expected)
1598
+ assert_array_equal(res2["b"][field], expected)
1599
+
1600
+
1601
+ def test_iter_copy_casts_structured2():
1602
+ # Similar to the above, this is a fairly arcane test to cover internals
1603
+ in_dtype = np.dtype([("a", np.dtype("O,O")),
1604
+ ("b", np.dtype("5O,3O,(1,)O,(1,)i,(1,)O"))])
1605
+ out_dtype = np.dtype([("a", np.dtype("O")),
1606
+ ("b", np.dtype("O,3i,4O,4O,4i"))])
1607
+
1608
+ arr = np.ones(1, dtype=in_dtype)
1609
+ it = np.nditer((arr,), ["buffered", "external_loop", "refs_ok"],
1610
+ op_dtypes=[out_dtype], casting="unsafe")
1611
+ it_copy = it.copy()
1612
+
1613
+ res1 = next(it)
1614
+ del it
1615
+ res2 = next(it_copy)
1616
+ del it_copy
1617
+
1618
+ # Array of two structured scalars:
1619
+ for res in res1, res2:
1620
+ # Cast to tuple by getitem, which may be weird and changeable?:
1621
+ assert isinstance(res["a"][0], tuple)
1622
+ assert res["a"][0] == (1, 1)
1623
+
1624
+ for res in res1, res2:
1625
+ assert_array_equal(res["b"]["f0"][0], np.ones(5, dtype=object))
1626
+ assert_array_equal(res["b"]["f1"], np.ones((1, 3), dtype="i"))
1627
+ assert res["b"]["f2"].shape == (1, 4)
1628
+ assert_array_equal(res["b"]["f2"][0], np.ones(4, dtype=object))
1629
+ assert_array_equal(res["b"]["f3"][0], np.ones(4, dtype=object))
1630
+ assert_array_equal(res["b"]["f3"][0], np.ones(4, dtype="i"))
1631
+
1632
+
1633
+ def test_iter_allocate_output_simple():
1634
+ # Check that the iterator will properly allocate outputs
1635
+
1636
+ # Simple case
1637
+ a = arange(6)
1638
+ i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
1639
+ op_dtypes=[None, np.dtype('f4')])
1640
+ assert_equal(i.operands[1].shape, a.shape)
1641
+ assert_equal(i.operands[1].dtype, np.dtype('f4'))
1642
+
1643
+ def test_iter_allocate_output_buffered_readwrite():
1644
+ # Allocated output with buffering + delay_bufalloc
1645
+
1646
+ a = arange(6)
1647
+ i = nditer([a, None], ['buffered', 'delay_bufalloc'],
1648
+ [['readonly'], ['allocate', 'readwrite']])
1649
+ with i:
1650
+ i.operands[1][:] = 1
1651
+ i.reset()
1652
+ for x in i:
1653
+ x[1][...] += x[0][...]
1654
+ assert_equal(i.operands[1], a + 1)
1655
+
1656
+ def test_iter_allocate_output_itorder():
1657
+ # The allocated output should match the iteration order
1658
+
1659
+ # C-order input, best iteration order
1660
+ a = arange(6, dtype='i4').reshape(2, 3)
1661
+ i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
1662
+ op_dtypes=[None, np.dtype('f4')])
1663
+ assert_equal(i.operands[1].shape, a.shape)
1664
+ assert_equal(i.operands[1].strides, a.strides)
1665
+ assert_equal(i.operands[1].dtype, np.dtype('f4'))
1666
+ # F-order input, best iteration order
1667
+ a = arange(24, dtype='i4').reshape(2, 3, 4).T
1668
+ i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']],
1669
+ op_dtypes=[None, np.dtype('f4')])
1670
+ assert_equal(i.operands[1].shape, a.shape)
1671
+ assert_equal(i.operands[1].strides, a.strides)
1672
+ assert_equal(i.operands[1].dtype, np.dtype('f4'))
1673
+ # Non-contiguous input, C iteration order
1674
+ a = arange(24, dtype='i4').reshape(2, 3, 4).swapaxes(0, 1)
1675
+ i = nditer([a, None], [],
1676
+ [['readonly'], ['writeonly', 'allocate']],
1677
+ order='C',
1678
+ op_dtypes=[None, np.dtype('f4')])
1679
+ assert_equal(i.operands[1].shape, a.shape)
1680
+ assert_equal(i.operands[1].strides, (32, 16, 4))
1681
+ assert_equal(i.operands[1].dtype, np.dtype('f4'))
1682
+
1683
+ def test_iter_allocate_output_opaxes():
1684
+ # Specifying op_axes should work
1685
+
1686
+ a = arange(24, dtype='i4').reshape(2, 3, 4)
1687
+ i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']],
1688
+ op_dtypes=[np.dtype('u4'), None],
1689
+ op_axes=[[1, 2, 0], None])
1690
+ assert_equal(i.operands[0].shape, (4, 2, 3))
1691
+ assert_equal(i.operands[0].strides, (4, 48, 16))
1692
+ assert_equal(i.operands[0].dtype, np.dtype('u4'))
1693
+
1694
+ def test_iter_allocate_output_types_promotion():
1695
+ # Check type promotion of automatic outputs (this was more interesting
1696
+ # before NEP 50...)
1697
+
1698
+ i = nditer([array([3], dtype='f4'), array([0], dtype='f8'), None], [],
1699
+ [['readonly']] * 2 + [['writeonly', 'allocate']])
1700
+ assert_equal(i.dtypes[2], np.dtype('f8'))
1701
+ i = nditer([array([3], dtype='i4'), array([0], dtype='f4'), None], [],
1702
+ [['readonly']] * 2 + [['writeonly', 'allocate']])
1703
+ assert_equal(i.dtypes[2], np.dtype('f8'))
1704
+ i = nditer([array([3], dtype='f4'), array(0, dtype='f8'), None], [],
1705
+ [['readonly']] * 2 + [['writeonly', 'allocate']])
1706
+ assert_equal(i.dtypes[2], np.dtype('f8'))
1707
+ i = nditer([array([3], dtype='u4'), array(0, dtype='i4'), None], [],
1708
+ [['readonly']] * 2 + [['writeonly', 'allocate']])
1709
+ assert_equal(i.dtypes[2], np.dtype('i8'))
1710
+ i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), None], [],
1711
+ [['readonly']] * 2 + [['writeonly', 'allocate']])
1712
+ assert_equal(i.dtypes[2], np.dtype('i8'))
1713
+
1714
+ def test_iter_allocate_output_types_byte_order():
1715
+ # Verify the rules for byte order changes
1716
+
1717
+ # When there's just one input, the output type exactly matches
1718
+ a = array([3], dtype='u4')
1719
+ a = a.view(a.dtype.newbyteorder())
1720
+ i = nditer([a, None], [],
1721
+ [['readonly'], ['writeonly', 'allocate']])
1722
+ assert_equal(i.dtypes[0], i.dtypes[1])
1723
+ # With two or more inputs, the output type is in native byte order
1724
+ i = nditer([a, a, None], [],
1725
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
1726
+ assert_(i.dtypes[0] != i.dtypes[2])
1727
+ assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2])
1728
+
1729
+ def test_iter_allocate_output_types_scalar():
1730
+ # If the inputs are all scalars, the output should be a scalar
1731
+
1732
+ i = nditer([None, 1, 2.3, np.float32(12), np.complex128(3)], [],
1733
+ [['writeonly', 'allocate']] + [['readonly']] * 4)
1734
+ assert_equal(i.operands[0].dtype, np.dtype('complex128'))
1735
+ assert_equal(i.operands[0].ndim, 0)
1736
+
1737
+ def test_iter_allocate_output_subtype():
1738
+ # Make sure that the subtype with priority wins
1739
+ class MyNDArray(np.ndarray):
1740
+ __array_priority__ = 15
1741
+
1742
+ # subclass vs ndarray
1743
+ a = np.array([[1, 2], [3, 4]]).view(MyNDArray)
1744
+ b = np.arange(4).reshape(2, 2).T
1745
+ i = nditer([a, b, None], [],
1746
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
1747
+ assert_equal(type(a), type(i.operands[2]))
1748
+ assert_(type(b) is not type(i.operands[2]))
1749
+ assert_equal(i.operands[2].shape, (2, 2))
1750
+
1751
+ # If subtypes are disabled, we should get back an ndarray.
1752
+ i = nditer([a, b, None], [],
1753
+ [['readonly'], ['readonly'],
1754
+ ['writeonly', 'allocate', 'no_subtype']])
1755
+ assert_equal(type(b), type(i.operands[2]))
1756
+ assert_(type(a) is not type(i.operands[2]))
1757
+ assert_equal(i.operands[2].shape, (2, 2))
1758
+
1759
+ def test_iter_allocate_output_errors():
1760
+ # Check that the iterator will throw errors for bad output allocations
1761
+
1762
+ # Need an input if no output data type is specified
1763
+ a = arange(6)
1764
+ assert_raises(TypeError, nditer, [a, None], [],
1765
+ [['writeonly'], ['writeonly', 'allocate']])
1766
+ # Allocated output should be flagged for writing
1767
+ assert_raises(ValueError, nditer, [a, None], [],
1768
+ [['readonly'], ['allocate', 'readonly']])
1769
+ # Allocated output can't have buffering without delayed bufalloc
1770
+ assert_raises(ValueError, nditer, [a, None], ['buffered'],
1771
+ ['allocate', 'readwrite'])
1772
+ # Must specify dtype if there are no inputs (cannot promote existing ones;
1773
+ # maybe this should use the 'f4' here, but it does not historically.)
1774
+ assert_raises(TypeError, nditer, [None, None], [],
1775
+ [['writeonly', 'allocate'],
1776
+ ['writeonly', 'allocate']],
1777
+ op_dtypes=[None, np.dtype('f4')])
1778
+ # If using op_axes, must specify all the axes
1779
+ a = arange(24, dtype='i4').reshape(2, 3, 4)
1780
+ assert_raises(ValueError, nditer, [a, None], [],
1781
+ [['readonly'], ['writeonly', 'allocate']],
1782
+ op_dtypes=[None, np.dtype('f4')],
1783
+ op_axes=[None, [0, np.newaxis, 1]])
1784
+ # If using op_axes, the axes must be within bounds
1785
+ assert_raises(ValueError, nditer, [a, None], [],
1786
+ [['readonly'], ['writeonly', 'allocate']],
1787
+ op_dtypes=[None, np.dtype('f4')],
1788
+ op_axes=[None, [0, 3, 1]])
1789
+ # If using op_axes, there can't be duplicates
1790
+ assert_raises(ValueError, nditer, [a, None], [],
1791
+ [['readonly'], ['writeonly', 'allocate']],
1792
+ op_dtypes=[None, np.dtype('f4')],
1793
+ op_axes=[None, [0, 2, 1, 0]])
1794
+ # Not all axes may be specified if a reduction. If there is a hole
1795
+ # in op_axes, this is an error.
1796
+ a = arange(24, dtype='i4').reshape(2, 3, 4)
1797
+ assert_raises(ValueError, nditer, [a, None], ["reduce_ok"],
1798
+ [['readonly'], ['readwrite', 'allocate']],
1799
+ op_dtypes=[None, np.dtype('f4')],
1800
+ op_axes=[None, [0, np.newaxis, 2]])
1801
+
1802
+ def test_all_allocated():
1803
+ # When no output and no shape is given, `()` is used as shape.
1804
+ i = np.nditer([None], op_dtypes=["int64"])
1805
+ assert i.operands[0].shape == ()
1806
+ assert i.dtypes == (np.dtype("int64"),)
1807
+
1808
+ i = np.nditer([None], op_dtypes=["int64"], itershape=(2, 3, 4))
1809
+ assert i.operands[0].shape == (2, 3, 4)
1810
+
1811
+ def test_iter_remove_axis():
1812
+ a = arange(24).reshape(2, 3, 4)
1813
+
1814
+ i = nditer(a, ['multi_index'])
1815
+ i.remove_axis(1)
1816
+ assert_equal(list(i), a[:, 0, :].ravel())
1817
+
1818
+ a = a[::-1, :, :]
1819
+ i = nditer(a, ['multi_index'])
1820
+ i.remove_axis(0)
1821
+ assert_equal(list(i), a[0, :, :].ravel())
1822
+
1823
+ def test_iter_remove_multi_index_inner_loop():
1824
+ # Check that removing multi-index support works
1825
+
1826
+ a = arange(24).reshape(2, 3, 4)
1827
+
1828
+ i = nditer(a, ['multi_index'])
1829
+ assert_equal(i.ndim, 3)
1830
+ assert_equal(i.shape, (2, 3, 4))
1831
+ assert_equal(i.itviews[0].shape, (2, 3, 4))
1832
+
1833
+ # Removing the multi-index tracking causes all dimensions to coalesce
1834
+ before = list(i)
1835
+ i.remove_multi_index()
1836
+ after = list(i)
1837
+
1838
+ assert_equal(before, after)
1839
+ assert_equal(i.ndim, 1)
1840
+ assert_raises(ValueError, lambda i: i.shape, i)
1841
+ assert_equal(i.itviews[0].shape, (24,))
1842
+
1843
+ # Removing the inner loop means there's just one iteration
1844
+ i.reset()
1845
+ assert_equal(i.itersize, 24)
1846
+ assert_equal(i[0].shape, ())
1847
+ i.enable_external_loop()
1848
+ assert_equal(i.itersize, 24)
1849
+ assert_equal(i[0].shape, (24,))
1850
+ assert_equal(i.value, arange(24))
1851
+
1852
+
1853
+ def test_iter_remove_multi_index_buffered():
1854
+ a = arange(10).reshape(10, 1)
1855
+ i = nditer(a, ["buffered", "multi_index"], buffersize=5)
1856
+
1857
+ i.remove_multi_index()
1858
+ i.enable_external_loop()
1859
+
1860
+ assert_equal(i.ndim, 1)
1861
+ assert_array_equal(np.concatenate([chunk.copy() for chunk in i]), a.ravel())
1862
+
1863
+
1864
+ def test_iter_iterindex():
1865
+ # Make sure iterindex works
1866
+
1867
+ buffersize = 5
1868
+ a = arange(24).reshape(4, 3, 2)
1869
+ for flags in ([], ['buffered']):
1870
+ i = nditer(a, flags, buffersize=buffersize)
1871
+ assert_equal(iter_iterindices(i), list(range(24)))
1872
+ i.iterindex = 2
1873
+ assert_equal(iter_iterindices(i), list(range(2, 24)))
1874
+
1875
+ i = nditer(a, flags, order='F', buffersize=buffersize)
1876
+ assert_equal(iter_iterindices(i), list(range(24)))
1877
+ i.iterindex = 5
1878
+ assert_equal(iter_iterindices(i), list(range(5, 24)))
1879
+
1880
+ i = nditer(a[::-1], flags, order='F', buffersize=buffersize)
1881
+ assert_equal(iter_iterindices(i), list(range(24)))
1882
+ i.iterindex = 9
1883
+ assert_equal(iter_iterindices(i), list(range(9, 24)))
1884
+
1885
+ i = nditer(a[::-1, ::-1], flags, order='C', buffersize=buffersize)
1886
+ assert_equal(iter_iterindices(i), list(range(24)))
1887
+ i.iterindex = 13
1888
+ assert_equal(iter_iterindices(i), list(range(13, 24)))
1889
+
1890
+ i = nditer(a[::1, ::-1], flags, buffersize=buffersize)
1891
+ assert_equal(iter_iterindices(i), list(range(24)))
1892
+ i.iterindex = 23
1893
+ assert_equal(iter_iterindices(i), list(range(23, 24)))
1894
+ i.reset()
1895
+ i.iterindex = 2
1896
+ assert_equal(iter_iterindices(i), list(range(2, 24)))
1897
+
1898
+ def test_iter_iterrange():
1899
+ # Make sure getting and resetting the iterrange works
1900
+
1901
+ buffersize = 5
1902
+ a = arange(24, dtype='i4').reshape(4, 3, 2)
1903
+ a_fort = a.ravel(order='F')
1904
+
1905
+ i = nditer(a, ['ranged'], ['readonly'], order='F',
1906
+ buffersize=buffersize)
1907
+ assert_equal(i.iterrange, (0, 24))
1908
+ assert_equal([x[()] for x in i], a_fort)
1909
+ for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
1910
+ i.iterrange = r
1911
+ assert_equal(i.iterrange, r)
1912
+ assert_equal([x[()] for x in i], a_fort[r[0]:r[1]])
1913
+
1914
+ i = nditer(a, ['ranged', 'buffered'], ['readonly'], order='F',
1915
+ op_dtypes='f8', buffersize=buffersize)
1916
+ assert_equal(i.iterrange, (0, 24))
1917
+ assert_equal([x[()] for x in i], a_fort)
1918
+ for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
1919
+ i.iterrange = r
1920
+ assert_equal(i.iterrange, r)
1921
+ assert_equal([x[()] for x in i], a_fort[r[0]:r[1]])
1922
+
1923
+ def get_array(i):
1924
+ val = np.array([], dtype='f8')
1925
+ for x in i:
1926
+ val = np.concatenate((val, x))
1927
+ return val
1928
+
1929
+ i = nditer(a, ['ranged', 'buffered', 'external_loop'],
1930
+ ['readonly'], order='F',
1931
+ op_dtypes='f8', buffersize=buffersize)
1932
+ assert_equal(i.iterrange, (0, 24))
1933
+ assert_equal(get_array(i), a_fort)
1934
+ for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]:
1935
+ i.iterrange = r
1936
+ assert_equal(i.iterrange, r)
1937
+ assert_equal(get_array(i), a_fort[r[0]:r[1]])
1938
+
1939
+ def test_iter_buffering():
1940
+ # Test buffering with several buffer sizes and types
1941
+ arrays = []
1942
+ # F-order swapped array
1943
+ _tmp = np.arange(24, dtype='c16').reshape(2, 3, 4).T
1944
+ _tmp = _tmp.view(_tmp.dtype.newbyteorder()).byteswap()
1945
+ arrays.append(_tmp)
1946
+ # Contiguous 1-dimensional array
1947
+ arrays.append(np.arange(10, dtype='f4'))
1948
+ # Unaligned array
1949
+ a = np.zeros((4 * 16 + 1,), dtype='i1')[1:]
1950
+ a = a.view('i4')
1951
+ a[:] = np.arange(16, dtype='i4')
1952
+ arrays.append(a)
1953
+ # 4-D F-order array
1954
+ arrays.append(np.arange(120, dtype='i4').reshape(5, 3, 2, 4).T)
1955
+ for a in arrays:
1956
+ for buffersize in (1, 2, 3, 5, 8, 11, 16, 1024):
1957
+ vals = []
1958
+ i = nditer(a, ['buffered', 'external_loop'],
1959
+ [['readonly', 'nbo', 'aligned']],
1960
+ order='C',
1961
+ casting='equiv',
1962
+ buffersize=buffersize)
1963
+ while not i.finished:
1964
+ assert_(i[0].size <= buffersize)
1965
+ vals.append(i[0].copy())
1966
+ i.iternext()
1967
+ assert_equal(np.concatenate(vals), a.ravel(order='C'))
1968
+
1969
+ def test_iter_write_buffering():
1970
+ # Test that buffering of writes is working
1971
+
1972
+ # F-order swapped array
1973
+ a = np.arange(24).reshape(2, 3, 4).T
1974
+ a = a.view(a.dtype.newbyteorder()).byteswap()
1975
+ i = nditer(a, ['buffered'],
1976
+ [['readwrite', 'nbo', 'aligned']],
1977
+ casting='equiv',
1978
+ order='C',
1979
+ buffersize=16)
1980
+ x = 0
1981
+ with i:
1982
+ while not i.finished:
1983
+ i[0] = x
1984
+ x += 1
1985
+ i.iternext()
1986
+ assert_equal(a.ravel(order='C'), np.arange(24))
1987
+
1988
+ def test_iter_buffering_delayed_alloc():
1989
+ # Test that delaying buffer allocation works
1990
+
1991
+ a = np.arange(6)
1992
+ b = np.arange(1, dtype='f4')
1993
+ i = nditer([a, b], ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok'],
1994
+ ['readwrite'],
1995
+ casting='unsafe',
1996
+ op_dtypes='f4')
1997
+ assert_(i.has_delayed_bufalloc)
1998
+ assert_raises(ValueError, lambda i: i.multi_index, i)
1999
+ assert_raises(ValueError, lambda i: i[0], i)
2000
+ assert_raises(ValueError, lambda i: i[0:2], i)
2001
+
2002
+ def assign_iter(i):
2003
+ i[0] = 0
2004
+ assert_raises(ValueError, assign_iter, i)
2005
+
2006
+ i.reset()
2007
+ assert_(not i.has_delayed_bufalloc)
2008
+ assert_equal(i.multi_index, (0,))
2009
+ with i:
2010
+ assert_equal(i[0], 0)
2011
+ i[1] = 1
2012
+ assert_equal(i[0:2], [0, 1])
2013
+ assert_equal([[x[0][()], x[1][()]] for x in i], list(zip(range(6), [1] * 6)))
2014
+
2015
+ def test_iter_buffered_cast_simple():
2016
+ # Test that buffering can handle a simple cast
2017
+
2018
+ a = np.arange(10, dtype='f4')
2019
+ i = nditer(a, ['buffered', 'external_loop'],
2020
+ [['readwrite', 'nbo', 'aligned']],
2021
+ casting='same_kind',
2022
+ op_dtypes=[np.dtype('f8')],
2023
+ buffersize=3)
2024
+ with i:
2025
+ for v in i:
2026
+ v[...] *= 2
2027
+
2028
+ assert_equal(a, 2 * np.arange(10, dtype='f4'))
2029
+
2030
+ def test_iter_buffered_cast_byteswapped():
2031
+ # Test that buffering can handle a cast which requires swap->cast->swap
2032
+
2033
+ a = np.arange(10, dtype='f4')
2034
+ a = a.view(a.dtype.newbyteorder()).byteswap()
2035
+ i = nditer(a, ['buffered', 'external_loop'],
2036
+ [['readwrite', 'nbo', 'aligned']],
2037
+ casting='same_kind',
2038
+ op_dtypes=[np.dtype('f8').newbyteorder()],
2039
+ buffersize=3)
2040
+ with i:
2041
+ for v in i:
2042
+ v[...] *= 2
2043
+
2044
+ assert_equal(a, 2 * np.arange(10, dtype='f4'))
2045
+
2046
+ with warnings.catch_warnings():
2047
+ warnings.simplefilter('ignore', np.exceptions.ComplexWarning)
2048
+
2049
+ a = np.arange(10, dtype='f8')
2050
+ a = a.view(a.dtype.newbyteorder()).byteswap()
2051
+ i = nditer(a, ['buffered', 'external_loop'],
2052
+ [['readwrite', 'nbo', 'aligned']],
2053
+ casting='unsafe',
2054
+ op_dtypes=[np.dtype('c8').newbyteorder()],
2055
+ buffersize=3)
2056
+ with i:
2057
+ for v in i:
2058
+ v[...] *= 2
2059
+
2060
+ assert_equal(a, 2 * np.arange(10, dtype='f8'))
2061
+
2062
+ def test_iter_buffered_cast_byteswapped_complex():
2063
+ # Test that buffering can handle a cast which requires swap->cast->copy
2064
+
2065
+ a = np.arange(10, dtype='c8')
2066
+ a = a.view(a.dtype.newbyteorder()).byteswap()
2067
+ a += 2j
2068
+ i = nditer(a, ['buffered', 'external_loop'],
2069
+ [['readwrite', 'nbo', 'aligned']],
2070
+ casting='same_kind',
2071
+ op_dtypes=[np.dtype('c16')],
2072
+ buffersize=3)
2073
+ with i:
2074
+ for v in i:
2075
+ v[...] *= 2
2076
+ assert_equal(a, 2 * np.arange(10, dtype='c8') + 4j)
2077
+
2078
+ a = np.arange(10, dtype='c8')
2079
+ a += 2j
2080
+ i = nditer(a, ['buffered', 'external_loop'],
2081
+ [['readwrite', 'nbo', 'aligned']],
2082
+ casting='same_kind',
2083
+ op_dtypes=[np.dtype('c16').newbyteorder()],
2084
+ buffersize=3)
2085
+ with i:
2086
+ for v in i:
2087
+ v[...] *= 2
2088
+ assert_equal(a, 2 * np.arange(10, dtype='c8') + 4j)
2089
+
2090
+ a = np.arange(10, dtype=np.clongdouble)
2091
+ a = a.view(a.dtype.newbyteorder()).byteswap()
2092
+ a += 2j
2093
+ i = nditer(a, ['buffered', 'external_loop'],
2094
+ [['readwrite', 'nbo', 'aligned']],
2095
+ casting='same_kind',
2096
+ op_dtypes=[np.dtype('c16')],
2097
+ buffersize=3)
2098
+ with i:
2099
+ for v in i:
2100
+ v[...] *= 2
2101
+ assert_equal(a, 2 * np.arange(10, dtype=np.clongdouble) + 4j)
2102
+
2103
+ a = np.arange(10, dtype=np.longdouble)
2104
+ a = a.view(a.dtype.newbyteorder()).byteswap()
2105
+ i = nditer(a, ['buffered', 'external_loop'],
2106
+ [['readwrite', 'nbo', 'aligned']],
2107
+ casting='same_kind',
2108
+ op_dtypes=[np.dtype('f4')],
2109
+ buffersize=7)
2110
+ with i:
2111
+ for v in i:
2112
+ v[...] *= 2
2113
+ assert_equal(a, 2 * np.arange(10, dtype=np.longdouble))
2114
+
2115
+ def test_iter_buffered_cast_structured_type():
2116
+ # Tests buffering of structured types
2117
+
2118
+ # simple -> struct type (duplicates the value)
2119
+ sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
2120
+ a = np.arange(3, dtype='f4') + 0.5
2121
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2122
+ casting='unsafe',
2123
+ op_dtypes=sdt)
2124
+ vals = [np.array(x) for x in i]
2125
+ assert_equal(vals[0]['a'], 0.5)
2126
+ assert_equal(vals[0]['b'], 0)
2127
+ assert_equal(vals[0]['c'], [[(0.5)] * 3] * 2)
2128
+ assert_equal(vals[0]['d'], 0.5)
2129
+ assert_equal(vals[1]['a'], 1.5)
2130
+ assert_equal(vals[1]['b'], 1)
2131
+ assert_equal(vals[1]['c'], [[(1.5)] * 3] * 2)
2132
+ assert_equal(vals[1]['d'], 1.5)
2133
+ assert_equal(vals[0].dtype, np.dtype(sdt))
2134
+
2135
+ # object -> struct type
2136
+ sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
2137
+ a = np.zeros((3,), dtype='O')
2138
+ a[0] = (0.5, 0.5, [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]], 0.5)
2139
+ a[1] = (1.5, 1.5, [[1.5, 1.5, 1.5], [1.5, 1.5, 1.5]], 1.5)
2140
+ a[2] = (2.5, 2.5, [[2.5, 2.5, 2.5], [2.5, 2.5, 2.5]], 2.5)
2141
+ if HAS_REFCOUNT:
2142
+ rc = sys.getrefcount(a[0])
2143
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2144
+ casting='unsafe',
2145
+ op_dtypes=sdt)
2146
+ vals = [x.copy() for x in i]
2147
+ assert_equal(vals[0]['a'], 0.5)
2148
+ assert_equal(vals[0]['b'], 0)
2149
+ assert_equal(vals[0]['c'], [[(0.5)] * 3] * 2)
2150
+ assert_equal(vals[0]['d'], 0.5)
2151
+ assert_equal(vals[1]['a'], 1.5)
2152
+ assert_equal(vals[1]['b'], 1)
2153
+ assert_equal(vals[1]['c'], [[(1.5)] * 3] * 2)
2154
+ assert_equal(vals[1]['d'], 1.5)
2155
+ assert_equal(vals[0].dtype, np.dtype(sdt))
2156
+ vals, i, x = [None] * 3
2157
+ if HAS_REFCOUNT:
2158
+ assert_equal(sys.getrefcount(a[0]), rc)
2159
+
2160
+ # single-field struct type -> simple
2161
+ sdt = [('a', 'f4')]
2162
+ a = np.array([(5.5,), (8,)], dtype=sdt)
2163
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2164
+ casting='unsafe',
2165
+ op_dtypes='i4')
2166
+ assert_equal([x_[()] for x_ in i], [5, 8])
2167
+
2168
+ # make sure multi-field struct type -> simple doesn't work
2169
+ sdt = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
2170
+ a = np.array([(5.5, 7, 'test'), (8, 10, 11)], dtype=sdt)
2171
+ assert_raises(TypeError, lambda: (
2172
+ nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2173
+ casting='unsafe',
2174
+ op_dtypes='i4')))
2175
+
2176
+ # struct type -> struct type (field-wise copy)
2177
+ sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
2178
+ sdt2 = [('d', 'u2'), ('a', 'O'), ('b', 'f8')]
2179
+ a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1)
2180
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2181
+ casting='unsafe',
2182
+ op_dtypes=sdt2)
2183
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2184
+ assert_equal([np.array(x_) for x_ in i],
2185
+ [np.array((1, 2, 3), dtype=sdt2),
2186
+ np.array((4, 5, 6), dtype=sdt2)])
2187
+
2188
+
2189
+ def test_iter_buffered_cast_structured_type_failure_with_cleanup():
2190
+ # make sure struct type -> struct type with different
2191
+ # number of fields fails
2192
+ sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')]
2193
+ sdt2 = [('b', 'O'), ('a', 'f8')]
2194
+ a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1)
2195
+
2196
+ for intent in ["readwrite", "readonly", "writeonly"]:
2197
+ # This test was initially designed to test an error at a different
2198
+ # place, but will now raise earlier due to the cast not being possible:
2199
+ # `assert np.can_cast(a.dtype, sdt2, casting="unsafe")` fails.
2200
+ # Without a faulty DType, there is probably no reliable
2201
+ # way to get the initial tested behaviour.
2202
+ simple_arr = np.array([1, 2], dtype="i,i") # requires clean up
2203
+ with pytest.raises(TypeError):
2204
+ nditer((simple_arr, a), ['buffered', 'refs_ok'], [intent, intent],
2205
+ casting='unsafe', op_dtypes=["f,f", sdt2])
2206
+
2207
+
2208
+ def test_buffered_cast_error_paths():
2209
+ with pytest.raises(ValueError):
2210
+ # The input is cast into an `S3` buffer
2211
+ np.nditer((np.array("a", dtype="S1"),), op_dtypes=["i"],
2212
+ casting="unsafe", flags=["buffered"])
2213
+
2214
+ # The `M8[ns]` is cast into the `S3` output
2215
+ it = np.nditer((np.array(1, dtype="i"),), op_dtypes=["S1"],
2216
+ op_flags=["writeonly"], casting="unsafe", flags=["buffered"])
2217
+ with pytest.raises(ValueError):
2218
+ with it:
2219
+ buf = next(it)
2220
+ buf[...] = "a" # cannot be converted to int.
2221
+
2222
+ @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
2223
+ def test_buffered_cast_error_paths_unraisable():
2224
+ # The following gives an unraisable error. Pytest sometimes captures that
2225
+ # (depending python and/or pytest version). So with Python>=3.8 this can
2226
+ # probably be cleaned out in the future to check for
2227
+ # pytest.PytestUnraisableExceptionWarning:
2228
+ code = textwrap.dedent("""
2229
+ import numpy as np
2230
+
2231
+ it = np.nditer((np.array(1, dtype="i"),), op_dtypes=["S1"],
2232
+ op_flags=["writeonly"], casting="unsafe", flags=["buffered"])
2233
+ buf = next(it)
2234
+ buf[...] = "a"
2235
+ del buf, it # Flushing only happens during deallocate right now.
2236
+ """)
2237
+ res = subprocess.check_output([sys.executable, "-c", code],
2238
+ stderr=subprocess.STDOUT, text=True)
2239
+ assert "ValueError" in res
2240
+
2241
+
2242
+ def test_iter_buffered_cast_subarray():
2243
+ # Tests buffering of subarrays
2244
+
2245
+ # one element -> many (copies it to all)
2246
+ sdt1 = [('a', 'f4')]
2247
+ sdt2 = [('a', 'f8', (3, 2, 2))]
2248
+ a = np.zeros((6,), dtype=sdt1)
2249
+ a['a'] = np.arange(6)
2250
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2251
+ casting='unsafe',
2252
+ op_dtypes=sdt2)
2253
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2254
+ for x, count in zip(i, list(range(6))):
2255
+ assert_(np.all(x['a'] == count))
2256
+
2257
+ # one element -> many -> back (copies it to all)
2258
+ sdt1 = [('a', 'O', (1, 1))]
2259
+ sdt2 = [('a', 'O', (3, 2, 2))]
2260
+ a = np.zeros((6,), dtype=sdt1)
2261
+ a['a'][:, 0, 0] = np.arange(6)
2262
+ i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'],
2263
+ casting='unsafe',
2264
+ op_dtypes=sdt2)
2265
+ with i:
2266
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2267
+ count = 0
2268
+ for x in i:
2269
+ assert_(np.all(x['a'] == count))
2270
+ x['a'][0] += 2
2271
+ count += 1
2272
+ assert_equal(a['a'], np.arange(6).reshape(6, 1, 1) + 2)
2273
+
2274
+ # many -> one element -> back (copies just element 0)
2275
+ sdt1 = [('a', 'O', (3, 2, 2))]
2276
+ sdt2 = [('a', 'O', (1,))]
2277
+ a = np.zeros((6,), dtype=sdt1)
2278
+ a['a'][:, 0, 0, 0] = np.arange(6)
2279
+ i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'],
2280
+ casting='unsafe',
2281
+ op_dtypes=sdt2)
2282
+ with i:
2283
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2284
+ count = 0
2285
+ for x in i:
2286
+ assert_equal(x['a'], count)
2287
+ x['a'] += 2
2288
+ count += 1
2289
+ assert_equal(a['a'], np.arange(6).reshape(6, 1, 1, 1) * np.ones((1, 3, 2, 2)) + 2)
2290
+
2291
+ # many -> one element -> back (copies just element 0)
2292
+ sdt1 = [('a', 'f8', (3, 2, 2))]
2293
+ sdt2 = [('a', 'O', (1,))]
2294
+ a = np.zeros((6,), dtype=sdt1)
2295
+ a['a'][:, 0, 0, 0] = np.arange(6)
2296
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2297
+ casting='unsafe',
2298
+ op_dtypes=sdt2)
2299
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2300
+ count = 0
2301
+ for x in i:
2302
+ assert_equal(x['a'], count)
2303
+ count += 1
2304
+
2305
+ # many -> one element (copies just element 0)
2306
+ sdt1 = [('a', 'O', (3, 2, 2))]
2307
+ sdt2 = [('a', 'f4', (1,))]
2308
+ a = np.zeros((6,), dtype=sdt1)
2309
+ a['a'][:, 0, 0, 0] = np.arange(6)
2310
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2311
+ casting='unsafe',
2312
+ op_dtypes=sdt2)
2313
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2314
+ count = 0
2315
+ for x in i:
2316
+ assert_equal(x['a'], count)
2317
+ count += 1
2318
+
2319
+ # many -> matching shape (straightforward copy)
2320
+ sdt1 = [('a', 'O', (3, 2, 2))]
2321
+ sdt2 = [('a', 'f4', (3, 2, 2))]
2322
+ a = np.zeros((6,), dtype=sdt1)
2323
+ a['a'] = np.arange(6 * 3 * 2 * 2).reshape(6, 3, 2, 2)
2324
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2325
+ casting='unsafe',
2326
+ op_dtypes=sdt2)
2327
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2328
+ count = 0
2329
+ for x in i:
2330
+ assert_equal(x['a'], a[count]['a'])
2331
+ count += 1
2332
+
2333
+ # vector -> smaller vector (truncates)
2334
+ sdt1 = [('a', 'f8', (6,))]
2335
+ sdt2 = [('a', 'f4', (2,))]
2336
+ a = np.zeros((6,), dtype=sdt1)
2337
+ a['a'] = np.arange(6 * 6).reshape(6, 6)
2338
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2339
+ casting='unsafe',
2340
+ op_dtypes=sdt2)
2341
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2342
+ count = 0
2343
+ for x in i:
2344
+ assert_equal(x['a'], a[count]['a'][:2])
2345
+ count += 1
2346
+
2347
+ # vector -> bigger vector (pads with zeros)
2348
+ sdt1 = [('a', 'f8', (2,))]
2349
+ sdt2 = [('a', 'f4', (6,))]
2350
+ a = np.zeros((6,), dtype=sdt1)
2351
+ a['a'] = np.arange(6 * 2).reshape(6, 2)
2352
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2353
+ casting='unsafe',
2354
+ op_dtypes=sdt2)
2355
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2356
+ count = 0
2357
+ for x in i:
2358
+ assert_equal(x['a'][:2], a[count]['a'])
2359
+ assert_equal(x['a'][2:], [0, 0, 0, 0])
2360
+ count += 1
2361
+
2362
+ # vector -> matrix (broadcasts)
2363
+ sdt1 = [('a', 'f8', (2,))]
2364
+ sdt2 = [('a', 'f4', (2, 2))]
2365
+ a = np.zeros((6,), dtype=sdt1)
2366
+ a['a'] = np.arange(6 * 2).reshape(6, 2)
2367
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2368
+ casting='unsafe',
2369
+ op_dtypes=sdt2)
2370
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2371
+ count = 0
2372
+ for x in i:
2373
+ assert_equal(x['a'][0], a[count]['a'])
2374
+ assert_equal(x['a'][1], a[count]['a'])
2375
+ count += 1
2376
+
2377
+ # vector -> matrix (broadcasts and zero-pads)
2378
+ sdt1 = [('a', 'f8', (2, 1))]
2379
+ sdt2 = [('a', 'f4', (3, 2))]
2380
+ a = np.zeros((6,), dtype=sdt1)
2381
+ a['a'] = np.arange(6 * 2).reshape(6, 2, 1)
2382
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2383
+ casting='unsafe',
2384
+ op_dtypes=sdt2)
2385
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2386
+ count = 0
2387
+ for x in i:
2388
+ assert_equal(x['a'][:2, 0], a[count]['a'][:, 0])
2389
+ assert_equal(x['a'][:2, 1], a[count]['a'][:, 0])
2390
+ assert_equal(x['a'][2, :], [0, 0])
2391
+ count += 1
2392
+
2393
+ # matrix -> matrix (truncates and zero-pads)
2394
+ sdt1 = [('a', 'f8', (2, 3))]
2395
+ sdt2 = [('a', 'f4', (3, 2))]
2396
+ a = np.zeros((6,), dtype=sdt1)
2397
+ a['a'] = np.arange(6 * 2 * 3).reshape(6, 2, 3)
2398
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
2399
+ casting='unsafe',
2400
+ op_dtypes=sdt2)
2401
+ assert_equal(i[0].dtype, np.dtype(sdt2))
2402
+ count = 0
2403
+ for x in i:
2404
+ assert_equal(x['a'][:2, 0], a[count]['a'][:, 0])
2405
+ assert_equal(x['a'][:2, 1], a[count]['a'][:, 1])
2406
+ assert_equal(x['a'][2, :], [0, 0])
2407
+ count += 1
2408
+
2409
+ def test_iter_buffering_badwriteback():
2410
+ # Writing back from a buffer cannot combine elements
2411
+
2412
+ # a needs write buffering, but had a broadcast dimension
2413
+ a = np.arange(6).reshape(2, 3, 1)
2414
+ b = np.arange(12).reshape(2, 3, 2)
2415
+ assert_raises(ValueError, nditer, [a, b],
2416
+ ['buffered', 'external_loop'],
2417
+ [['readwrite'], ['writeonly']],
2418
+ order='C')
2419
+
2420
+ # But if a is readonly, it's fine
2421
+ nditer([a, b], ['buffered', 'external_loop'],
2422
+ [['readonly'], ['writeonly']],
2423
+ order='C')
2424
+
2425
+ # If a has just one element, it's fine too (constant 0 stride, a reduction)
2426
+ a = np.arange(1).reshape(1, 1, 1)
2427
+ nditer([a, b], ['buffered', 'external_loop', 'reduce_ok'],
2428
+ [['readwrite'], ['writeonly']],
2429
+ order='C')
2430
+
2431
+ # check that it fails on other dimensions too
2432
+ a = np.arange(6).reshape(1, 3, 2)
2433
+ assert_raises(ValueError, nditer, [a, b],
2434
+ ['buffered', 'external_loop'],
2435
+ [['readwrite'], ['writeonly']],
2436
+ order='C')
2437
+ a = np.arange(4).reshape(2, 1, 2)
2438
+ assert_raises(ValueError, nditer, [a, b],
2439
+ ['buffered', 'external_loop'],
2440
+ [['readwrite'], ['writeonly']],
2441
+ order='C')
2442
+
2443
+ def test_iter_buffering_string():
2444
+ # Safe casting disallows shrinking strings
2445
+ a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_)
2446
+ assert_equal(a.dtype, np.dtype('S4'))
2447
+ assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
2448
+ op_dtypes='S2')
2449
+ i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6')
2450
+ assert_equal(i[0], b'abc')
2451
+ assert_equal(i[0].dtype, np.dtype('S6'))
2452
+
2453
+ a = np.array(['abc', 'a', 'abcd'], dtype=np.str_)
2454
+ assert_equal(a.dtype, np.dtype('U4'))
2455
+ assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'],
2456
+ op_dtypes='U2')
2457
+ i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6')
2458
+ assert_equal(i[0], 'abc')
2459
+ assert_equal(i[0].dtype, np.dtype('U6'))
2460
+
2461
+ def test_iter_buffering_growinner():
2462
+ # Test that the inner loop grows when no buffering is needed
2463
+ a = np.arange(30)
2464
+ i = nditer(a, ['buffered', 'growinner', 'external_loop'],
2465
+ buffersize=5)
2466
+ # Should end up with just one inner loop here
2467
+ assert_equal(i[0].size, a.size)
2468
+
2469
+
2470
+ @pytest.mark.parametrize("read_or_readwrite", ["readonly", "readwrite"])
2471
+ def test_iter_contig_flag_reduce_error(read_or_readwrite):
2472
+ # Test that a non-contiguous operand is rejected without buffering.
2473
+ # NOTE: This is true even for a reduction, where we return a 0-stride
2474
+ # below!
2475
+ with pytest.raises(TypeError, match="Iterator operand required buffering"):
2476
+ it = np.nditer(
2477
+ (np.zeros(()),), flags=["external_loop", "reduce_ok"],
2478
+ op_flags=[(read_or_readwrite, "contig"),], itershape=(10,))
2479
+
2480
+
2481
+ @pytest.mark.parametrize("arr", [
2482
+ lambda: np.zeros(()),
2483
+ lambda: np.zeros((20, 1))[::20],
2484
+ lambda: np.zeros((1, 20))[:, ::20]
2485
+ ])
2486
+ def test_iter_contig_flag_single_operand_strides(arr):
2487
+ """
2488
+ Tests the strides with the contig flag for both broadcast and non-broadcast
2489
+ operands in 3 cases where the logic is needed:
2490
+ 1. When everything has a zero stride, the broadcast op needs to repeated
2491
+ 2. When the reduce axis is the last axis (first to iterate).
2492
+ 3. When the reduce axis is the first axis (last to iterate).
2493
+
2494
+ NOTE: The semantics of the cast flag are not clearly defined when
2495
+ it comes to reduction. It is unclear that there are any users.
2496
+ """
2497
+ first_op = np.ones((10, 10))
2498
+ broadcast_op = arr()
2499
+ red_op = arr()
2500
+ # Add a first operand to ensure no axis-reordering and the result shape.
2501
+ iterator = np.nditer(
2502
+ (first_op, broadcast_op, red_op),
2503
+ flags=["external_loop", "reduce_ok", "buffered", "delay_bufalloc"],
2504
+ op_flags=[("readonly", "contig")] * 2 + [("readwrite", "contig")])
2505
+
2506
+ with iterator:
2507
+ iterator.reset()
2508
+ for f, b, r in iterator:
2509
+ # The first operand is contigouos, we should have a view
2510
+ assert np.shares_memory(f, first_op)
2511
+ # Although broadcast, the second op always has a contiguous stride
2512
+ assert b.strides[0] == 8
2513
+ assert not np.shares_memory(b, broadcast_op)
2514
+ # The reduction has a contiguous stride or a 0 stride
2515
+ if red_op.ndim == 0 or red_op.shape[-1] == 1:
2516
+ assert r.strides[0] == 0
2517
+ else:
2518
+ # The stride is 8, although it was not originally:
2519
+ assert r.strides[0] == 8
2520
+ # If the reduce stride is 0, buffering makes no difference, but we
2521
+ # do it anyway right now:
2522
+ assert not np.shares_memory(r, red_op)
2523
+
2524
+
2525
+ @pytest.mark.xfail(reason="The contig flag was always buggy.")
2526
+ def test_iter_contig_flag_incorrect():
2527
+ # This case does the wrong thing...
2528
+ iterator = np.nditer(
2529
+ (np.ones((10, 10)).T, np.ones((1, 10))),
2530
+ flags=["external_loop", "reduce_ok", "buffered", "delay_bufalloc"],
2531
+ op_flags=[("readonly", "contig")] * 2)
2532
+
2533
+ with iterator:
2534
+ iterator.reset()
2535
+ for a, b in iterator:
2536
+ # Remove a and b from locals (pytest may want to format them)
2537
+ a, b = a.strides, b.strides
2538
+ assert a == 8
2539
+ assert b == 8 # should be 8 but is 0 due to axis reorder
2540
+
2541
+
2542
+ @pytest.mark.slow
2543
+ def test_iter_buffered_reduce_reuse():
2544
+ # large enough array for all views, including negative strides.
2545
+ a = np.arange(2 * 3**5)[3**5:3**5 + 1]
2546
+ flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok']
2547
+ op_flags = [('readonly',), ('readwrite', 'allocate')]
2548
+ op_axes_list = [[(0, 1, 2), (0, 1, -1)], [(0, 1, 2), (0, -1, -1)]]
2549
+ # wrong dtype to force buffering
2550
+ op_dtypes = [float, a.dtype]
2551
+
2552
+ def get_params():
2553
+ for xs in range(-3**2, 3**2 + 1):
2554
+ for ys in range(xs, 3**2 + 1):
2555
+ for op_axes in op_axes_list:
2556
+ # last stride is reduced and because of that not
2557
+ # important for this test, as it is the inner stride.
2558
+ strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize)
2559
+ arr = np.lib.stride_tricks.as_strided(a, (3, 3, 3), strides)
2560
+
2561
+ for skip in [0, 1]:
2562
+ yield arr, op_axes, skip
2563
+
2564
+ for arr, op_axes, skip in get_params():
2565
+ nditer2 = np.nditer([arr.copy(), None],
2566
+ op_axes=op_axes, flags=flags, op_flags=op_flags,
2567
+ op_dtypes=op_dtypes)
2568
+ with nditer2:
2569
+ nditer2.operands[-1][...] = 0
2570
+ nditer2.reset()
2571
+ nditer2.iterindex = skip
2572
+
2573
+ for (a2_in, b2_in) in nditer2:
2574
+ b2_in += a2_in.astype(np.int_)
2575
+
2576
+ comp_res = nditer2.operands[-1]
2577
+
2578
+ for bufsize in range(3**3):
2579
+ nditer1 = np.nditer([arr, None],
2580
+ op_axes=op_axes, flags=flags, op_flags=op_flags,
2581
+ buffersize=bufsize, op_dtypes=op_dtypes)
2582
+ with nditer1:
2583
+ nditer1.operands[-1][...] = 0
2584
+ nditer1.reset()
2585
+ nditer1.iterindex = skip
2586
+
2587
+ for (a1_in, b1_in) in nditer1:
2588
+ b1_in += a1_in.astype(np.int_)
2589
+
2590
+ res = nditer1.operands[-1]
2591
+ assert_array_equal(res, comp_res)
2592
+
2593
+
2594
+ def test_iter_buffered_reduce_reuse_core():
2595
+ # NumPy re-uses buffers for broadcast operands (as of writing when reading).
2596
+ # Test this even if the offset is manually set at some point during
2597
+ # the iteration. (not a particularly tricky path)
2598
+ arr = np.empty((1, 6, 4, 1)).reshape(1, 6, 4, 1)[:, ::3, ::2, :]
2599
+ arr[...] = np.arange(arr.size).reshape(arr.shape)
2600
+ # First and last dimension are broadcast dimensions.
2601
+ arr = np.broadcast_to(arr, (100, 2, 2, 2))
2602
+
2603
+ flags = ['buffered', 'reduce_ok', 'refs_ok', 'multi_index']
2604
+ op_flags = [('readonly',)]
2605
+
2606
+ buffersize = 100 # small enough to not fit the whole array
2607
+ it = np.nditer(arr, flags=flags, op_flags=op_flags, buffersize=100)
2608
+
2609
+ # Iterate a bit (this will cause buffering internally)
2610
+ expected = [next(it) for i in range(11)]
2611
+ # Now, manually advance to inside the core (the +1)
2612
+ it.iterindex = 10 * (2 * 2 * 2) + 1
2613
+ result = [next(it) for i in range(10)]
2614
+
2615
+ assert expected[1:] == result
2616
+
2617
+
2618
+ def test_iter_no_broadcast():
2619
+ # Test that the no_broadcast flag works
2620
+ a = np.arange(24).reshape(2, 3, 4)
2621
+ b = np.arange(6).reshape(2, 3, 1)
2622
+ c = np.arange(12).reshape(3, 4)
2623
+
2624
+ nditer([a, b, c], [],
2625
+ [['readonly', 'no_broadcast'],
2626
+ ['readonly'], ['readonly']])
2627
+ assert_raises(ValueError, nditer, [a, b, c], [],
2628
+ [['readonly'], ['readonly', 'no_broadcast'], ['readonly']])
2629
+ assert_raises(ValueError, nditer, [a, b, c], [],
2630
+ [['readonly'], ['readonly'], ['readonly', 'no_broadcast']])
2631
+
2632
+
2633
+ class TestIterNested:
2634
+
2635
+ def test_basic(self):
2636
+ # Test nested iteration basic usage
2637
+ a = arange(12).reshape(2, 3, 2)
2638
+
2639
+ i, j = np.nested_iters(a, [[0], [1, 2]])
2640
+ vals = [list(j) for _ in i]
2641
+ assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
2642
+
2643
+ i, j = np.nested_iters(a, [[0, 1], [2]])
2644
+ vals = [list(j) for _ in i]
2645
+ assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
2646
+
2647
+ i, j = np.nested_iters(a, [[0, 2], [1]])
2648
+ vals = [list(j) for _ in i]
2649
+ assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
2650
+
2651
+ def test_reorder(self):
2652
+ # Test nested iteration basic usage
2653
+ a = arange(12).reshape(2, 3, 2)
2654
+
2655
+ # In 'K' order (default), it gets reordered
2656
+ i, j = np.nested_iters(a, [[0], [2, 1]])
2657
+ vals = [list(j) for _ in i]
2658
+ assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
2659
+
2660
+ i, j = np.nested_iters(a, [[1, 0], [2]])
2661
+ vals = [list(j) for _ in i]
2662
+ assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
2663
+
2664
+ i, j = np.nested_iters(a, [[2, 0], [1]])
2665
+ vals = [list(j) for _ in i]
2666
+ assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
2667
+
2668
+ # In 'C' order, it doesn't
2669
+ i, j = np.nested_iters(a, [[0], [2, 1]], order='C')
2670
+ vals = [list(j) for _ in i]
2671
+ assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]])
2672
+
2673
+ i, j = np.nested_iters(a, [[1, 0], [2]], order='C')
2674
+ vals = [list(j) for _ in i]
2675
+ assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]])
2676
+
2677
+ i, j = np.nested_iters(a, [[2, 0], [1]], order='C')
2678
+ vals = [list(j) for _ in i]
2679
+ assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]])
2680
+
2681
+ def test_flip_axes(self):
2682
+ # Test nested iteration with negative axes
2683
+ a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1]
2684
+
2685
+ # In 'K' order (default), the axes all get flipped
2686
+ i, j = np.nested_iters(a, [[0], [1, 2]])
2687
+ vals = [list(j) for _ in i]
2688
+ assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]])
2689
+
2690
+ i, j = np.nested_iters(a, [[0, 1], [2]])
2691
+ vals = [list(j) for _ in i]
2692
+ assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]])
2693
+
2694
+ i, j = np.nested_iters(a, [[0, 2], [1]])
2695
+ vals = [list(j) for _ in i]
2696
+ assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
2697
+
2698
+ # In 'C' order, flipping axes is disabled
2699
+ i, j = np.nested_iters(a, [[0], [1, 2]], order='C')
2700
+ vals = [list(j) for _ in i]
2701
+ assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]])
2702
+
2703
+ i, j = np.nested_iters(a, [[0, 1], [2]], order='C')
2704
+ vals = [list(j) for _ in i]
2705
+ assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]])
2706
+
2707
+ i, j = np.nested_iters(a, [[0, 2], [1]], order='C')
2708
+ vals = [list(j) for _ in i]
2709
+ assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]])
2710
+
2711
+ def test_broadcast(self):
2712
+ # Test nested iteration with broadcasting
2713
+ a = arange(2).reshape(2, 1)
2714
+ b = arange(3).reshape(1, 3)
2715
+
2716
+ i, j = np.nested_iters([a, b], [[0], [1]])
2717
+ vals = [list(j) for _ in i]
2718
+ assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]])
2719
+
2720
+ i, j = np.nested_iters([a, b], [[1], [0]])
2721
+ vals = [list(j) for _ in i]
2722
+ assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]])
2723
+
2724
+ def test_dtype_copy(self):
2725
+ # Test nested iteration with a copy to change dtype
2726
+
2727
+ # copy
2728
+ a = arange(6, dtype='i4').reshape(2, 3)
2729
+ i, j = np.nested_iters(a, [[0], [1]],
2730
+ op_flags=['readonly', 'copy'],
2731
+ op_dtypes='f8')
2732
+ assert_equal(j[0].dtype, np.dtype('f8'))
2733
+ vals = [list(j) for _ in i]
2734
+ assert_equal(vals, [[0, 1, 2], [3, 4, 5]])
2735
+ vals = None
2736
+
2737
+ # writebackifcopy - using context manager
2738
+ a = arange(6, dtype='f4').reshape(2, 3)
2739
+ i, j = np.nested_iters(a, [[0], [1]],
2740
+ op_flags=['readwrite', 'updateifcopy'],
2741
+ casting='same_kind',
2742
+ op_dtypes='f8')
2743
+ with i, j:
2744
+ assert_equal(j[0].dtype, np.dtype('f8'))
2745
+ for x in i:
2746
+ for y in j:
2747
+ y[...] += 1
2748
+ assert_equal(a, [[0, 1, 2], [3, 4, 5]])
2749
+ assert_equal(a, [[1, 2, 3], [4, 5, 6]])
2750
+
2751
+ # writebackifcopy - using close()
2752
+ a = arange(6, dtype='f4').reshape(2, 3)
2753
+ i, j = np.nested_iters(a, [[0], [1]],
2754
+ op_flags=['readwrite', 'updateifcopy'],
2755
+ casting='same_kind',
2756
+ op_dtypes='f8')
2757
+ assert_equal(j[0].dtype, np.dtype('f8'))
2758
+ for x in i:
2759
+ for y in j:
2760
+ y[...] += 1
2761
+ assert_equal(a, [[0, 1, 2], [3, 4, 5]])
2762
+ i.close()
2763
+ j.close()
2764
+ assert_equal(a, [[1, 2, 3], [4, 5, 6]])
2765
+
2766
+ def test_dtype_buffered(self):
2767
+ # Test nested iteration with buffering to change dtype
2768
+
2769
+ a = arange(6, dtype='f4').reshape(2, 3)
2770
+ i, j = np.nested_iters(a, [[0], [1]],
2771
+ flags=['buffered'],
2772
+ op_flags=['readwrite'],
2773
+ casting='same_kind',
2774
+ op_dtypes='f8')
2775
+ assert_equal(j[0].dtype, np.dtype('f8'))
2776
+ for x in i:
2777
+ for y in j:
2778
+ y[...] += 1
2779
+ assert_equal(a, [[1, 2, 3], [4, 5, 6]])
2780
+
2781
+ def test_0d(self):
2782
+ a = np.arange(12).reshape(2, 3, 2)
2783
+ i, j = np.nested_iters(a, [[], [1, 0, 2]])
2784
+ vals = [list(j) for _ in i]
2785
+ assert_equal(vals, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
2786
+
2787
+ i, j = np.nested_iters(a, [[1, 0, 2], []])
2788
+ vals = [list(j) for _ in i]
2789
+ assert_equal(
2790
+ vals,
2791
+ [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]],
2792
+ )
2793
+
2794
+ i, j, k = np.nested_iters(a, [[2, 0], [], [1]])
2795
+ vals = []
2796
+ for x in i:
2797
+ for y in j:
2798
+ vals.append(list(k))
2799
+ assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]])
2800
+
2801
+ def test_iter_nested_iters_dtype_buffered(self):
2802
+ # Test nested iteration with buffering to change dtype
2803
+
2804
+ a = arange(6, dtype='f4').reshape(2, 3)
2805
+ i, j = np.nested_iters(a, [[0], [1]],
2806
+ flags=['buffered'],
2807
+ op_flags=['readwrite'],
2808
+ casting='same_kind',
2809
+ op_dtypes='f8')
2810
+ with i, j:
2811
+ assert_equal(j[0].dtype, np.dtype('f8'))
2812
+ for x in i:
2813
+ for y in j:
2814
+ y[...] += 1
2815
+ assert_equal(a, [[1, 2, 3], [4, 5, 6]])
2816
+
2817
+ def test_iter_reduction_error():
2818
+
2819
+ a = np.arange(6)
2820
+ assert_raises(ValueError, nditer, [a, None], [],
2821
+ [['readonly'], ['readwrite', 'allocate']],
2822
+ op_axes=[[0], [-1]])
2823
+
2824
+ a = np.arange(6).reshape(2, 3)
2825
+ assert_raises(ValueError, nditer, [a, None], ['external_loop'],
2826
+ [['readonly'], ['readwrite', 'allocate']],
2827
+ op_axes=[[0, 1], [-1, -1]])
2828
+
2829
+ def test_iter_reduction():
2830
+ # Test doing reductions with the iterator
2831
+
2832
+ a = np.arange(6)
2833
+ i = nditer([a, None], ['reduce_ok'],
2834
+ [['readonly'], ['readwrite', 'allocate']],
2835
+ op_axes=[[0], [-1]])
2836
+ # Need to initialize the output operand to the addition unit
2837
+ with i:
2838
+ i.operands[1][...] = 0
2839
+ # Do the reduction
2840
+ for x, y in i:
2841
+ y[...] += x
2842
+ # Since no axes were specified, should have allocated a scalar
2843
+ assert_equal(i.operands[1].ndim, 0)
2844
+ assert_equal(i.operands[1], np.sum(a))
2845
+
2846
+ a = np.arange(6).reshape(2, 3)
2847
+ i = nditer([a, None], ['reduce_ok', 'external_loop'],
2848
+ [['readonly'], ['readwrite', 'allocate']],
2849
+ op_axes=[[0, 1], [-1, -1]])
2850
+ # Need to initialize the output operand to the addition unit
2851
+ with i:
2852
+ i.operands[1][...] = 0
2853
+ # Reduction shape/strides for the output
2854
+ assert_equal(i[1].shape, (6,))
2855
+ assert_equal(i[1].strides, (0,))
2856
+ # Do the reduction
2857
+ for x, y in i:
2858
+ # Use a for loop instead of ``y[...] += x``
2859
+ # (equivalent to ``y[...] = y[...].copy() + x``),
2860
+ # because y has zero strides we use for the reduction
2861
+ for j in range(len(y)):
2862
+ y[j] += x[j]
2863
+ # Since no axes were specified, should have allocated a scalar
2864
+ assert_equal(i.operands[1].ndim, 0)
2865
+ assert_equal(i.operands[1], np.sum(a))
2866
+
2867
+ # This is a tricky reduction case for the buffering double loop
2868
+ # to handle
2869
+ a = np.ones((2, 3, 5))
2870
+ it1 = nditer([a, None], ['reduce_ok', 'external_loop'],
2871
+ [['readonly'], ['readwrite', 'allocate']],
2872
+ op_axes=[None, [0, -1, 1]])
2873
+ it2 = nditer([a, None], ['reduce_ok', 'external_loop',
2874
+ 'buffered', 'delay_bufalloc'],
2875
+ [['readonly'], ['readwrite', 'allocate']],
2876
+ op_axes=[None, [0, -1, 1]], buffersize=10)
2877
+ with it1, it2:
2878
+ it1.operands[1].fill(0)
2879
+ it2.operands[1].fill(0)
2880
+ it2.reset()
2881
+ for x in it1:
2882
+ x[1][...] += x[0]
2883
+ for x in it2:
2884
+ x[1][...] += x[0]
2885
+ assert_equal(it1.operands[1], it2.operands[1])
2886
+ assert_equal(it2.operands[1].sum(), a.size)
2887
+
2888
+ def test_iter_buffering_reduction():
2889
+ # Test doing buffered reductions with the iterator
2890
+
2891
+ a = np.arange(6)
2892
+ b = np.array(0., dtype='f8').byteswap()
2893
+ b = b.view(b.dtype.newbyteorder())
2894
+ i = nditer([a, b], ['reduce_ok', 'buffered'],
2895
+ [['readonly'], ['readwrite', 'nbo']],
2896
+ op_axes=[[0], [-1]])
2897
+ with i:
2898
+ assert_equal(i[1].dtype, np.dtype('f8'))
2899
+ assert_(i[1].dtype != b.dtype)
2900
+ # Do the reduction
2901
+ for x, y in i:
2902
+ y[...] += x
2903
+ # Since no axes were specified, should have allocated a scalar
2904
+ assert_equal(b, np.sum(a))
2905
+
2906
+ a = np.arange(6).reshape(2, 3)
2907
+ b = np.array([0, 0], dtype='f8').byteswap()
2908
+ b = b.view(b.dtype.newbyteorder())
2909
+ i = nditer([a, b], ['reduce_ok', 'external_loop', 'buffered'],
2910
+ [['readonly'], ['readwrite', 'nbo']],
2911
+ op_axes=[[0, 1], [0, -1]])
2912
+ # Reduction shape/strides for the output
2913
+ with i:
2914
+ assert_equal(i[1].shape, (3,))
2915
+ assert_equal(i[1].strides, (0,))
2916
+ # Do the reduction
2917
+ for x, y in i:
2918
+ # Use a for loop instead of ``y[...] += x``
2919
+ # (equivalent to ``y[...] = y[...].copy() + x``),
2920
+ # because y has zero strides we use for the reduction
2921
+ for j in range(len(y)):
2922
+ y[j] += x[j]
2923
+ assert_equal(b, np.sum(a, axis=1))
2924
+
2925
+ # Iterator inner double loop was wrong on this one
2926
+ p = np.arange(2) + 1
2927
+ it = np.nditer([p, None],
2928
+ ['delay_bufalloc', 'reduce_ok', 'buffered', 'external_loop'],
2929
+ [['readonly'], ['readwrite', 'allocate']],
2930
+ op_axes=[[-1, 0], [-1, -1]],
2931
+ itershape=(2, 2))
2932
+ with it:
2933
+ it.operands[1].fill(0)
2934
+ it.reset()
2935
+ assert_equal(it[0], [1, 2, 1, 2])
2936
+
2937
+ # Iterator inner loop should take argument contiguity into account
2938
+ x = np.ones((7, 13, 8), np.int8)[4:6, 1:11:6, 1:5].transpose(1, 2, 0)
2939
+ x[...] = np.arange(x.size).reshape(x.shape)
2940
+ y_base = np.arange(4 * 4, dtype=np.int8).reshape(4, 4)
2941
+ y_base_copy = y_base.copy()
2942
+ y = y_base[::2, :, None]
2943
+
2944
+ it = np.nditer([y, x],
2945
+ ['buffered', 'external_loop', 'reduce_ok'],
2946
+ [['readwrite'], ['readonly']])
2947
+ with it:
2948
+ for a, b in it:
2949
+ a.fill(2)
2950
+
2951
+ assert_equal(y_base[1::2], y_base_copy[1::2])
2952
+ assert_equal(y_base[::2], 2)
2953
+
2954
+ def test_iter_buffering_reduction_reuse_reduce_loops():
2955
+ # There was a bug triggering reuse of the reduce loop inappropriately,
2956
+ # which caused processing to happen in unnecessarily small chunks
2957
+ # and overran the buffer.
2958
+
2959
+ a = np.zeros((2, 7))
2960
+ b = np.zeros((1, 7))
2961
+ it = np.nditer([a, b], flags=['reduce_ok', 'external_loop', 'buffered'],
2962
+ op_flags=[['readonly'], ['readwrite']],
2963
+ buffersize=5)
2964
+
2965
+ with it:
2966
+ bufsizes = [x.shape[0] for x, y in it]
2967
+ assert_equal(bufsizes, [5, 2, 5, 2])
2968
+ assert_equal(sum(bufsizes), a.size)
2969
+
2970
+ def test_iter_writemasked_badinput():
2971
+ a = np.zeros((2, 3))
2972
+ b = np.zeros((3,))
2973
+ m = np.array([[True, True, False], [False, True, False]])
2974
+ m2 = np.array([True, True, False])
2975
+ m3 = np.array([0, 1, 1], dtype='u1')
2976
+ mbad1 = np.array([0, 1, 1], dtype='i1')
2977
+ mbad2 = np.array([0, 1, 1], dtype='f4')
2978
+
2979
+ # Need an 'arraymask' if any operand is 'writemasked'
2980
+ assert_raises(ValueError, nditer, [a, m], [],
2981
+ [['readwrite', 'writemasked'], ['readonly']])
2982
+
2983
+ # A 'writemasked' operand must not be readonly
2984
+ assert_raises(ValueError, nditer, [a, m], [],
2985
+ [['readonly', 'writemasked'], ['readonly', 'arraymask']])
2986
+
2987
+ # 'writemasked' and 'arraymask' may not be used together
2988
+ assert_raises(ValueError, nditer, [a, m], [],
2989
+ [['readonly'], ['readwrite', 'arraymask', 'writemasked']])
2990
+
2991
+ # 'arraymask' may only be specified once
2992
+ assert_raises(ValueError, nditer, [a, m, m2], [],
2993
+ [['readwrite', 'writemasked'],
2994
+ ['readonly', 'arraymask'],
2995
+ ['readonly', 'arraymask']])
2996
+
2997
+ # An 'arraymask' with nothing 'writemasked' also doesn't make sense
2998
+ assert_raises(ValueError, nditer, [a, m], [],
2999
+ [['readwrite'], ['readonly', 'arraymask']])
3000
+
3001
+ # A writemasked reduction requires a similarly smaller mask
3002
+ assert_raises(ValueError, nditer, [a, b, m], ['reduce_ok'],
3003
+ [['readonly'],
3004
+ ['readwrite', 'writemasked'],
3005
+ ['readonly', 'arraymask']])
3006
+ # But this should work with a smaller/equal mask to the reduction operand
3007
+ np.nditer([a, b, m2], ['reduce_ok'],
3008
+ [['readonly'],
3009
+ ['readwrite', 'writemasked'],
3010
+ ['readonly', 'arraymask']])
3011
+ # The arraymask itself cannot be a reduction
3012
+ assert_raises(ValueError, nditer, [a, b, m2], ['reduce_ok'],
3013
+ [['readonly'],
3014
+ ['readwrite', 'writemasked'],
3015
+ ['readwrite', 'arraymask']])
3016
+
3017
+ # A uint8 mask is ok too
3018
+ np.nditer([a, m3], ['buffered'],
3019
+ [['readwrite', 'writemasked'],
3020
+ ['readonly', 'arraymask']],
3021
+ op_dtypes=['f4', None],
3022
+ casting='same_kind')
3023
+ # An int8 mask isn't ok
3024
+ assert_raises(TypeError, np.nditer, [a, mbad1], ['buffered'],
3025
+ [['readwrite', 'writemasked'],
3026
+ ['readonly', 'arraymask']],
3027
+ op_dtypes=['f4', None],
3028
+ casting='same_kind')
3029
+ # A float32 mask isn't ok
3030
+ assert_raises(TypeError, np.nditer, [a, mbad2], ['buffered'],
3031
+ [['readwrite', 'writemasked'],
3032
+ ['readonly', 'arraymask']],
3033
+ op_dtypes=['f4', None],
3034
+ casting='same_kind')
3035
+
3036
+
3037
+ def _is_buffered(iterator):
3038
+ try:
3039
+ iterator.itviews
3040
+ except ValueError:
3041
+ return True
3042
+ return False
3043
+
3044
+ @pytest.mark.parametrize("arrs",
3045
+ [np.zeros((3,), dtype='f8'),
3046
+ np.zeros((9876, 3 * 5), dtype='f8')[::2, :],
3047
+ np.zeros((4, 312, 124, 3), dtype='f8')[::2, :, ::2, :],
3048
+ # Also test with the last dimension strided (so it does not fit if
3049
+ # there is repeated access)
3050
+ np.zeros((9,), dtype='f8')[::3],
3051
+ np.zeros((9876, 3 * 10), dtype='f8')[::2, ::5],
3052
+ np.zeros((4, 312, 124, 3), dtype='f8')[::2, :, ::2, ::-1]])
3053
+ def test_iter_writemasked(arrs):
3054
+ # Note, the slicing above is to ensure that nditer cannot combine multiple
3055
+ # axes into one. The repetition is just to make things a bit more
3056
+ # interesting.
3057
+ a = arrs.copy()
3058
+ shape = a.shape
3059
+ reps = shape[-1] // 3
3060
+ msk = np.empty(shape, dtype=bool)
3061
+ msk[...] = [True, True, False] * reps
3062
+
3063
+ # When buffering is unused, 'writemasked' effectively does nothing.
3064
+ # It's up to the user of the iterator to obey the requested semantics.
3065
+ it = np.nditer([a, msk], [],
3066
+ [['readwrite', 'writemasked'],
3067
+ ['readonly', 'arraymask']])
3068
+ with it:
3069
+ for x, m in it:
3070
+ x[...] = 1
3071
+ # Because we violated the semantics, all the values became 1
3072
+ assert_equal(a, np.broadcast_to([1, 1, 1] * reps, shape))
3073
+
3074
+ # Even if buffering is enabled, we still may be accessing the array
3075
+ # directly.
3076
+ it = np.nditer([a, msk], ['buffered'],
3077
+ [['readwrite', 'writemasked'],
3078
+ ['readonly', 'arraymask']])
3079
+ # @seberg: I honestly don't currently understand why a "buffered" iterator
3080
+ # would end up not using a buffer for the small array here at least when
3081
+ # "writemasked" is used, that seems confusing... Check by testing for
3082
+ # actual memory overlap!
3083
+ is_buffered = True
3084
+ with it:
3085
+ for x, m in it:
3086
+ x[...] = 2.5
3087
+ if np.may_share_memory(x, a):
3088
+ is_buffered = False
3089
+
3090
+ if not is_buffered:
3091
+ # Because we violated the semantics, all the values became 2.5
3092
+ assert_equal(a, np.broadcast_to([2.5, 2.5, 2.5] * reps, shape))
3093
+ else:
3094
+ # For large sizes, the iterator may be buffered:
3095
+ assert_equal(a, np.broadcast_to([2.5, 2.5, 1] * reps, shape))
3096
+ a[...] = 2.5
3097
+
3098
+ # If buffering will definitely happening, for instance because of
3099
+ # a cast, only the items selected by the mask will be copied back from
3100
+ # the buffer.
3101
+ it = np.nditer([a, msk], ['buffered'],
3102
+ [['readwrite', 'writemasked'],
3103
+ ['readonly', 'arraymask']],
3104
+ op_dtypes=['i8', None],
3105
+ casting='unsafe')
3106
+ with it:
3107
+ for x, m in it:
3108
+ x[...] = 3
3109
+ # Even though we violated the semantics, only the selected values
3110
+ # were copied back
3111
+ assert_equal(a, np.broadcast_to([3, 3, 2.5] * reps, shape))
3112
+
3113
+
3114
+ @pytest.mark.parametrize(["mask", "mask_axes"], [
3115
+ # Allocated operand (only broadcasts with -1)
3116
+ (None, [-1, 0]),
3117
+ # Reduction along the first dimension (with and without op_axes)
3118
+ (np.zeros((1, 4), dtype="bool"), [0, 1]),
3119
+ (np.zeros((1, 4), dtype="bool"), None),
3120
+ # Test 0-D and -1 op_axes
3121
+ (np.zeros(4, dtype="bool"), [-1, 0]),
3122
+ (np.zeros((), dtype="bool"), [-1, -1]),
3123
+ (np.zeros((), dtype="bool"), None)])
3124
+ def test_iter_writemasked_broadcast_error(mask, mask_axes):
3125
+ # This assumes that a readwrite mask makes sense. This is likely not the
3126
+ # case and should simply be deprecated.
3127
+ arr = np.zeros((3, 4))
3128
+ itflags = ["reduce_ok"]
3129
+ mask_flags = ["arraymask", "readwrite", "allocate"]
3130
+ a_flags = ["writeonly", "writemasked"]
3131
+ if mask_axes is None:
3132
+ op_axes = None
3133
+ else:
3134
+ op_axes = [mask_axes, [0, 1]]
3135
+
3136
+ with assert_raises(ValueError):
3137
+ np.nditer((mask, arr), flags=itflags, op_flags=[mask_flags, a_flags],
3138
+ op_axes=op_axes)
3139
+
3140
+
3141
+ def test_iter_writemasked_decref():
3142
+ # force casting (to make it interesting) by using a structured dtype.
3143
+ arr = np.arange(10000).astype(">i,O")
3144
+ original = arr.copy()
3145
+ mask = np.random.randint(0, 2, size=10000).astype(bool)
3146
+
3147
+ it = np.nditer([arr, mask], ['buffered', "refs_ok"],
3148
+ [['readwrite', 'writemasked'],
3149
+ ['readonly', 'arraymask']],
3150
+ op_dtypes=["<i,O", "?"])
3151
+ singleton = object()
3152
+ if HAS_REFCOUNT:
3153
+ count = sys.getrefcount(singleton)
3154
+ for buf, mask_buf in it:
3155
+ buf[...] = (3, singleton)
3156
+
3157
+ del buf, mask_buf, it # delete everything to ensure correct cleanup
3158
+
3159
+ if HAS_REFCOUNT:
3160
+ # The buffer would have included additional items, they must be
3161
+ # cleared correctly:
3162
+ assert sys.getrefcount(singleton) - count == np.count_nonzero(mask)
3163
+
3164
+ assert_array_equal(arr[~mask], original[~mask])
3165
+ assert (arr[mask] == np.array((3, singleton), arr.dtype)).all()
3166
+ del arr
3167
+
3168
+ if HAS_REFCOUNT:
3169
+ assert sys.getrefcount(singleton) == count
3170
+
3171
+
3172
+ def test_iter_non_writable_attribute_deletion():
3173
+ it = np.nditer(np.ones(2))
3174
+ attr = ["value", "shape", "operands", "itviews", "has_delayed_bufalloc",
3175
+ "iterationneedsapi", "has_multi_index", "has_index", "dtypes",
3176
+ "ndim", "nop", "itersize", "finished"]
3177
+
3178
+ for s in attr:
3179
+ assert_raises(AttributeError, delattr, it, s)
3180
+
3181
+
3182
+ def test_iter_writable_attribute_deletion():
3183
+ it = np.nditer(np.ones(2))
3184
+ attr = ["multi_index", "index", "iterrange", "iterindex"]
3185
+ for s in attr:
3186
+ assert_raises(AttributeError, delattr, it, s)
3187
+
3188
+
3189
+ def test_iter_element_deletion():
3190
+ it = np.nditer(np.ones(3))
3191
+ try:
3192
+ del it[1]
3193
+ del it[1:2]
3194
+ except TypeError:
3195
+ pass
3196
+ except Exception:
3197
+ raise AssertionError
3198
+
3199
+ def test_iter_allocated_array_dtypes():
3200
+ # If the dtype of an allocated output has a shape, the shape gets
3201
+ # tacked onto the end of the result.
3202
+ it = np.nditer(([1, 3, 20], None), op_dtypes=[None, ('i4', (2,))])
3203
+ for a, b in it:
3204
+ b[0] = a - 1
3205
+ b[1] = a + 1
3206
+ assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]])
3207
+
3208
+ # Check the same (less sensitive) thing when `op_axes` with -1 is given.
3209
+ it = np.nditer(([[1, 3, 20]], None), op_dtypes=[None, ('i4', (2,))],
3210
+ flags=["reduce_ok"], op_axes=[None, (-1, 0)])
3211
+ for a, b in it:
3212
+ b[0] = a - 1
3213
+ b[1] = a + 1
3214
+ assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]])
3215
+
3216
+ # Make sure this works for scalars too
3217
+ it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2, 2))])
3218
+ for a, b, c in it:
3219
+ c[0, 0] = a - b
3220
+ c[0, 1] = a + b
3221
+ c[1, 0] = a * b
3222
+ c[1, 1] = a / b
3223
+ assert_equal(it.operands[2], [[8, 12], [20, 5]])
3224
+
3225
+
3226
+ def test_0d_iter():
3227
+ # Basic test for iteration of 0-d arrays:
3228
+ i = nditer([2, 3], ['multi_index'], [['readonly']] * 2)
3229
+ assert_equal(i.ndim, 0)
3230
+ assert_equal(next(i), (2, 3))
3231
+ assert_equal(i.multi_index, ())
3232
+ assert_equal(i.iterindex, 0)
3233
+ assert_raises(StopIteration, next, i)
3234
+ # test reset:
3235
+ i.reset()
3236
+ assert_equal(next(i), (2, 3))
3237
+ assert_raises(StopIteration, next, i)
3238
+
3239
+ # test forcing to 0-d
3240
+ i = nditer(np.arange(5), ['multi_index'], [['readonly']], op_axes=[()])
3241
+ assert_equal(i.ndim, 0)
3242
+ assert_equal(len(i), 1)
3243
+
3244
+ i = nditer(np.arange(5), ['multi_index'], [['readonly']],
3245
+ op_axes=[()], itershape=())
3246
+ assert_equal(i.ndim, 0)
3247
+ assert_equal(len(i), 1)
3248
+
3249
+ # passing an itershape alone is not enough, the op_axes are also needed
3250
+ with assert_raises(ValueError):
3251
+ nditer(np.arange(5), ['multi_index'], [['readonly']], itershape=())
3252
+
3253
+ # Test a more complex buffered casting case (same as another test above)
3254
+ sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')]
3255
+ a = np.array(0.5, dtype='f4')
3256
+ i = nditer(a, ['buffered', 'refs_ok'], ['readonly'],
3257
+ casting='unsafe', op_dtypes=sdt)
3258
+ vals = next(i)
3259
+ assert_equal(vals['a'], 0.5)
3260
+ assert_equal(vals['b'], 0)
3261
+ assert_equal(vals['c'], [[(0.5)] * 3] * 2)
3262
+ assert_equal(vals['d'], 0.5)
3263
+
3264
+ def test_object_iter_cleanup():
3265
+ # see gh-18450
3266
+ # object arrays can raise a python exception in ufunc inner loops using
3267
+ # nditer, which should cause iteration to stop & cleanup. There were bugs
3268
+ # in the nditer cleanup when decref'ing object arrays.
3269
+ # This test would trigger valgrind "uninitialized read" before the bugfix.
3270
+ assert_raises(TypeError, lambda: np.zeros((17000, 2), dtype='f4') * None)
3271
+
3272
+ # this more explicit code also triggers the invalid access
3273
+ arr = np.arange(ncu.BUFSIZE * 10).reshape(10, -1).astype(str)
3274
+ oarr = arr.astype(object)
3275
+ oarr[:, -1] = None
3276
+ assert_raises(TypeError, lambda: np.add(oarr[:, ::-1], arr[:, ::-1]))
3277
+
3278
+ # followup: this tests for a bug introduced in the first pass of gh-18450,
3279
+ # caused by an incorrect fallthrough of the TypeError
3280
+ class T:
3281
+ def __bool__(self):
3282
+ raise TypeError("Ambiguous")
3283
+ assert_raises(TypeError, np.logical_or.reduce,
3284
+ np.array([T(), T()], dtype='O'))
3285
+
3286
+ def test_object_iter_cleanup_reduce():
3287
+ # Similar as above, but a complex reduction case that was previously
3288
+ # missed (see gh-18810).
3289
+ # The following array is special in that it cannot be flattened:
3290
+ arr = np.array([[None, 1], [-1, -1], [None, 2], [-1, -1]])[::2]
3291
+ with pytest.raises(TypeError):
3292
+ np.sum(arr)
3293
+
3294
+ @pytest.mark.parametrize("arr", [
3295
+ np.ones((8000, 4, 2), dtype=object)[:, ::2, :],
3296
+ np.ones((8000, 4, 2), dtype=object, order="F")[:, ::2, :],
3297
+ np.ones((8000, 4, 2), dtype=object)[:, ::2, :].copy("F")])
3298
+ def test_object_iter_cleanup_large_reduce(arr):
3299
+ # More complicated calls are possible for large arrays:
3300
+ out = np.ones(8000, dtype=np.intp)
3301
+ # force casting with `dtype=object`
3302
+ res = np.sum(arr, axis=(1, 2), dtype=object, out=out)
3303
+ assert_array_equal(res, np.full(8000, 4, dtype=object))
3304
+
3305
+ def test_iter_too_large():
3306
+ # The total size of the iterator must not exceed the maximum intp due
3307
+ # to broadcasting. Dividing by 1024 will keep it small enough to
3308
+ # give a legal array.
3309
+ size = np.iinfo(np.intp).max // 1024
3310
+ arr = np.lib.stride_tricks.as_strided(np.zeros(1), (size,), (0,))
3311
+ assert_raises(ValueError, nditer, (arr, arr[:, None]))
3312
+ # test the same for multiindex. That may get more interesting when
3313
+ # removing 0 dimensional axis is allowed (since an iterator can grow then)
3314
+ assert_raises(ValueError, nditer,
3315
+ (arr, arr[:, None]), flags=['multi_index'])
3316
+
3317
+
3318
+ def test_iter_too_large_with_multiindex():
3319
+ # When a multi index is being tracked, the error is delayed this
3320
+ # checks the delayed error messages and getting below that by
3321
+ # removing an axis.
3322
+ base_size = 2**10
3323
+ num = 1
3324
+ while base_size**num < np.iinfo(np.intp).max:
3325
+ num += 1
3326
+
3327
+ shape_template = [1, 1] * num
3328
+ arrays = []
3329
+ for i in range(num):
3330
+ shape = shape_template[:]
3331
+ shape[i * 2] = 2**10
3332
+ arrays.append(np.empty(shape))
3333
+ arrays = tuple(arrays)
3334
+
3335
+ # arrays are now too large to be broadcast. The different modes test
3336
+ # different nditer functionality with or without GIL.
3337
+ for mode in range(6):
3338
+ with assert_raises(ValueError):
3339
+ _multiarray_tests.test_nditer_too_large(arrays, -1, mode)
3340
+ # but if we do nothing with the nditer, it can be constructed:
3341
+ _multiarray_tests.test_nditer_too_large(arrays, -1, 7)
3342
+
3343
+ # When an axis is removed, things should work again (half the time):
3344
+ for i in range(num):
3345
+ for mode in range(6):
3346
+ # an axis with size 1024 is removed:
3347
+ _multiarray_tests.test_nditer_too_large(arrays, i * 2, mode)
3348
+ # an axis with size 1 is removed:
3349
+ with assert_raises(ValueError):
3350
+ _multiarray_tests.test_nditer_too_large(arrays, i * 2 + 1, mode)
3351
+
3352
+
3353
+ def test_invalid_call_of_enable_external_loop():
3354
+ with pytest.raises(ValueError,
3355
+ match='Iterator flag EXTERNAL_LOOP cannot be used'):
3356
+ np.nditer(([[1], [2]], [3, 4]), ['multi_index']).enable_external_loop()
3357
+
3358
+
3359
+ def test_writebacks():
3360
+ a = np.arange(6, dtype='f4')
3361
+ au = a.byteswap()
3362
+ au = au.view(au.dtype.newbyteorder())
3363
+ assert_(a.dtype.byteorder != au.dtype.byteorder)
3364
+ it = nditer(au, [], [['readwrite', 'updateifcopy']],
3365
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3366
+ with it:
3367
+ it.operands[0][:] = 100
3368
+ assert_equal(au, 100)
3369
+ # do it again, this time raise an error,
3370
+ it = nditer(au, [], [['readwrite', 'updateifcopy']],
3371
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3372
+ try:
3373
+ with it:
3374
+ assert_equal(au.flags.writeable, False)
3375
+ it.operands[0][:] = 0
3376
+ raise ValueError('exit context manager on exception')
3377
+ except Exception:
3378
+ pass
3379
+ assert_equal(au, 0)
3380
+ assert_equal(au.flags.writeable, True)
3381
+ # cannot reuse i outside context manager
3382
+ assert_raises(ValueError, getattr, it, 'operands')
3383
+
3384
+ it = nditer(au, [], [['readwrite', 'updateifcopy']],
3385
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3386
+ with it:
3387
+ x = it.operands[0]
3388
+ x[:] = 6
3389
+ assert_(x.flags.writebackifcopy)
3390
+ assert_equal(au, 6)
3391
+ assert_(not x.flags.writebackifcopy)
3392
+ x[:] = 123 # x.data still valid
3393
+ assert_equal(au, 6) # but not connected to au
3394
+
3395
+ it = nditer(au, [],
3396
+ [['readwrite', 'updateifcopy']],
3397
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3398
+ # reentering works
3399
+ with it:
3400
+ with it:
3401
+ for x in it:
3402
+ x[...] = 123
3403
+
3404
+ it = nditer(au, [],
3405
+ [['readwrite', 'updateifcopy']],
3406
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3407
+ # make sure exiting the inner context manager closes the iterator
3408
+ with it:
3409
+ with it:
3410
+ for x in it:
3411
+ x[...] = 123
3412
+ assert_raises(ValueError, getattr, it, 'operands')
3413
+ # do not crash if original data array is decrefed
3414
+ it = nditer(au, [],
3415
+ [['readwrite', 'updateifcopy']],
3416
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3417
+ del au
3418
+ with it:
3419
+ for x in it:
3420
+ x[...] = 123
3421
+ # make sure we cannot reenter the closed iterator
3422
+ enter = it.__enter__
3423
+ assert_raises(RuntimeError, enter)
3424
+
3425
+ def test_close_equivalent():
3426
+ ''' using a context amanger and using nditer.close are equivalent
3427
+ '''
3428
+ def add_close(x, y, out=None):
3429
+ addop = np.add
3430
+ it = np.nditer([x, y, out], [],
3431
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
3432
+ for (a, b, c) in it:
3433
+ addop(a, b, out=c)
3434
+ ret = it.operands[2]
3435
+ it.close()
3436
+ return ret
3437
+
3438
+ def add_context(x, y, out=None):
3439
+ addop = np.add
3440
+ it = np.nditer([x, y, out], [],
3441
+ [['readonly'], ['readonly'], ['writeonly', 'allocate']])
3442
+ with it:
3443
+ for (a, b, c) in it:
3444
+ addop(a, b, out=c)
3445
+ return it.operands[2]
3446
+ z = add_close(range(5), range(5))
3447
+ assert_equal(z, range(0, 10, 2))
3448
+ z = add_context(range(5), range(5))
3449
+ assert_equal(z, range(0, 10, 2))
3450
+
3451
+ def test_close_raises():
3452
+ it = np.nditer(np.arange(3))
3453
+ assert_equal(next(it), 0)
3454
+ it.close()
3455
+ assert_raises(StopIteration, next, it)
3456
+ assert_raises(ValueError, getattr, it, 'operands')
3457
+
3458
+ def test_close_parameters():
3459
+ it = np.nditer(np.arange(3))
3460
+ assert_raises(TypeError, it.close, 1)
3461
+
3462
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
3463
+ def test_warn_noclose():
3464
+ a = np.arange(6, dtype='f4')
3465
+ au = a.byteswap()
3466
+ au = au.view(au.dtype.newbyteorder())
3467
+ with pytest.warns(RuntimeWarning):
3468
+ it = np.nditer(au, [], [['readwrite', 'updateifcopy']],
3469
+ casting='equiv', op_dtypes=[np.dtype('f4')])
3470
+ del it
3471
+
3472
+ @pytest.mark.parametrize(["in_dtype", "buf_dtype"],
3473
+ [("i", "O"), ("O", "i"), # most simple cases
3474
+ ("i,O", "O,O"), # structured partially only copying O
3475
+ ("O,i", "i,O"), # structured casting to and from O
3476
+ ])
3477
+ @pytest.mark.parametrize("steps", [1, 2, 3])
3478
+ def test_partial_iteration_cleanup(in_dtype, buf_dtype, steps):
3479
+ """
3480
+ Checks for reference counting leaks during cleanup. Using explicit
3481
+ reference counts lead to occasional false positives (at least in parallel
3482
+ test setups). This test now should still test leaks correctly when
3483
+ run e.g. with pytest-valgrind or pytest-leaks
3484
+ """
3485
+ value = 2**30 + 1 # just a random value that Python won't intern
3486
+ arr = np.full(int(ncu.BUFSIZE * 2.5), value).astype(in_dtype)
3487
+
3488
+ it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
3489
+ flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
3490
+ for step in range(steps):
3491
+ # The iteration finishes in 3 steps, the first two are partial
3492
+ next(it)
3493
+
3494
+ del it # not necessary, but we test the cleanup
3495
+
3496
+ # Repeat the test with `iternext`
3497
+ it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
3498
+ flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
3499
+ for step in range(steps):
3500
+ it.iternext()
3501
+
3502
+ del it # not necessary, but we test the cleanup
3503
+
3504
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
3505
+ @pytest.mark.parametrize(["in_dtype", "buf_dtype"],
3506
+ [("O", "i"), # most simple cases
3507
+ ("O,i", "i,O"), # structured casting to and from O
3508
+ ])
3509
+ def test_partial_iteration_error(in_dtype, buf_dtype):
3510
+ value = 123 # relies on python cache (leak-check will still find it)
3511
+ arr = np.full(int(ncu.BUFSIZE * 2.5), value).astype(in_dtype)
3512
+ if in_dtype == "O":
3513
+ arr[int(ncu.BUFSIZE * 1.5)] = None
3514
+ else:
3515
+ arr[int(ncu.BUFSIZE * 1.5)]["f0"] = None
3516
+
3517
+ count = sys.getrefcount(value)
3518
+
3519
+ it = np.nditer(arr, op_dtypes=[np.dtype(buf_dtype)],
3520
+ flags=["buffered", "external_loop", "refs_ok"], casting="unsafe")
3521
+ with pytest.raises(TypeError):
3522
+ # pytest.raises seems to have issues with the error originating
3523
+ # in the for loop, so manually unravel:
3524
+ next(it)
3525
+ next(it) # raises TypeError
3526
+
3527
+ # Repeat the test with `iternext` after resetting, the buffers should
3528
+ # already be cleared from any references, so resetting is sufficient.
3529
+ it.reset()
3530
+ with pytest.raises(TypeError):
3531
+ it.iternext()
3532
+ it.iternext()
3533
+
3534
+ assert count == sys.getrefcount(value)
3535
+
3536
+
3537
+ def test_arbitrary_number_of_ops():
3538
+ # 2*16 + 1 is still just a few kiB, so should be fast and easy to deal with
3539
+ # but larger than any small custom integer.
3540
+ ops = [np.arange(10) for a in range(2**16 + 1)]
3541
+
3542
+ it = np.nditer(ops)
3543
+ for i, vals in enumerate(it):
3544
+ assert all(v == i for v in vals)
3545
+
3546
+
3547
+ def test_arbitrary_number_of_ops_nested():
3548
+ # 2*16 + 1 is still just a few kiB, so should be fast and easy to deal with
3549
+ # but larger than any small custom integer.
3550
+ ops = [np.arange(10) for a in range(2**16 + 1)]
3551
+
3552
+ it = np.nested_iters(ops, [[0], []])
3553
+ for i, vals in enumerate(it):
3554
+ assert all(v == i for v in vals)
3555
+
3556
+
3557
+ @pytest.mark.slow
3558
+ @pytest.mark.skipif(not IS_64BIT, reason="test requires 64-bit system")
3559
+ @requires_memory(9 * np.iinfo(np.intc).max)
3560
+ @pytest.mark.thread_unsafe(reason="crashes with low memory")
3561
+ def test_arbitrary_number_of_ops_error():
3562
+ # A different error may happen for more than integer operands, but that
3563
+ # is too large to test nicely.
3564
+ a = np.ones(1)
3565
+ args = [a] * (np.iinfo(np.intc).max + 1)
3566
+ with pytest.raises(ValueError, match="Too many operands to nditer"):
3567
+ np.nditer(args)
3568
+
3569
+ with pytest.raises(ValueError, match="Too many operands to nditer"):
3570
+ np.nested_iters(args, [[0], []])
3571
+
3572
+
3573
+ @pytest.mark.thread_unsafe(reason="capfd is thread-unsafe")
3574
+ def test_debug_print(capfd):
3575
+ """
3576
+ Matches the expected output of a debug print with the actual output.
3577
+ Note that the iterator dump should not be considered stable API,
3578
+ this test is mainly to ensure the print does not crash.
3579
+
3580
+ Currently uses a subprocess to avoid dealing with the C level `printf`s.
3581
+ """
3582
+ # the expected output with all addresses and sizes stripped (they vary
3583
+ # and/or are platform dependent).
3584
+ expected = """
3585
+ ------ BEGIN ITERATOR DUMP ------
3586
+ | Iterator Address:
3587
+ | ItFlags: BUFFER REDUCE
3588
+ | NDim: 2
3589
+ | NOp: 2
3590
+ | IterSize: 50
3591
+ | IterStart: 0
3592
+ | IterEnd: 50
3593
+ | IterIndex: 0
3594
+ | Iterator SizeOf:
3595
+ | BufferData SizeOf:
3596
+ | AxisData SizeOf:
3597
+ |
3598
+ | Perm: 0 1
3599
+ | DTypes:
3600
+ | DTypes: dtype('float64') dtype('int32')
3601
+ | InitDataPtrs:
3602
+ | BaseOffsets: 0 0
3603
+ | Ptrs:
3604
+ | User/buffer ptrs:
3605
+ | Operands:
3606
+ | Operand DTypes: dtype('int64') dtype('float64')
3607
+ | OpItFlags:
3608
+ | Flags[0]: READ CAST
3609
+ | Flags[1]: READ WRITE CAST REDUCE
3610
+ |
3611
+ | BufferData:
3612
+ | BufferSize: 50
3613
+ | Size: 5
3614
+ | BufIterEnd: 5
3615
+ | BUFFER CoreSize: 5
3616
+ | REDUCE Pos: 0
3617
+ | REDUCE OuterSize: 10
3618
+ | REDUCE OuterDim: 1
3619
+ | Strides: 8 4
3620
+ | REDUCE Outer Strides: 40 0
3621
+ | REDUCE Outer Ptrs:
3622
+ | ReadTransferFn:
3623
+ | ReadTransferData:
3624
+ | WriteTransferFn:
3625
+ | WriteTransferData:
3626
+ | Buffers:
3627
+ |
3628
+ | AxisData[0]:
3629
+ | Shape: 5
3630
+ | Index: 0
3631
+ | Strides: 16 8
3632
+ | AxisData[1]:
3633
+ | Shape: 10
3634
+ | Index: 0
3635
+ | Strides: 80 0
3636
+ ------- END ITERATOR DUMP -------
3637
+ """.strip().splitlines()
3638
+
3639
+ arr1 = np.arange(100, dtype=np.int64).reshape(10, 10)[:, ::2]
3640
+ arr2 = np.arange(5.)
3641
+ it = np.nditer((arr1, arr2), op_dtypes=["d", "i4"], casting="unsafe",
3642
+ flags=["reduce_ok", "buffered"],
3643
+ op_flags=[["readonly"], ["readwrite"]])
3644
+ it.debug_print()
3645
+ res = capfd.readouterr().out
3646
+ res = res.strip().splitlines()
3647
+
3648
+ assert len(res) == len(expected)
3649
+ for res_line, expected_line in zip(res, expected):
3650
+ # The actual output may have additional pointers listed that are
3651
+ # stripped from the example output:
3652
+ assert res_line.startswith(expected_line.strip())
3653
+
3654
+
3655
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
3656
+ def test_signature_constructor():
3657
+ sig = inspect.signature(np.nditer)
3658
+
3659
+ assert sig.parameters
3660
+ assert "self" not in sig.parameters
3661
+ assert "args" not in sig.parameters
3662
+ assert "kwargs" not in sig.parameters
3663
+
3664
+
3665
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
3666
+ @pytest.mark.parametrize(
3667
+ "method",
3668
+ [fn for name, fn in vars(np.nditer).items() if callable(fn) and name[0] != "_"],
3669
+ )
3670
+ def test_signature_methods(method):
3671
+ sig = inspect.signature(method)
3672
+
3673
+ assert "self" in sig.parameters
3674
+ assert sig.parameters["self"].kind is inspect.Parameter.POSITIONAL_ONLY
3675
+
3676
+
3677
+ def test_nditer_multi_index_no_segfault():
3678
+ class BadSequence:
3679
+ def __len__(self):
3680
+ return 2
3681
+
3682
+ def __getitem__(self, i):
3683
+ if i == 1:
3684
+ raise RuntimeError("intentional error")
3685
+ return 0
3686
+
3687
+ arr = np.zeros((3, 4))
3688
+ it = np.nditer(arr, flags=["multi_index"])
3689
+ with pytest.raises(RuntimeError, match="intentional error"):
3690
+ it.multi_index = BadSequence()