numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,2752 @@
1
+ """
2
+ Utility function to facilitate testing.
3
+
4
+ """
5
+ import concurrent.futures
6
+ import contextlib
7
+ import gc
8
+ import importlib.metadata
9
+ import operator
10
+ import os
11
+ import pathlib
12
+ import platform
13
+ import pprint
14
+ import re
15
+ import shutil
16
+ import sys
17
+ import sysconfig
18
+ import threading
19
+ import warnings
20
+ from functools import partial, wraps
21
+ from io import StringIO
22
+ from tempfile import mkdtemp, mkstemp
23
+ from unittest.case import SkipTest
24
+ from warnings import WarningMessage
25
+
26
+ import numpy as np
27
+ import numpy.linalg._umath_linalg
28
+ from numpy import isfinite, isinf, isnan
29
+ from numpy._core import arange, array, array_repr, empty, float32, intp, isnat, ndarray
30
+
31
+ __all__ = [
32
+ 'assert_equal', 'assert_almost_equal', 'assert_approx_equal',
33
+ 'assert_array_equal', 'assert_array_less', 'assert_string_equal',
34
+ 'assert_array_almost_equal', 'assert_raises', 'build_err_msg',
35
+ 'decorate_methods', 'jiffies', 'memusage', 'print_assert_equal',
36
+ 'rundocs', 'runstring', 'verbose', 'measure',
37
+ 'assert_', 'assert_array_almost_equal_nulp', 'assert_raises_regex',
38
+ 'assert_array_max_ulp', 'assert_warns', 'assert_no_warnings',
39
+ 'assert_allclose', 'IgnoreException', 'clear_and_catch_warnings',
40
+ 'SkipTest', 'KnownFailureException', 'temppath', 'tempdir', 'IS_PYPY',
41
+ 'HAS_REFCOUNT', "IS_WASM", 'suppress_warnings', 'assert_array_compare',
42
+ 'assert_no_gc_cycles', 'break_cycles', 'HAS_LAPACK64', 'IS_PYSTON',
43
+ 'IS_MUSL', 'check_support_sve', 'NOGIL_BUILD',
44
+ 'IS_EDITABLE', 'IS_INSTALLED', 'NUMPY_ROOT', 'run_threaded', 'IS_64BIT',
45
+ 'BLAS_SUPPORTS_FPE',
46
+ ]
47
+
48
+
49
+ class KnownFailureException(Exception):
50
+ '''Raise this exception to mark a test as a known failing test.'''
51
+ pass
52
+
53
+
54
+ KnownFailureTest = KnownFailureException # backwards compat
55
+ verbose = 0
56
+
57
+ NUMPY_ROOT = pathlib.Path(np.__file__).parent
58
+
59
+ try:
60
+ np_dist = importlib.metadata.distribution('numpy')
61
+ except importlib.metadata.PackageNotFoundError:
62
+ IS_INSTALLED = IS_EDITABLE = False
63
+ else:
64
+ IS_INSTALLED = True
65
+ try:
66
+ if sys.version_info >= (3, 13):
67
+ IS_EDITABLE = np_dist.origin.dir_info.editable
68
+ else:
69
+ # Backport importlib.metadata.Distribution.origin
70
+ import json # noqa: E401
71
+ import types
72
+ origin = json.loads(
73
+ np_dist.read_text('direct_url.json') or '{}',
74
+ object_hook=lambda data: types.SimpleNamespace(**data),
75
+ )
76
+ IS_EDITABLE = origin.dir_info.editable
77
+ except AttributeError:
78
+ IS_EDITABLE = False
79
+
80
+ # spin installs numpy directly via meson, instead of using meson-python, and
81
+ # runs the module by setting PYTHONPATH. This is problematic because the
82
+ # resulting installation lacks the Python metadata (.dist-info), and numpy
83
+ # might already be installed on the environment, causing us to find its
84
+ # metadata, even though we are not actually loading that package.
85
+ # Work around this issue by checking if the numpy root matches.
86
+ if not IS_EDITABLE and np_dist.locate_file('numpy') != NUMPY_ROOT:
87
+ IS_INSTALLED = False
88
+
89
+ IS_WASM = platform.machine() in ["wasm32", "wasm64"]
90
+ IS_PYPY = sys.implementation.name == 'pypy'
91
+ IS_PYSTON = hasattr(sys, "pyston_version_info")
92
+ HAS_REFCOUNT = getattr(sys, 'getrefcount', None) is not None and not IS_PYSTON
93
+ BLAS_SUPPORTS_FPE = np._core._multiarray_umath._blas_supports_fpe(None)
94
+
95
+ HAS_LAPACK64 = numpy.linalg._umath_linalg._ilp64
96
+
97
+ IS_MUSL = False
98
+ # alternate way is
99
+ # from packaging.tags import sys_tags
100
+ # _tags = list(sys_tags())
101
+ # if 'musllinux' in _tags[0].platform:
102
+ _v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
103
+ if 'musl' in _v:
104
+ IS_MUSL = True
105
+
106
+ NOGIL_BUILD = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
107
+ IS_64BIT = np.dtype(np.intp).itemsize == 8
108
+
109
+ def assert_(val, msg=''):
110
+ """
111
+ Assert that works in release mode.
112
+ Accepts callable msg to allow deferring evaluation until failure.
113
+
114
+ The Python built-in ``assert`` does not work when executing code in
115
+ optimized mode (the ``-O`` flag) - no byte-code is generated for it.
116
+
117
+ For documentation on usage, refer to the Python documentation.
118
+
119
+ """
120
+ __tracebackhide__ = True # Hide traceback for py.test
121
+ if not val:
122
+ try:
123
+ smsg = msg()
124
+ except TypeError:
125
+ smsg = msg
126
+ raise AssertionError(smsg)
127
+
128
+
129
+ if os.name == 'nt':
130
+ # Code "stolen" from enthought/debug/memusage.py
131
+ def GetPerformanceAttributes(object, counter, instance=None,
132
+ inum=-1, format=None, machine=None):
133
+ # NOTE: Many counters require 2 samples to give accurate results,
134
+ # including "% Processor Time" (as by definition, at any instant, a
135
+ # thread's CPU usage is either 0 or 100). To read counters like this,
136
+ # you should copy this function, but keep the counter open, and call
137
+ # CollectQueryData() each time you need to know.
138
+ # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
139
+ # (dead link)
140
+ # My older explanation for this was that the "AddCounter" process
141
+ # forced the CPU to 100%, but the above makes more sense :)
142
+ import win32pdh
143
+ if format is None:
144
+ format = win32pdh.PDH_FMT_LONG
145
+ path = win32pdh.MakeCounterPath((machine, object, instance, None,
146
+ inum, counter))
147
+ hq = win32pdh.OpenQuery()
148
+ try:
149
+ hc = win32pdh.AddCounter(hq, path)
150
+ try:
151
+ win32pdh.CollectQueryData(hq)
152
+ type, val = win32pdh.GetFormattedCounterValue(hc, format)
153
+ return val
154
+ finally:
155
+ win32pdh.RemoveCounter(hc)
156
+ finally:
157
+ win32pdh.CloseQuery(hq)
158
+
159
+ def memusage(processName="python", instance=0):
160
+ # from win32pdhutil, part of the win32all package
161
+ import win32pdh
162
+ return GetPerformanceAttributes("Process", "Virtual Bytes",
163
+ processName, instance,
164
+ win32pdh.PDH_FMT_LONG, None)
165
+ elif sys.platform[:5] == 'linux':
166
+
167
+ def memusage(_proc_pid_stat=None):
168
+ """
169
+ Return virtual memory size in bytes of the running python.
170
+
171
+ """
172
+ _proc_pid_stat = _proc_pid_stat or f'/proc/{os.getpid()}/stat'
173
+ try:
174
+ with open(_proc_pid_stat) as f:
175
+ l = f.readline().split(' ')
176
+ return int(l[22])
177
+ except Exception:
178
+ return
179
+ else:
180
+ def memusage():
181
+ """
182
+ Return memory usage of running python. [Not implemented]
183
+
184
+ """
185
+ raise NotImplementedError
186
+
187
+
188
+ if sys.platform[:5] == 'linux':
189
+ def jiffies(_proc_pid_stat=None, _load_time=None):
190
+ """
191
+ Return number of jiffies elapsed.
192
+
193
+ Return number of jiffies (1/100ths of a second) that this
194
+ process has been scheduled in user mode. See man 5 proc.
195
+
196
+ """
197
+ _proc_pid_stat = _proc_pid_stat or f'/proc/{os.getpid()}/stat'
198
+ _load_time = _load_time or []
199
+ import time
200
+ if not _load_time:
201
+ _load_time.append(time.time())
202
+ try:
203
+ with open(_proc_pid_stat) as f:
204
+ l = f.readline().split(' ')
205
+ return int(l[13])
206
+ except Exception:
207
+ return int(100 * (time.time() - _load_time[0]))
208
+ else:
209
+ # os.getpid is not in all platforms available.
210
+ # Using time is safe but inaccurate, especially when process
211
+ # was suspended or sleeping.
212
+ def jiffies(_load_time=[]):
213
+ """
214
+ Return number of jiffies elapsed.
215
+
216
+ Return number of jiffies (1/100ths of a second) that this
217
+ process has been scheduled in user mode. See man 5 proc.
218
+
219
+ """
220
+ import time
221
+ if not _load_time:
222
+ _load_time.append(time.time())
223
+ return int(100 * (time.time() - _load_time[0]))
224
+
225
+
226
+ def build_err_msg(arrays, err_msg, header='Items are not equal:',
227
+ verbose=True, names=('ACTUAL', 'DESIRED'), precision=8):
228
+ msg = ['\n' + header]
229
+ err_msg = str(err_msg)
230
+ if err_msg:
231
+ if err_msg.find('\n') == -1 and len(err_msg) < 79 - len(header):
232
+ msg = [msg[0] + ' ' + err_msg]
233
+ else:
234
+ msg.append(err_msg)
235
+ if verbose:
236
+ for i, a in enumerate(arrays):
237
+
238
+ if isinstance(a, ndarray):
239
+ # precision argument is only needed if the objects are ndarrays
240
+ r_func = partial(array_repr, precision=precision)
241
+ else:
242
+ r_func = repr
243
+
244
+ try:
245
+ r = r_func(a)
246
+ except Exception as exc:
247
+ r = f'[repr failed for <{type(a).__name__}>: {exc}]'
248
+ if r.count('\n') > 3:
249
+ r = '\n'.join(r.splitlines()[:3])
250
+ r += '...'
251
+ msg.append(f' {names[i]}: {r}')
252
+ return '\n'.join(msg)
253
+
254
+
255
+ def assert_equal(actual, desired, err_msg='', verbose=True, *, strict=False):
256
+ """
257
+ Raises an AssertionError if two objects are not equal.
258
+
259
+ Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
260
+ check that all elements of these objects are equal. An exception is raised
261
+ at the first conflicting values.
262
+
263
+ This function handles NaN comparisons as if NaN was a "normal" number.
264
+ That is, AssertionError is not raised if both objects have NaNs in the same
265
+ positions. This is in contrast to the IEEE standard on NaNs, which says
266
+ that NaN compared to anything must return False.
267
+
268
+ Parameters
269
+ ----------
270
+ actual : array_like
271
+ The object to check.
272
+ desired : array_like
273
+ The expected object.
274
+ err_msg : str, optional
275
+ The error message to be printed in case of failure.
276
+ verbose : bool, optional
277
+ If True, the conflicting values are appended to the error message.
278
+ strict : bool, optional
279
+ If True and either of the `actual` and `desired` arguments is an array,
280
+ raise an ``AssertionError`` when either the shape or the data type of
281
+ the arguments does not match. If neither argument is an array, this
282
+ parameter has no effect.
283
+
284
+ .. versionadded:: 2.0.0
285
+
286
+ Raises
287
+ ------
288
+ AssertionError
289
+ If actual and desired are not equal.
290
+
291
+ See Also
292
+ --------
293
+ assert_allclose
294
+ assert_array_almost_equal_nulp,
295
+ assert_array_max_ulp,
296
+
297
+ Notes
298
+ -----
299
+ By default, when one of `actual` and `desired` is a scalar and the other is
300
+ an array, the function checks that each element of the array is equal to
301
+ the scalar. This behaviour can be disabled by setting ``strict==True``.
302
+
303
+ Examples
304
+ --------
305
+ >>> np.testing.assert_equal([4, 5], [4, 6])
306
+ Traceback (most recent call last):
307
+ ...
308
+ AssertionError:
309
+ Items are not equal:
310
+ item=1
311
+ ACTUAL: 5
312
+ DESIRED: 6
313
+
314
+ The following comparison does not raise an exception. There are NaNs
315
+ in the inputs, but they are in the same positions.
316
+
317
+ >>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
318
+
319
+ As mentioned in the Notes section, `assert_equal` has special
320
+ handling for scalars when one of the arguments is an array.
321
+ Here, the test checks that each value in `x` is 3:
322
+
323
+ >>> x = np.full((2, 5), fill_value=3)
324
+ >>> np.testing.assert_equal(x, 3)
325
+
326
+ Use `strict` to raise an AssertionError when comparing a scalar with an
327
+ array of a different shape:
328
+
329
+ >>> np.testing.assert_equal(x, 3, strict=True)
330
+ Traceback (most recent call last):
331
+ ...
332
+ AssertionError:
333
+ Arrays are not equal
334
+ <BLANKLINE>
335
+ (shapes (2, 5), () mismatch)
336
+ ACTUAL: array([[3, 3, 3, 3, 3],
337
+ [3, 3, 3, 3, 3]])
338
+ DESIRED: array(3)
339
+
340
+ The `strict` parameter also ensures that the array data types match:
341
+
342
+ >>> x = np.array([2, 2, 2])
343
+ >>> y = np.array([2., 2., 2.], dtype=np.float32)
344
+ >>> np.testing.assert_equal(x, y, strict=True)
345
+ Traceback (most recent call last):
346
+ ...
347
+ AssertionError:
348
+ Arrays are not equal
349
+ <BLANKLINE>
350
+ (dtypes int64, float32 mismatch)
351
+ ACTUAL: array([2, 2, 2])
352
+ DESIRED: array([2., 2., 2.], dtype=float32)
353
+ """
354
+ __tracebackhide__ = True # Hide traceback for py.test
355
+ if isinstance(desired, dict):
356
+ if not isinstance(actual, dict):
357
+ raise AssertionError(repr(type(actual)))
358
+ assert_equal(len(actual), len(desired), err_msg, verbose)
359
+ for k, i in desired.items():
360
+ if k not in actual:
361
+ raise AssertionError(repr(k))
362
+ assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}',
363
+ verbose)
364
+ return
365
+ if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
366
+ assert_equal(len(actual), len(desired), err_msg, verbose)
367
+ for k in range(len(desired)):
368
+ assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}',
369
+ verbose)
370
+ return
371
+ from numpy import imag, iscomplexobj, real
372
+ from numpy._core import isscalar, ndarray, signbit
373
+ if isinstance(actual, ndarray) or isinstance(desired, ndarray):
374
+ return assert_array_equal(actual, desired, err_msg, verbose,
375
+ strict=strict)
376
+ msg = build_err_msg([actual, desired], err_msg, verbose=verbose)
377
+
378
+ # Handle complex numbers: separate into real/imag to handle
379
+ # nan/inf/negative zero correctly
380
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
381
+ try:
382
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
383
+ except (ValueError, TypeError):
384
+ usecomplex = False
385
+
386
+ if usecomplex:
387
+ if iscomplexobj(actual):
388
+ actualr = real(actual)
389
+ actuali = imag(actual)
390
+ else:
391
+ actualr = actual
392
+ actuali = 0
393
+ if iscomplexobj(desired):
394
+ desiredr = real(desired)
395
+ desiredi = imag(desired)
396
+ else:
397
+ desiredr = desired
398
+ desiredi = 0
399
+ try:
400
+ assert_equal(actualr, desiredr)
401
+ assert_equal(actuali, desiredi)
402
+ except AssertionError:
403
+ raise AssertionError(msg)
404
+
405
+ # isscalar test to check cases such as [np.nan] != np.nan
406
+ if isscalar(desired) != isscalar(actual):
407
+ raise AssertionError(msg)
408
+
409
+ try:
410
+ isdesnat = isnat(desired)
411
+ isactnat = isnat(actual)
412
+ dtypes_match = (np.asarray(desired).dtype.type ==
413
+ np.asarray(actual).dtype.type)
414
+ if isdesnat and isactnat:
415
+ # If both are NaT (and have the same dtype -- datetime or
416
+ # timedelta) they are considered equal.
417
+ if dtypes_match:
418
+ return
419
+ else:
420
+ raise AssertionError(msg)
421
+
422
+ except (TypeError, ValueError, NotImplementedError):
423
+ pass
424
+
425
+ # Inf/nan/negative zero handling
426
+ try:
427
+ isdesnan = isnan(desired)
428
+ isactnan = isnan(actual)
429
+ if isdesnan and isactnan:
430
+ return # both nan, so equal
431
+
432
+ # handle signed zero specially for floats
433
+ array_actual = np.asarray(actual)
434
+ array_desired = np.asarray(desired)
435
+ if (array_actual.dtype.char in 'Mm' or
436
+ array_desired.dtype.char in 'Mm'):
437
+ # version 1.18
438
+ # until this version, isnan failed for datetime64 and timedelta64.
439
+ # Now it succeeds but comparison to scalar with a different type
440
+ # emits a DeprecationWarning.
441
+ # Avoid that by skipping the next check
442
+ raise NotImplementedError('cannot compare to a scalar '
443
+ 'with a different type')
444
+
445
+ if desired == 0 and actual == 0:
446
+ if not signbit(desired) == signbit(actual):
447
+ raise AssertionError(msg)
448
+
449
+ except (TypeError, ValueError, NotImplementedError):
450
+ pass
451
+
452
+ try:
453
+ # Explicitly use __eq__ for comparison, gh-2552
454
+ if not (desired == actual):
455
+ raise AssertionError(msg)
456
+
457
+ except (DeprecationWarning, FutureWarning) as e:
458
+ # this handles the case when the two types are not even comparable
459
+ if 'elementwise == comparison' in e.args[0]:
460
+ raise AssertionError(msg)
461
+ else:
462
+ raise
463
+
464
+
465
+ def print_assert_equal(test_string, actual, desired):
466
+ """
467
+ Test if two objects are equal, and print an error message if test fails.
468
+
469
+ The test is performed with ``actual == desired``.
470
+
471
+ Parameters
472
+ ----------
473
+ test_string : str
474
+ The message supplied to AssertionError.
475
+ actual : object
476
+ The object to test for equality against `desired`.
477
+ desired : object
478
+ The expected result.
479
+
480
+ Examples
481
+ --------
482
+ >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
483
+ >>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
484
+ Traceback (most recent call last):
485
+ ...
486
+ AssertionError: Test XYZ of func xyz failed
487
+ ACTUAL:
488
+ [0, 1]
489
+ DESIRED:
490
+ [0, 2]
491
+
492
+ """
493
+ __tracebackhide__ = True # Hide traceback for py.test
494
+ import pprint
495
+
496
+ if not (actual == desired):
497
+ msg = StringIO()
498
+ msg.write(test_string)
499
+ msg.write(' failed\nACTUAL: \n')
500
+ pprint.pprint(actual, msg)
501
+ msg.write('DESIRED: \n')
502
+ pprint.pprint(desired, msg)
503
+ raise AssertionError(msg.getvalue())
504
+
505
+
506
+ def assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True):
507
+ """
508
+ Raises an AssertionError if two items are not equal up to desired
509
+ precision.
510
+
511
+ .. note:: It is recommended to use one of `assert_allclose`,
512
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
513
+ instead of this function for more consistent floating point
514
+ comparisons.
515
+
516
+ The test verifies that the elements of `actual` and `desired` satisfy::
517
+
518
+ abs(desired-actual) < float64(1.5 * 10**(-decimal))
519
+
520
+ That is a looser test than originally documented, but agrees with what the
521
+ actual implementation in `assert_array_almost_equal` did up to rounding
522
+ vagaries. An exception is raised at conflicting values. For ndarrays this
523
+ delegates to assert_array_almost_equal
524
+
525
+ Parameters
526
+ ----------
527
+ actual : array_like
528
+ The object to check.
529
+ desired : array_like
530
+ The expected object.
531
+ decimal : int, optional
532
+ Desired precision, default is 7.
533
+ err_msg : str, optional
534
+ The error message to be printed in case of failure.
535
+ verbose : bool, optional
536
+ If True, the conflicting values are appended to the error message.
537
+
538
+ Raises
539
+ ------
540
+ AssertionError
541
+ If actual and desired are not equal up to specified precision.
542
+
543
+ See Also
544
+ --------
545
+ assert_allclose: Compare two array_like objects for equality with desired
546
+ relative and/or absolute precision.
547
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
548
+
549
+ Examples
550
+ --------
551
+ >>> from numpy.testing import assert_almost_equal
552
+ >>> assert_almost_equal(2.3333333333333, 2.33333334)
553
+ >>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
554
+ Traceback (most recent call last):
555
+ ...
556
+ AssertionError:
557
+ Arrays are not almost equal to 10 decimals
558
+ ACTUAL: 2.3333333333333
559
+ DESIRED: 2.33333334
560
+
561
+ >>> assert_almost_equal(np.array([1.0,2.3333333333333]),
562
+ ... np.array([1.0,2.33333334]), decimal=9)
563
+ Traceback (most recent call last):
564
+ ...
565
+ AssertionError:
566
+ Arrays are not almost equal to 9 decimals
567
+ <BLANKLINE>
568
+ Mismatched elements: 1 / 2 (50%)
569
+ Max absolute difference among violations: 6.66669964e-09
570
+ Max relative difference among violations: 2.85715698e-09
571
+ ACTUAL: array([1. , 2.333333333])
572
+ DESIRED: array([1. , 2.33333334])
573
+
574
+ """
575
+ __tracebackhide__ = True # Hide traceback for py.test
576
+ from numpy import imag, iscomplexobj, real
577
+ from numpy._core import ndarray
578
+
579
+ # Handle complex numbers: separate into real/imag to handle
580
+ # nan/inf/negative zero correctly
581
+ # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
582
+ try:
583
+ usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
584
+ except ValueError:
585
+ usecomplex = False
586
+
587
+ def _build_err_msg():
588
+ header = ('Arrays are not almost equal to %d decimals' % decimal)
589
+ return build_err_msg([actual, desired], err_msg, verbose=verbose,
590
+ header=header)
591
+
592
+ if usecomplex:
593
+ if iscomplexobj(actual):
594
+ actualr = real(actual)
595
+ actuali = imag(actual)
596
+ else:
597
+ actualr = actual
598
+ actuali = 0
599
+ if iscomplexobj(desired):
600
+ desiredr = real(desired)
601
+ desiredi = imag(desired)
602
+ else:
603
+ desiredr = desired
604
+ desiredi = 0
605
+ try:
606
+ assert_almost_equal(actualr, desiredr, decimal=decimal)
607
+ assert_almost_equal(actuali, desiredi, decimal=decimal)
608
+ except AssertionError:
609
+ raise AssertionError(_build_err_msg())
610
+
611
+ if isinstance(actual, (ndarray, tuple, list)) \
612
+ or isinstance(desired, (ndarray, tuple, list)):
613
+ return assert_array_almost_equal(actual, desired, decimal, err_msg)
614
+ try:
615
+ # If one of desired/actual is not finite, handle it specially here:
616
+ # check that both are nan if any is a nan, and test for equality
617
+ # otherwise
618
+ if not (isfinite(desired) and isfinite(actual)):
619
+ if isnan(desired) or isnan(actual):
620
+ if not (isnan(desired) and isnan(actual)):
621
+ raise AssertionError(_build_err_msg())
622
+ elif not desired == actual:
623
+ raise AssertionError(_build_err_msg())
624
+ return
625
+ except (NotImplementedError, TypeError):
626
+ pass
627
+ if abs(desired - actual) >= np.float64(1.5 * 10.0**(-decimal)):
628
+ raise AssertionError(_build_err_msg())
629
+
630
+
631
+ def assert_approx_equal(actual, desired, significant=7, err_msg='',
632
+ verbose=True):
633
+ """
634
+ Raises an AssertionError if two items are not equal up to significant
635
+ digits.
636
+
637
+ .. note:: It is recommended to use one of `assert_allclose`,
638
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
639
+ instead of this function for more consistent floating point
640
+ comparisons.
641
+
642
+ Given two numbers, check that they are approximately equal.
643
+ Approximately equal is defined as the number of significant digits
644
+ that agree.
645
+
646
+ Parameters
647
+ ----------
648
+ actual : scalar
649
+ The object to check.
650
+ desired : scalar
651
+ The expected object.
652
+ significant : int, optional
653
+ Desired precision, default is 7.
654
+ err_msg : str, optional
655
+ The error message to be printed in case of failure.
656
+ verbose : bool, optional
657
+ If True, the conflicting values are appended to the error message.
658
+
659
+ Raises
660
+ ------
661
+ AssertionError
662
+ If actual and desired are not equal up to specified precision.
663
+
664
+ See Also
665
+ --------
666
+ assert_allclose: Compare two array_like objects for equality with desired
667
+ relative and/or absolute precision.
668
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
669
+
670
+ Examples
671
+ --------
672
+ >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
673
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
674
+ ... significant=8)
675
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
676
+ ... significant=8)
677
+ Traceback (most recent call last):
678
+ ...
679
+ AssertionError:
680
+ Items are not equal to 8 significant digits:
681
+ ACTUAL: 1.234567e-21
682
+ DESIRED: 1.2345672e-21
683
+
684
+ the evaluated condition that raises the exception is
685
+
686
+ >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
687
+ True
688
+
689
+ """
690
+ __tracebackhide__ = True # Hide traceback for py.test
691
+ import numpy as np
692
+
693
+ (actual, desired) = map(float, (actual, desired))
694
+ if desired == actual:
695
+ return
696
+ # Normalized the numbers to be in range (-10.0,10.0)
697
+ # scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
698
+ with np.errstate(invalid='ignore'):
699
+ scale = 0.5 * (np.abs(desired) + np.abs(actual))
700
+ scale = np.power(10, np.floor(np.log10(scale)))
701
+ try:
702
+ sc_desired = desired / scale
703
+ except ZeroDivisionError:
704
+ sc_desired = 0.0
705
+ try:
706
+ sc_actual = actual / scale
707
+ except ZeroDivisionError:
708
+ sc_actual = 0.0
709
+ msg = build_err_msg(
710
+ [actual, desired], err_msg,
711
+ header='Items are not equal to %d significant digits:' % significant,
712
+ verbose=verbose)
713
+ try:
714
+ # If one of desired/actual is not finite, handle it specially here:
715
+ # check that both are nan if any is a nan, and test for equality
716
+ # otherwise
717
+ if not (isfinite(desired) and isfinite(actual)):
718
+ if isnan(desired) or isnan(actual):
719
+ if not (isnan(desired) and isnan(actual)):
720
+ raise AssertionError(msg)
721
+ elif not desired == actual:
722
+ raise AssertionError(msg)
723
+ return
724
+ except (TypeError, NotImplementedError):
725
+ pass
726
+ if np.abs(sc_desired - sc_actual) >= np.power(10., -(significant - 1)):
727
+ raise AssertionError(msg)
728
+
729
+
730
+ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='',
731
+ precision=6, equal_nan=True, equal_inf=True,
732
+ *, strict=False, names=('ACTUAL', 'DESIRED')):
733
+ __tracebackhide__ = True # Hide traceback for py.test
734
+ from numpy._core import all, array2string, errstate, inf, isnan, max, object_
735
+
736
+ x = np.asanyarray(x)
737
+ y = np.asanyarray(y)
738
+
739
+ # original array for output formatting
740
+ ox, oy = x, y
741
+
742
+ def isnumber(x):
743
+ return x.dtype.char in '?bhilqpBHILQPefdgFDG'
744
+
745
+ def istime(x):
746
+ return x.dtype.char in "Mm"
747
+
748
+ def isvstring(x):
749
+ return x.dtype.char == "T"
750
+
751
+ def func_assert_same_pos(x, y, func=isnan, hasval='nan'):
752
+ """Handling nan/inf.
753
+
754
+ Combine results of running func on x and y, checking that they are True
755
+ at the same locations.
756
+
757
+ """
758
+ __tracebackhide__ = True # Hide traceback for py.test
759
+
760
+ x_id = func(x)
761
+ y_id = func(y)
762
+ # We include work-arounds here to handle three types of slightly
763
+ # pathological ndarray subclasses:
764
+ # (1) all() on `masked` array scalars can return masked arrays, so we
765
+ # use != True
766
+ # (2) __eq__ on some ndarray subclasses returns Python booleans
767
+ # instead of element-wise comparisons, so we cast to np.bool() and
768
+ # use isinstance(..., bool) checks
769
+ # (3) subclasses with bare-bones __array_function__ implementations may
770
+ # not implement np.all(), so favor using the .all() method
771
+ # We are not committed to supporting such subclasses, but it's nice to
772
+ # support them if possible.
773
+ if np.bool(x_id == y_id).all() != True:
774
+ msg = build_err_msg(
775
+ [x, y],
776
+ err_msg + '\n%s location mismatch:'
777
+ % (hasval), verbose=verbose, header=header,
778
+ names=names,
779
+ precision=precision)
780
+ raise AssertionError(msg)
781
+ # If there is a scalar, then here we know the array has the same
782
+ # flag as it everywhere, so we should return the scalar flag.
783
+ if isinstance(x_id, bool) or x_id.ndim == 0:
784
+ return np.bool(x_id)
785
+ elif isinstance(y_id, bool) or y_id.ndim == 0:
786
+ return np.bool(y_id)
787
+ else:
788
+ return y_id
789
+
790
+ try:
791
+ if strict:
792
+ cond = x.shape == y.shape and x.dtype == y.dtype
793
+ else:
794
+ cond = (x.shape == () or y.shape == ()) or x.shape == y.shape
795
+ if not cond:
796
+ if x.shape != y.shape:
797
+ reason = f'\n(shapes {x.shape}, {y.shape} mismatch)'
798
+ else:
799
+ reason = f'\n(dtypes {x.dtype}, {y.dtype} mismatch)'
800
+ msg = build_err_msg([x, y],
801
+ err_msg
802
+ + reason,
803
+ verbose=verbose, header=header,
804
+ names=names,
805
+ precision=precision)
806
+ raise AssertionError(msg)
807
+
808
+ flagged = np.bool(False)
809
+ if isnumber(x) and isnumber(y):
810
+ if equal_nan:
811
+ flagged = func_assert_same_pos(x, y, func=isnan, hasval='nan')
812
+
813
+ if equal_inf:
814
+ flagged |= func_assert_same_pos(x, y,
815
+ func=lambda xy: xy == +inf,
816
+ hasval='+inf')
817
+ flagged |= func_assert_same_pos(x, y,
818
+ func=lambda xy: xy == -inf,
819
+ hasval='-inf')
820
+
821
+ elif istime(x) and istime(y):
822
+ # If one is datetime64 and the other timedelta64 there is no point
823
+ if equal_nan and x.dtype.type == y.dtype.type:
824
+ flagged = func_assert_same_pos(x, y, func=isnat, hasval="NaT")
825
+
826
+ elif isvstring(x) and isvstring(y):
827
+ dt = x.dtype
828
+ if equal_nan and dt == y.dtype and hasattr(dt, 'na_object'):
829
+ is_nan = (isinstance(dt.na_object, float) and
830
+ np.isnan(dt.na_object))
831
+ bool_errors = 0
832
+ try:
833
+ bool(dt.na_object)
834
+ except TypeError:
835
+ bool_errors = 1
836
+ if is_nan or bool_errors:
837
+ # nan-like NA object
838
+ flagged = func_assert_same_pos(
839
+ x, y, func=isnan, hasval=x.dtype.na_object)
840
+
841
+ if flagged.ndim > 0:
842
+ x, y = x[~flagged], y[~flagged]
843
+ # Only do the comparison if actual values are left
844
+ if x.size == 0:
845
+ return
846
+ elif flagged:
847
+ # no sense doing comparison if everything is flagged.
848
+ return
849
+
850
+ val = comparison(x, y)
851
+ invalids = np.logical_not(val)
852
+
853
+ if isinstance(val, bool):
854
+ cond = val
855
+ reduced = array([val])
856
+ else:
857
+ reduced = val.ravel()
858
+ cond = reduced.all()
859
+
860
+ # The below comparison is a hack to ensure that fully masked
861
+ # results, for which val.ravel().all() returns np.ma.masked,
862
+ # do not trigger a failure (np.ma.masked != True evaluates as
863
+ # np.ma.masked, which is falsy).
864
+ if cond != True:
865
+ n_mismatch = reduced.size - reduced.sum(dtype=intp)
866
+ n_elements = flagged.size if flagged.ndim != 0 else reduced.size
867
+ percent_mismatch = 100 * n_mismatch / n_elements
868
+ remarks = [f'Mismatched elements: {n_mismatch} / {n_elements} '
869
+ f'({percent_mismatch:.3g}%)']
870
+
871
+ with errstate(all='ignore'):
872
+ # ignore errors for non-numeric types
873
+ with contextlib.suppress(TypeError):
874
+ error = abs(x - y)
875
+ if np.issubdtype(x.dtype, np.unsignedinteger):
876
+ error2 = abs(y - x)
877
+ np.minimum(error, error2, out=error)
878
+
879
+ reduced_error = error[invalids]
880
+ max_abs_error = max(reduced_error)
881
+ if getattr(error, 'dtype', object_) == object_:
882
+ remarks.append(
883
+ 'Max absolute difference among violations: '
884
+ + str(max_abs_error))
885
+ else:
886
+ remarks.append(
887
+ 'Max absolute difference among violations: '
888
+ + array2string(max_abs_error))
889
+
890
+ # note: this definition of relative error matches that one
891
+ # used by assert_allclose (found in np.isclose)
892
+ # Filter values where the divisor would be zero
893
+ nonzero = np.bool(y != 0)
894
+ nonzero_and_invalid = np.logical_and(invalids, nonzero)
895
+
896
+ if all(~nonzero_and_invalid):
897
+ max_rel_error = array(inf)
898
+ else:
899
+ nonzero_invalid_error = error[nonzero_and_invalid]
900
+ broadcasted_y = np.broadcast_to(y, error.shape)
901
+ nonzero_invalid_y = broadcasted_y[nonzero_and_invalid]
902
+ max_rel_error = max(nonzero_invalid_error
903
+ / abs(nonzero_invalid_y))
904
+
905
+ if getattr(error, 'dtype', object_) == object_:
906
+ remarks.append(
907
+ 'Max relative difference among violations: '
908
+ + str(max_rel_error))
909
+ else:
910
+ remarks.append(
911
+ 'Max relative difference among violations: '
912
+ + array2string(max_rel_error))
913
+ err_msg = str(err_msg)
914
+ err_msg += '\n' + '\n'.join(remarks)
915
+ msg = build_err_msg([ox, oy], err_msg,
916
+ verbose=verbose, header=header,
917
+ names=names,
918
+ precision=precision)
919
+ raise AssertionError(msg)
920
+ except ValueError:
921
+ import traceback
922
+ efmt = traceback.format_exc()
923
+ header = f'error during assertion:\n\n{efmt}\n\n{header}'
924
+
925
+ msg = build_err_msg([x, y], err_msg, verbose=verbose, header=header,
926
+ names=names, precision=precision)
927
+ raise ValueError(msg)
928
+
929
+
930
+ def assert_array_equal(actual, desired, err_msg='', verbose=True, *,
931
+ strict=False):
932
+ """
933
+ Raises an AssertionError if two array_like objects are not equal.
934
+
935
+ Given two array_like objects, check that the shape is equal and all
936
+ elements of these objects are equal (but see the Notes for the special
937
+ handling of a scalar). An exception is raised at shape mismatch or
938
+ conflicting values. In contrast to the standard usage in numpy, NaNs
939
+ are compared like numbers, no assertion is raised if both objects have
940
+ NaNs in the same positions.
941
+
942
+ The usual caution for verifying equality with floating point numbers is
943
+ advised.
944
+
945
+ .. note:: When either `actual` or `desired` is already an instance of
946
+ `numpy.ndarray` and `desired` is not a ``dict``, the behavior of
947
+ ``assert_equal(actual, desired)`` is identical to the behavior of this
948
+ function. Otherwise, this function performs `np.asanyarray` on the
949
+ inputs before comparison, whereas `assert_equal` defines special
950
+ comparison rules for common Python types. For example, only
951
+ `assert_equal` can be used to compare nested Python lists. In new code,
952
+ consider using only `assert_equal`, explicitly converting either
953
+ `actual` or `desired` to arrays if the behavior of `assert_array_equal`
954
+ is desired.
955
+
956
+ Parameters
957
+ ----------
958
+ actual : array_like
959
+ The actual object to check.
960
+ desired : array_like
961
+ The desired, expected object.
962
+ err_msg : str, optional
963
+ The error message to be printed in case of failure.
964
+ verbose : bool, optional
965
+ If True, the conflicting values are appended to the error message.
966
+ strict : bool, optional
967
+ If True, raise an AssertionError when either the shape or the data
968
+ type of the array_like objects does not match. The special
969
+ handling for scalars mentioned in the Notes section is disabled.
970
+
971
+ .. versionadded:: 1.24.0
972
+
973
+ Raises
974
+ ------
975
+ AssertionError
976
+ If actual and desired objects are not equal.
977
+
978
+ See Also
979
+ --------
980
+ assert_allclose: Compare two array_like objects for equality with desired
981
+ relative and/or absolute precision.
982
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
983
+
984
+ Notes
985
+ -----
986
+ When one of `actual` and `desired` is a scalar and the other is array_like,
987
+ the function checks that each element of the array_like object is equal to
988
+ the scalar. This behaviour can be disabled with the `strict` parameter.
989
+
990
+ Examples
991
+ --------
992
+ The first assert does not raise an exception:
993
+
994
+ >>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
995
+ ... [np.exp(0),2.33333, np.nan])
996
+
997
+ Assert fails with numerical imprecision with floats:
998
+
999
+ >>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
1000
+ ... [1, np.sqrt(np.pi)**2, np.nan])
1001
+ Traceback (most recent call last):
1002
+ ...
1003
+ AssertionError:
1004
+ Arrays are not equal
1005
+ <BLANKLINE>
1006
+ Mismatched elements: 1 / 3 (33.3%)
1007
+ Max absolute difference among violations: 4.4408921e-16
1008
+ Max relative difference among violations: 1.41357986e-16
1009
+ ACTUAL: array([1. , 3.141593, nan])
1010
+ DESIRED: array([1. , 3.141593, nan])
1011
+
1012
+ Use `assert_allclose` or one of the nulp (number of floating point values)
1013
+ functions for these cases instead:
1014
+
1015
+ >>> np.testing.assert_allclose([1.0,np.pi,np.nan],
1016
+ ... [1, np.sqrt(np.pi)**2, np.nan],
1017
+ ... rtol=1e-10, atol=0)
1018
+
1019
+ As mentioned in the Notes section, `assert_array_equal` has special
1020
+ handling for scalars. Here the test checks that each value in `x` is 3:
1021
+
1022
+ >>> x = np.full((2, 5), fill_value=3)
1023
+ >>> np.testing.assert_array_equal(x, 3)
1024
+
1025
+ Use `strict` to raise an AssertionError when comparing a scalar with an
1026
+ array:
1027
+
1028
+ >>> np.testing.assert_array_equal(x, 3, strict=True)
1029
+ Traceback (most recent call last):
1030
+ ...
1031
+ AssertionError:
1032
+ Arrays are not equal
1033
+ <BLANKLINE>
1034
+ (shapes (2, 5), () mismatch)
1035
+ ACTUAL: array([[3, 3, 3, 3, 3],
1036
+ [3, 3, 3, 3, 3]])
1037
+ DESIRED: array(3)
1038
+
1039
+ The `strict` parameter also ensures that the array data types match:
1040
+
1041
+ >>> x = np.array([2, 2, 2])
1042
+ >>> y = np.array([2., 2., 2.], dtype=np.float32)
1043
+ >>> np.testing.assert_array_equal(x, y, strict=True)
1044
+ Traceback (most recent call last):
1045
+ ...
1046
+ AssertionError:
1047
+ Arrays are not equal
1048
+ <BLANKLINE>
1049
+ (dtypes int64, float32 mismatch)
1050
+ ACTUAL: array([2, 2, 2])
1051
+ DESIRED: array([2., 2., 2.], dtype=float32)
1052
+ """
1053
+ __tracebackhide__ = True # Hide traceback for py.test
1054
+ assert_array_compare(operator.__eq__, actual, desired, err_msg=err_msg,
1055
+ verbose=verbose, header='Arrays are not equal',
1056
+ strict=strict)
1057
+
1058
+
1059
+ def assert_array_almost_equal(actual, desired, decimal=6, err_msg='',
1060
+ verbose=True):
1061
+ """
1062
+ Raises an AssertionError if two objects are not equal up to desired
1063
+ precision.
1064
+
1065
+ .. note:: It is recommended to use one of `assert_allclose`,
1066
+ `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
1067
+ instead of this function for more consistent floating point
1068
+ comparisons.
1069
+
1070
+ The test verifies identical shapes and that the elements of ``actual`` and
1071
+ ``desired`` satisfy::
1072
+
1073
+ abs(desired-actual) < 1.5 * 10**(-decimal)
1074
+
1075
+ That is a looser test than originally documented, but agrees with what the
1076
+ actual implementation did up to rounding vagaries. An exception is raised
1077
+ at shape mismatch or conflicting values. In contrast to the standard usage
1078
+ in numpy, NaNs are compared like numbers, no assertion is raised if both
1079
+ objects have NaNs in the same positions.
1080
+
1081
+ Parameters
1082
+ ----------
1083
+ actual : array_like
1084
+ The actual object to check.
1085
+ desired : array_like
1086
+ The desired, expected object.
1087
+ decimal : int, optional
1088
+ Desired precision, default is 6.
1089
+ err_msg : str, optional
1090
+ The error message to be printed in case of failure.
1091
+ verbose : bool, optional
1092
+ If True, the conflicting values are appended to the error message.
1093
+
1094
+ Raises
1095
+ ------
1096
+ AssertionError
1097
+ If actual and desired are not equal up to specified precision.
1098
+
1099
+ See Also
1100
+ --------
1101
+ assert_allclose: Compare two array_like objects for equality with desired
1102
+ relative and/or absolute precision.
1103
+ assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
1104
+
1105
+ Examples
1106
+ --------
1107
+ the first assert does not raise an exception
1108
+
1109
+ >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
1110
+ ... [1.0,2.333,np.nan])
1111
+
1112
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
1113
+ ... [1.0,2.33339,np.nan], decimal=5)
1114
+ Traceback (most recent call last):
1115
+ ...
1116
+ AssertionError:
1117
+ Arrays are not almost equal to 5 decimals
1118
+ <BLANKLINE>
1119
+ Mismatched elements: 1 / 3 (33.3%)
1120
+ Max absolute difference among violations: 6.e-05
1121
+ Max relative difference among violations: 2.57136612e-05
1122
+ ACTUAL: array([1. , 2.33333, nan])
1123
+ DESIRED: array([1. , 2.33339, nan])
1124
+
1125
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
1126
+ ... [1.0,2.33333, 5], decimal=5)
1127
+ Traceback (most recent call last):
1128
+ ...
1129
+ AssertionError:
1130
+ Arrays are not almost equal to 5 decimals
1131
+ <BLANKLINE>
1132
+ nan location mismatch:
1133
+ ACTUAL: array([1. , 2.33333, nan])
1134
+ DESIRED: array([1. , 2.33333, 5. ])
1135
+
1136
+ """
1137
+ __tracebackhide__ = True # Hide traceback for py.test
1138
+ from numpy._core import number, result_type
1139
+ from numpy._core.fromnumeric import any as npany
1140
+ from numpy._core.numerictypes import issubdtype
1141
+
1142
+ def compare(x, y):
1143
+ try:
1144
+ if npany(isinf(x)) or npany(isinf(y)):
1145
+ xinfid = isinf(x)
1146
+ yinfid = isinf(y)
1147
+ if not (xinfid == yinfid).all():
1148
+ return False
1149
+ # if one item, x and y is +- inf
1150
+ if x.size == y.size == 1:
1151
+ return x == y
1152
+ x = x[~xinfid]
1153
+ y = y[~yinfid]
1154
+ except (TypeError, NotImplementedError):
1155
+ pass
1156
+
1157
+ # make sure y is an inexact type to avoid abs(MIN_INT); will cause
1158
+ # casting of x later.
1159
+ dtype = result_type(y, 1.)
1160
+ y = np.asanyarray(y, dtype)
1161
+ z = abs(x - y)
1162
+
1163
+ if not issubdtype(z.dtype, number):
1164
+ z = z.astype(np.float64) # handle object arrays
1165
+
1166
+ return z < 1.5 * 10.0**(-decimal)
1167
+
1168
+ assert_array_compare(compare, actual, desired, err_msg=err_msg,
1169
+ verbose=verbose,
1170
+ header=('Arrays are not almost equal to %d decimals' % decimal),
1171
+ precision=decimal)
1172
+
1173
+
1174
+ def assert_array_less(x, y, err_msg='', verbose=True, *, strict=False):
1175
+ """
1176
+ Raises an AssertionError if two array_like objects are not ordered by less
1177
+ than.
1178
+
1179
+ Given two array_like objects `x` and `y`, check that the shape is equal and
1180
+ all elements of `x` are strictly less than the corresponding elements of
1181
+ `y` (but see the Notes for the special handling of a scalar). An exception
1182
+ is raised at shape mismatch or values that are not correctly ordered. In
1183
+ contrast to the standard usage in NumPy, no assertion is raised if both
1184
+ objects have NaNs in the same positions.
1185
+
1186
+ Parameters
1187
+ ----------
1188
+ x : array_like
1189
+ The smaller object to check.
1190
+ y : array_like
1191
+ The larger object to compare.
1192
+ err_msg : string
1193
+ The error message to be printed in case of failure.
1194
+ verbose : bool
1195
+ If True, the conflicting values are appended to the error message.
1196
+ strict : bool, optional
1197
+ If True, raise an AssertionError when either the shape or the data
1198
+ type of the array_like objects does not match. The special
1199
+ handling for scalars mentioned in the Notes section is disabled.
1200
+
1201
+ .. versionadded:: 2.0.0
1202
+
1203
+ Raises
1204
+ ------
1205
+ AssertionError
1206
+ If x is not strictly smaller than y, element-wise.
1207
+
1208
+ See Also
1209
+ --------
1210
+ assert_array_equal: tests objects for equality
1211
+ assert_array_almost_equal: test objects for equality up to precision
1212
+
1213
+ Notes
1214
+ -----
1215
+ When one of `x` and `y` is a scalar and the other is array_like, the
1216
+ function performs the comparison as though the scalar were broadcasted
1217
+ to the shape of the array. This behaviour can be disabled with the `strict`
1218
+ parameter.
1219
+
1220
+ Examples
1221
+ --------
1222
+ The following assertion passes because each finite element of `x` is
1223
+ strictly less than the corresponding element of `y`, and the NaNs are in
1224
+ corresponding locations.
1225
+
1226
+ >>> x = [1.0, 1.0, np.nan]
1227
+ >>> y = [1.1, 2.0, np.nan]
1228
+ >>> np.testing.assert_array_less(x, y)
1229
+
1230
+ The following assertion fails because the zeroth element of `x` is no
1231
+ longer strictly less than the zeroth element of `y`.
1232
+
1233
+ >>> y[0] = 1
1234
+ >>> np.testing.assert_array_less(x, y)
1235
+ Traceback (most recent call last):
1236
+ ...
1237
+ AssertionError:
1238
+ Arrays are not strictly ordered `x < y`
1239
+ <BLANKLINE>
1240
+ Mismatched elements: 1 / 3 (33.3%)
1241
+ Max absolute difference among violations: 0.
1242
+ Max relative difference among violations: 0.
1243
+ x: array([ 1., 1., nan])
1244
+ y: array([ 1., 2., nan])
1245
+
1246
+ Here, `y` is a scalar, so each element of `x` is compared to `y`, and
1247
+ the assertion passes.
1248
+
1249
+ >>> x = [1.0, 4.0]
1250
+ >>> y = 5.0
1251
+ >>> np.testing.assert_array_less(x, y)
1252
+
1253
+ However, with ``strict=True``, the assertion will fail because the shapes
1254
+ do not match.
1255
+
1256
+ >>> np.testing.assert_array_less(x, y, strict=True)
1257
+ Traceback (most recent call last):
1258
+ ...
1259
+ AssertionError:
1260
+ Arrays are not strictly ordered `x < y`
1261
+ <BLANKLINE>
1262
+ (shapes (2,), () mismatch)
1263
+ x: array([1., 4.])
1264
+ y: array(5.)
1265
+
1266
+ With ``strict=True``, the assertion also fails if the dtypes of the two
1267
+ arrays do not match.
1268
+
1269
+ >>> y = [5, 5]
1270
+ >>> np.testing.assert_array_less(x, y, strict=True)
1271
+ Traceback (most recent call last):
1272
+ ...
1273
+ AssertionError:
1274
+ Arrays are not strictly ordered `x < y`
1275
+ <BLANKLINE>
1276
+ (dtypes float64, int64 mismatch)
1277
+ x: array([1., 4.])
1278
+ y: array([5, 5])
1279
+ """
1280
+ __tracebackhide__ = True # Hide traceback for py.test
1281
+ assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
1282
+ verbose=verbose,
1283
+ header='Arrays are not strictly ordered `x < y`',
1284
+ equal_inf=False,
1285
+ strict=strict,
1286
+ names=('x', 'y'))
1287
+
1288
+
1289
+ def runstring(astr, dict):
1290
+ exec(astr, dict)
1291
+
1292
+
1293
+ def assert_string_equal(actual, desired):
1294
+ """
1295
+ Test if two strings are equal.
1296
+
1297
+ If the given strings are equal, `assert_string_equal` does nothing.
1298
+ If they are not equal, an AssertionError is raised, and the diff
1299
+ between the strings is shown.
1300
+
1301
+ Parameters
1302
+ ----------
1303
+ actual : str
1304
+ The string to test for equality against the expected string.
1305
+ desired : str
1306
+ The expected string.
1307
+
1308
+ Examples
1309
+ --------
1310
+ >>> np.testing.assert_string_equal('abc', 'abc')
1311
+ >>> np.testing.assert_string_equal('abc', 'abcd')
1312
+ Traceback (most recent call last):
1313
+ File "<stdin>", line 1, in <module>
1314
+ ...
1315
+ AssertionError: Differences in strings:
1316
+ - abc+ abcd? +
1317
+
1318
+ """
1319
+ # delay import of difflib to reduce startup time
1320
+ __tracebackhide__ = True # Hide traceback for py.test
1321
+ import difflib
1322
+
1323
+ if not isinstance(actual, str):
1324
+ raise AssertionError(repr(type(actual)))
1325
+ if not isinstance(desired, str):
1326
+ raise AssertionError(repr(type(desired)))
1327
+ if desired == actual:
1328
+ return
1329
+
1330
+ diff = list(difflib.Differ().compare(actual.splitlines(True),
1331
+ desired.splitlines(True)))
1332
+ diff_list = []
1333
+ while diff:
1334
+ d1 = diff.pop(0)
1335
+ if d1.startswith(' '):
1336
+ continue
1337
+ if d1.startswith('- '):
1338
+ l = [d1]
1339
+ d2 = diff.pop(0)
1340
+ if d2.startswith('? '):
1341
+ l.append(d2)
1342
+ d2 = diff.pop(0)
1343
+ if not d2.startswith('+ '):
1344
+ raise AssertionError(repr(d2))
1345
+ l.append(d2)
1346
+ if diff:
1347
+ d3 = diff.pop(0)
1348
+ if d3.startswith('? '):
1349
+ l.append(d3)
1350
+ else:
1351
+ diff.insert(0, d3)
1352
+ if d2[2:] == d1[2:]:
1353
+ continue
1354
+ diff_list.extend(l)
1355
+ continue
1356
+ raise AssertionError(repr(d1))
1357
+ if not diff_list:
1358
+ return
1359
+ msg = f"Differences in strings:\n{''.join(diff_list).rstrip()}"
1360
+ if actual != desired:
1361
+ raise AssertionError(msg)
1362
+
1363
+
1364
+ def rundocs(filename=None, raise_on_error=True):
1365
+ """
1366
+ Run doctests found in the given file.
1367
+
1368
+ By default `rundocs` raises an AssertionError on failure.
1369
+
1370
+ Parameters
1371
+ ----------
1372
+ filename : str
1373
+ The path to the file for which the doctests are run.
1374
+ raise_on_error : bool
1375
+ Whether to raise an AssertionError when a doctest fails. Default is
1376
+ True.
1377
+
1378
+ Notes
1379
+ -----
1380
+ The doctests can be run by the user/developer by adding the ``doctests``
1381
+ argument to the ``test()`` call. For example, to run all tests (including
1382
+ doctests) for ``numpy.lib``:
1383
+
1384
+ >>> np.lib.test(doctests=True) # doctest: +SKIP
1385
+ """
1386
+ import doctest
1387
+
1388
+ from numpy.distutils.misc_util import exec_mod_from_location
1389
+ if filename is None:
1390
+ f = sys._getframe(1)
1391
+ filename = f.f_globals['__file__']
1392
+ name = os.path.splitext(os.path.basename(filename))[0]
1393
+ m = exec_mod_from_location(name, filename)
1394
+
1395
+ tests = doctest.DocTestFinder().find(m)
1396
+ runner = doctest.DocTestRunner(verbose=False)
1397
+
1398
+ msg = []
1399
+ if raise_on_error:
1400
+ out = msg.append
1401
+ else:
1402
+ out = None
1403
+
1404
+ for test in tests:
1405
+ runner.run(test, out=out)
1406
+
1407
+ if runner.failures > 0 and raise_on_error:
1408
+ raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
1409
+
1410
+
1411
+ def check_support_sve(__cache=[]):
1412
+ """
1413
+ gh-22982
1414
+ """
1415
+
1416
+ if __cache:
1417
+ return __cache[0]
1418
+
1419
+ import subprocess
1420
+ cmd = 'lscpu'
1421
+ try:
1422
+ output = subprocess.run(cmd, capture_output=True, text=True)
1423
+ result = 'sve' in output.stdout
1424
+ except (OSError, subprocess.SubprocessError):
1425
+ result = False
1426
+ __cache.append(result)
1427
+ return __cache[0]
1428
+
1429
+
1430
+ #
1431
+ # assert_raises and assert_raises_regex are taken from unittest.
1432
+ #
1433
+ import unittest
1434
+
1435
+
1436
+ class _Dummy(unittest.TestCase):
1437
+ def nop(self):
1438
+ pass
1439
+
1440
+
1441
+ _d = _Dummy('nop')
1442
+
1443
+
1444
+ def assert_raises(*args, **kwargs):
1445
+ """
1446
+ assert_raises(exception_class, callable, *args, **kwargs)
1447
+ assert_raises(exception_class)
1448
+
1449
+ Fail unless an exception of class exception_class is thrown
1450
+ by callable when invoked with arguments args and keyword
1451
+ arguments kwargs. If a different type of exception is
1452
+ thrown, it will not be caught, and the test case will be
1453
+ deemed to have suffered an error, exactly as for an
1454
+ unexpected exception.
1455
+
1456
+ Alternatively, `assert_raises` can be used as a context manager:
1457
+
1458
+ >>> from numpy.testing import assert_raises
1459
+ >>> with assert_raises(ZeroDivisionError):
1460
+ ... 1 / 0
1461
+
1462
+ is equivalent to
1463
+
1464
+ >>> def div(x, y):
1465
+ ... return x / y
1466
+ >>> assert_raises(ZeroDivisionError, div, 1, 0)
1467
+
1468
+ """
1469
+ __tracebackhide__ = True # Hide traceback for py.test
1470
+ return _d.assertRaises(*args, **kwargs)
1471
+
1472
+
1473
+ def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
1474
+ """
1475
+ assert_raises_regex(exception_class, expected_regexp, callable, *args,
1476
+ **kwargs)
1477
+ assert_raises_regex(exception_class, expected_regexp)
1478
+
1479
+ Fail unless an exception of class exception_class and with message that
1480
+ matches expected_regexp is thrown by callable when invoked with arguments
1481
+ args and keyword arguments kwargs.
1482
+
1483
+ Alternatively, can be used as a context manager like `assert_raises`.
1484
+ """
1485
+ __tracebackhide__ = True # Hide traceback for py.test
1486
+ return _d.assertRaisesRegex(exception_class, expected_regexp, *args, **kwargs)
1487
+
1488
+
1489
+ def decorate_methods(cls, decorator, testmatch=None):
1490
+ """
1491
+ Apply a decorator to all methods in a class matching a regular expression.
1492
+
1493
+ The given decorator is applied to all public methods of `cls` that are
1494
+ matched by the regular expression `testmatch`
1495
+ (``testmatch.search(methodname)``). Methods that are private, i.e. start
1496
+ with an underscore, are ignored.
1497
+
1498
+ Parameters
1499
+ ----------
1500
+ cls : class
1501
+ Class whose methods to decorate.
1502
+ decorator : function
1503
+ Decorator to apply to methods
1504
+ testmatch : compiled regexp or str, optional
1505
+ The regular expression. Default value is None, in which case the
1506
+ nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
1507
+ is used.
1508
+ If `testmatch` is a string, it is compiled to a regular expression
1509
+ first.
1510
+
1511
+ """
1512
+ if testmatch is None:
1513
+ testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
1514
+ else:
1515
+ testmatch = re.compile(testmatch)
1516
+ cls_attr = cls.__dict__
1517
+
1518
+ # delayed import to reduce startup time
1519
+ from inspect import isfunction
1520
+
1521
+ methods = [_m for _m in cls_attr.values() if isfunction(_m)]
1522
+ for function in methods:
1523
+ try:
1524
+ if hasattr(function, 'compat_func_name'):
1525
+ funcname = function.compat_func_name
1526
+ else:
1527
+ funcname = function.__name__
1528
+ except AttributeError:
1529
+ # not a function
1530
+ continue
1531
+ if testmatch.search(funcname) and not funcname.startswith('_'):
1532
+ setattr(cls, funcname, decorator(function))
1533
+
1534
+
1535
+ def measure(code_str, times=1, label=None):
1536
+ """
1537
+ Return elapsed time for executing code in the namespace of the caller.
1538
+
1539
+ The supplied code string is compiled with the Python builtin ``compile``.
1540
+ The precision of the timing is 10 milli-seconds. If the code will execute
1541
+ fast on this timescale, it can be executed many times to get reasonable
1542
+ timing accuracy.
1543
+
1544
+ Parameters
1545
+ ----------
1546
+ code_str : str
1547
+ The code to be timed.
1548
+ times : int, optional
1549
+ The number of times the code is executed. Default is 1. The code is
1550
+ only compiled once.
1551
+ label : str, optional
1552
+ A label to identify `code_str` with. This is passed into ``compile``
1553
+ as the second argument (for run-time error messages).
1554
+
1555
+ Returns
1556
+ -------
1557
+ elapsed : float
1558
+ Total elapsed time in seconds for executing `code_str` `times` times.
1559
+
1560
+ Examples
1561
+ --------
1562
+ >>> times = 10
1563
+ >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
1564
+ >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP
1565
+ Time for a single execution : 0.005 s
1566
+
1567
+ """
1568
+ frame = sys._getframe(1)
1569
+ locs, globs = frame.f_locals, frame.f_globals
1570
+
1571
+ code = compile(code_str, f'Test name: {label} ', 'exec')
1572
+ i = 0
1573
+ elapsed = jiffies()
1574
+ while i < times:
1575
+ i += 1
1576
+ exec(code, globs, locs)
1577
+ elapsed = jiffies() - elapsed
1578
+ return 0.01 * elapsed
1579
+
1580
+
1581
+ def _assert_valid_refcount(op):
1582
+ """
1583
+ Check that ufuncs don't mishandle refcount of object `1`.
1584
+ Used in a few regression tests.
1585
+ """
1586
+ if not HAS_REFCOUNT:
1587
+ return True
1588
+
1589
+ import gc
1590
+
1591
+ import numpy as np
1592
+
1593
+ b = np.arange(100 * 100).reshape(100, 100)
1594
+ c = b
1595
+ i = 1
1596
+
1597
+ gc.disable()
1598
+ try:
1599
+ rc = sys.getrefcount(i)
1600
+ for j in range(15):
1601
+ d = op(b, c)
1602
+ assert_(sys.getrefcount(i) >= rc)
1603
+ finally:
1604
+ gc.enable()
1605
+
1606
+
1607
+ def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
1608
+ err_msg='', verbose=True, *, strict=False):
1609
+ """
1610
+ Raises an AssertionError if two objects are not equal up to desired
1611
+ tolerance.
1612
+
1613
+ Given two array_like objects, check that their shapes and all elements
1614
+ are equal (but see the Notes for the special handling of a scalar). An
1615
+ exception is raised if the shapes mismatch or any values conflict. In
1616
+ contrast to the standard usage in numpy, NaNs are compared like numbers,
1617
+ no assertion is raised if both objects have NaNs in the same positions.
1618
+
1619
+ The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
1620
+ that ``allclose`` has different default values). It compares the difference
1621
+ between `actual` and `desired` to ``atol + rtol * abs(desired)``.
1622
+
1623
+ Parameters
1624
+ ----------
1625
+ actual : array_like
1626
+ Array obtained.
1627
+ desired : array_like
1628
+ Array desired.
1629
+ rtol : float, optional
1630
+ Relative tolerance.
1631
+ atol : float, optional
1632
+ Absolute tolerance.
1633
+ equal_nan : bool, optional.
1634
+ If True, NaNs will compare equal.
1635
+ err_msg : str, optional
1636
+ The error message to be printed in case of failure.
1637
+ verbose : bool, optional
1638
+ If True, the conflicting values are appended to the error message.
1639
+ strict : bool, optional
1640
+ If True, raise an ``AssertionError`` when either the shape or the data
1641
+ type of the arguments does not match. The special handling of scalars
1642
+ mentioned in the Notes section is disabled.
1643
+
1644
+ .. versionadded:: 2.0.0
1645
+
1646
+ Raises
1647
+ ------
1648
+ AssertionError
1649
+ If actual and desired are not equal up to specified precision.
1650
+
1651
+ See Also
1652
+ --------
1653
+ assert_array_almost_equal_nulp, assert_array_max_ulp
1654
+
1655
+ Notes
1656
+ -----
1657
+ When one of `actual` and `desired` is a scalar and the other is
1658
+ array_like, the function performs the comparison as if the scalar were
1659
+ broadcasted to the shape of the array.
1660
+ This behaviour can be disabled with the `strict` parameter.
1661
+
1662
+ Examples
1663
+ --------
1664
+ >>> x = [1e-5, 1e-3, 1e-1]
1665
+ >>> y = np.arccos(np.cos(x))
1666
+ >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
1667
+
1668
+ As mentioned in the Notes section, `assert_allclose` has special
1669
+ handling for scalars. Here, the test checks that the value of `numpy.sin`
1670
+ is nearly zero at integer multiples of π.
1671
+
1672
+ >>> x = np.arange(3) * np.pi
1673
+ >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
1674
+
1675
+ Use `strict` to raise an ``AssertionError`` when comparing an array
1676
+ with one or more dimensions against a scalar.
1677
+
1678
+ >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True)
1679
+ Traceback (most recent call last):
1680
+ ...
1681
+ AssertionError:
1682
+ Not equal to tolerance rtol=1e-07, atol=1e-15
1683
+ <BLANKLINE>
1684
+ (shapes (3,), () mismatch)
1685
+ ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
1686
+ DESIRED: array(0)
1687
+
1688
+ The `strict` parameter also ensures that the array data types match:
1689
+
1690
+ >>> y = np.zeros(3, dtype=np.float32)
1691
+ >>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True)
1692
+ Traceback (most recent call last):
1693
+ ...
1694
+ AssertionError:
1695
+ Not equal to tolerance rtol=1e-07, atol=1e-15
1696
+ <BLANKLINE>
1697
+ (dtypes float64, float32 mismatch)
1698
+ ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
1699
+ DESIRED: array([0., 0., 0.], dtype=float32)
1700
+
1701
+ """
1702
+ __tracebackhide__ = True # Hide traceback for py.test
1703
+ import numpy as np
1704
+
1705
+ def compare(x, y):
1706
+ return np._core.numeric.isclose(x, y, rtol=rtol, atol=atol,
1707
+ equal_nan=equal_nan)
1708
+
1709
+ actual, desired = np.asanyarray(actual), np.asanyarray(desired)
1710
+ header = f'Not equal to tolerance rtol={rtol:g}, atol={atol:g}'
1711
+ assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
1712
+ verbose=verbose, header=header, equal_nan=equal_nan,
1713
+ strict=strict)
1714
+
1715
+
1716
+ def assert_array_almost_equal_nulp(x, y, nulp=1):
1717
+ """
1718
+ Compare two arrays relatively to their spacing.
1719
+
1720
+ This is a relatively robust method to compare two arrays whose amplitude
1721
+ is variable.
1722
+
1723
+ Parameters
1724
+ ----------
1725
+ x, y : array_like
1726
+ Input arrays.
1727
+ nulp : int, optional
1728
+ The maximum number of unit in the last place for tolerance (see Notes).
1729
+ Default is 1.
1730
+
1731
+ Returns
1732
+ -------
1733
+ None
1734
+
1735
+ Raises
1736
+ ------
1737
+ AssertionError
1738
+ If the spacing between `x` and `y` for one or more elements is larger
1739
+ than `nulp`.
1740
+
1741
+ See Also
1742
+ --------
1743
+ assert_array_max_ulp : Check that all items of arrays differ in at most
1744
+ N Units in the Last Place.
1745
+ spacing : Return the distance between x and the nearest adjacent number.
1746
+
1747
+ Notes
1748
+ -----
1749
+ An assertion is raised if the following condition is not met::
1750
+
1751
+ abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
1752
+
1753
+ Examples
1754
+ --------
1755
+ >>> x = np.array([1., 1e-10, 1e-20])
1756
+ >>> eps = np.finfo(x.dtype).eps
1757
+ >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
1758
+
1759
+ >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
1760
+ Traceback (most recent call last):
1761
+ ...
1762
+ AssertionError: Arrays are not equal to 1 ULP (max is 2)
1763
+
1764
+ """
1765
+ __tracebackhide__ = True # Hide traceback for py.test
1766
+ import numpy as np
1767
+ ax = np.abs(x)
1768
+ ay = np.abs(y)
1769
+ ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
1770
+ if not np.all(np.abs(x - y) <= ref):
1771
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1772
+ msg = f"Arrays are not equal to {nulp} ULP"
1773
+ else:
1774
+ max_nulp = np.max(nulp_diff(x, y))
1775
+ msg = f"Arrays are not equal to {nulp} ULP (max is {max_nulp:g})"
1776
+ raise AssertionError(msg)
1777
+
1778
+
1779
+ def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
1780
+ """
1781
+ Check that all items of arrays differ in at most N Units in the Last Place.
1782
+
1783
+ Parameters
1784
+ ----------
1785
+ a, b : array_like
1786
+ Input arrays to be compared.
1787
+ maxulp : int, optional
1788
+ The maximum number of units in the last place that elements of `a` and
1789
+ `b` can differ. Default is 1.
1790
+ dtype : dtype, optional
1791
+ Data-type to convert `a` and `b` to if given. Default is None.
1792
+
1793
+ Returns
1794
+ -------
1795
+ ret : ndarray
1796
+ Array containing number of representable floating point numbers between
1797
+ items in `a` and `b`.
1798
+
1799
+ Raises
1800
+ ------
1801
+ AssertionError
1802
+ If one or more elements differ by more than `maxulp`.
1803
+
1804
+ Notes
1805
+ -----
1806
+ For computing the ULP difference, this API does not differentiate between
1807
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1808
+ is zero).
1809
+
1810
+ See Also
1811
+ --------
1812
+ assert_array_almost_equal_nulp : Compare two arrays relatively to their
1813
+ spacing.
1814
+
1815
+ Examples
1816
+ --------
1817
+ >>> a = np.linspace(0., 1., 100)
1818
+ >>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
1819
+
1820
+ """
1821
+ __tracebackhide__ = True # Hide traceback for py.test
1822
+ import numpy as np
1823
+ ret = nulp_diff(a, b, dtype)
1824
+ if not np.all(ret <= maxulp):
1825
+ raise AssertionError("Arrays are not almost equal up to %g "
1826
+ "ULP (max difference is %g ULP)" %
1827
+ (maxulp, np.max(ret)))
1828
+ return ret
1829
+
1830
+
1831
+ def nulp_diff(x, y, dtype=None):
1832
+ """For each item in x and y, return the number of representable floating
1833
+ points between them.
1834
+
1835
+ Parameters
1836
+ ----------
1837
+ x : array_like
1838
+ first input array
1839
+ y : array_like
1840
+ second input array
1841
+ dtype : dtype, optional
1842
+ Data-type to convert `x` and `y` to if given. Default is None.
1843
+
1844
+ Returns
1845
+ -------
1846
+ nulp : array_like
1847
+ number of representable floating point numbers between each item in x
1848
+ and y.
1849
+
1850
+ Notes
1851
+ -----
1852
+ For computing the ULP difference, this API does not differentiate between
1853
+ various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
1854
+ is zero).
1855
+
1856
+ Examples
1857
+ --------
1858
+ # By definition, epsilon is the smallest number such as 1 + eps != 1, so
1859
+ # there should be exactly one ULP between 1 and 1 + eps
1860
+ >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
1861
+ 1.0
1862
+ """
1863
+ import numpy as np
1864
+ if dtype:
1865
+ x = np.asarray(x, dtype=dtype)
1866
+ y = np.asarray(y, dtype=dtype)
1867
+ else:
1868
+ x = np.asarray(x)
1869
+ y = np.asarray(y)
1870
+
1871
+ t = np.common_type(x, y)
1872
+ if np.iscomplexobj(x) or np.iscomplexobj(y):
1873
+ raise NotImplementedError("_nulp not implemented for complex array")
1874
+
1875
+ x = np.array([x], dtype=t)
1876
+ y = np.array([y], dtype=t)
1877
+
1878
+ x[np.isnan(x)] = np.nan
1879
+ y[np.isnan(y)] = np.nan
1880
+
1881
+ if not x.shape == y.shape:
1882
+ raise ValueError(f"Arrays do not have the same shape: {x.shape} - {y.shape}")
1883
+
1884
+ def _diff(rx, ry, vdt):
1885
+ diff = np.asarray(rx - ry, dtype=vdt)
1886
+ return np.abs(diff)
1887
+
1888
+ rx = integer_repr(x)
1889
+ ry = integer_repr(y)
1890
+ return _diff(rx, ry, t)
1891
+
1892
+
1893
+ def _integer_repr(x, vdt, comp):
1894
+ # Reinterpret binary representation of the float as sign-magnitude:
1895
+ # take into account two-complement representation
1896
+ # See also
1897
+ # https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
1898
+ rx = x.view(vdt)
1899
+ if not (rx.size == 1):
1900
+ rx[rx < 0] = comp - rx[rx < 0]
1901
+ elif rx < 0:
1902
+ rx = comp - rx
1903
+
1904
+ return rx
1905
+
1906
+
1907
+ def integer_repr(x):
1908
+ """Return the signed-magnitude interpretation of the binary representation
1909
+ of x."""
1910
+ import numpy as np
1911
+ if x.dtype == np.float16:
1912
+ return _integer_repr(x, np.int16, np.int16(-2**15))
1913
+ elif x.dtype == np.float32:
1914
+ return _integer_repr(x, np.int32, np.int32(-2**31))
1915
+ elif x.dtype == np.float64:
1916
+ return _integer_repr(x, np.int64, np.int64(-2**63))
1917
+ else:
1918
+ raise ValueError(f'Unsupported dtype {x.dtype}')
1919
+
1920
+
1921
+ @contextlib.contextmanager
1922
+ def _assert_warns_context(warning_class, name=None):
1923
+ __tracebackhide__ = True # Hide traceback for py.test
1924
+ with suppress_warnings() as sup:
1925
+ l = sup.record(warning_class)
1926
+ yield
1927
+ if not len(l) > 0:
1928
+ name_str = f' when calling {name}' if name is not None else ''
1929
+ raise AssertionError("No warning raised" + name_str)
1930
+
1931
+
1932
+ def assert_warns(warning_class, *args, **kwargs):
1933
+ """
1934
+ Fail unless the given callable throws the specified warning.
1935
+
1936
+ A warning of class warning_class should be thrown by the callable when
1937
+ invoked with arguments args and keyword arguments kwargs.
1938
+ If a different type of warning is thrown, it will not be caught.
1939
+
1940
+ If called with all arguments other than the warning class omitted, may be
1941
+ used as a context manager::
1942
+
1943
+ with assert_warns(SomeWarning):
1944
+ do_something()
1945
+
1946
+ The ability to be used as a context manager is new in NumPy v1.11.0.
1947
+
1948
+ Parameters
1949
+ ----------
1950
+ warning_class : class
1951
+ The class defining the warning that `func` is expected to throw.
1952
+ func : callable, optional
1953
+ Callable to test
1954
+ *args : Arguments
1955
+ Arguments for `func`.
1956
+ **kwargs : Kwargs
1957
+ Keyword arguments for `func`.
1958
+
1959
+ Returns
1960
+ -------
1961
+ The value returned by `func`.
1962
+
1963
+ Examples
1964
+ --------
1965
+ >>> import warnings
1966
+ >>> def deprecated_func(num):
1967
+ ... warnings.warn("Please upgrade", DeprecationWarning)
1968
+ ... return num*num
1969
+ >>> with np.testing.assert_warns(DeprecationWarning):
1970
+ ... assert deprecated_func(4) == 16
1971
+ >>> # or passing a func
1972
+ >>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
1973
+ >>> assert ret == 16
1974
+ """
1975
+ if not args and not kwargs:
1976
+ return _assert_warns_context(warning_class)
1977
+ elif len(args) < 1:
1978
+ if "match" in kwargs:
1979
+ raise RuntimeError(
1980
+ "assert_warns does not use 'match' kwarg, "
1981
+ "use pytest.warns instead"
1982
+ )
1983
+ raise RuntimeError("assert_warns(...) needs at least one arg")
1984
+
1985
+ func = args[0]
1986
+ args = args[1:]
1987
+ with _assert_warns_context(warning_class, name=func.__name__):
1988
+ return func(*args, **kwargs)
1989
+
1990
+
1991
+ @contextlib.contextmanager
1992
+ def _assert_no_warnings_context(name=None):
1993
+ __tracebackhide__ = True # Hide traceback for py.test
1994
+ with warnings.catch_warnings(record=True) as l:
1995
+ warnings.simplefilter('always')
1996
+ yield
1997
+ if len(l) > 0:
1998
+ name_str = f' when calling {name}' if name is not None else ''
1999
+ raise AssertionError(f'Got warnings{name_str}: {l}')
2000
+
2001
+
2002
+ def assert_no_warnings(*args, **kwargs):
2003
+ """
2004
+ Fail if the given callable produces any warnings.
2005
+
2006
+ If called with all arguments omitted, may be used as a context manager::
2007
+
2008
+ with assert_no_warnings():
2009
+ do_something()
2010
+
2011
+ The ability to be used as a context manager is new in NumPy v1.11.0.
2012
+
2013
+ Parameters
2014
+ ----------
2015
+ func : callable
2016
+ The callable to test.
2017
+ \\*args : Arguments
2018
+ Arguments passed to `func`.
2019
+ \\*\\*kwargs : Kwargs
2020
+ Keyword arguments passed to `func`.
2021
+
2022
+ Returns
2023
+ -------
2024
+ The value returned by `func`.
2025
+
2026
+ """
2027
+ if not args:
2028
+ return _assert_no_warnings_context()
2029
+
2030
+ func = args[0]
2031
+ args = args[1:]
2032
+ with _assert_no_warnings_context(name=func.__name__):
2033
+ return func(*args, **kwargs)
2034
+
2035
+
2036
+ def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
2037
+ """
2038
+ generator producing data with different alignment and offsets
2039
+ to test simd vectorization
2040
+
2041
+ Parameters
2042
+ ----------
2043
+ dtype : dtype
2044
+ data type to produce
2045
+ type : string
2046
+ 'unary': create data for unary operations, creates one input
2047
+ and output array
2048
+ 'binary': create data for unary operations, creates two input
2049
+ and output array
2050
+ max_size : integer
2051
+ maximum size of data to produce
2052
+
2053
+ Returns
2054
+ -------
2055
+ if type is 'unary' yields one output, one input array and a message
2056
+ containing information on the data
2057
+ if type is 'binary' yields one output array, two input array and a message
2058
+ containing information on the data
2059
+
2060
+ """
2061
+ ufmt = 'unary offset=(%d, %d), size=%d, dtype=%r, %s'
2062
+ bfmt = 'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'
2063
+ for o in range(3):
2064
+ for s in range(o + 2, max(o + 3, max_size)):
2065
+ if type == 'unary':
2066
+ inp = lambda: arange(s, dtype=dtype)[o:]
2067
+ out = empty((s,), dtype=dtype)[o:]
2068
+ yield out, inp(), ufmt % (o, o, s, dtype, 'out of place')
2069
+ d = inp()
2070
+ yield d, d, ufmt % (o, o, s, dtype, 'in place')
2071
+ yield out[1:], inp()[:-1], ufmt % \
2072
+ (o + 1, o, s - 1, dtype, 'out of place')
2073
+ yield out[:-1], inp()[1:], ufmt % \
2074
+ (o, o + 1, s - 1, dtype, 'out of place')
2075
+ yield inp()[:-1], inp()[1:], ufmt % \
2076
+ (o, o + 1, s - 1, dtype, 'aliased')
2077
+ yield inp()[1:], inp()[:-1], ufmt % \
2078
+ (o + 1, o, s - 1, dtype, 'aliased')
2079
+ if type == 'binary':
2080
+ inp1 = lambda: arange(s, dtype=dtype)[o:]
2081
+ inp2 = lambda: arange(s, dtype=dtype)[o:]
2082
+ out = empty((s,), dtype=dtype)[o:]
2083
+ yield out, inp1(), inp2(), bfmt % \
2084
+ (o, o, o, s, dtype, 'out of place')
2085
+ d = inp1()
2086
+ yield d, d, inp2(), bfmt % \
2087
+ (o, o, o, s, dtype, 'in place1')
2088
+ d = inp2()
2089
+ yield d, inp1(), d, bfmt % \
2090
+ (o, o, o, s, dtype, 'in place2')
2091
+ yield out[1:], inp1()[:-1], inp2()[:-1], bfmt % \
2092
+ (o + 1, o, o, s - 1, dtype, 'out of place')
2093
+ yield out[:-1], inp1()[1:], inp2()[:-1], bfmt % \
2094
+ (o, o + 1, o, s - 1, dtype, 'out of place')
2095
+ yield out[:-1], inp1()[:-1], inp2()[1:], bfmt % \
2096
+ (o, o, o + 1, s - 1, dtype, 'out of place')
2097
+ yield inp1()[1:], inp1()[:-1], inp2()[:-1], bfmt % \
2098
+ (o + 1, o, o, s - 1, dtype, 'aliased')
2099
+ yield inp1()[:-1], inp1()[1:], inp2()[:-1], bfmt % \
2100
+ (o, o + 1, o, s - 1, dtype, 'aliased')
2101
+ yield inp1()[:-1], inp1()[:-1], inp2()[1:], bfmt % \
2102
+ (o, o, o + 1, s - 1, dtype, 'aliased')
2103
+
2104
+
2105
+ class IgnoreException(Exception):
2106
+ "Ignoring this exception due to disabled feature"
2107
+ pass
2108
+
2109
+
2110
+ @contextlib.contextmanager
2111
+ def tempdir(*args, **kwargs):
2112
+ """Context manager to provide a temporary test folder.
2113
+
2114
+ All arguments are passed as this to the underlying tempfile.mkdtemp
2115
+ function.
2116
+
2117
+ """
2118
+ tmpdir = mkdtemp(*args, **kwargs)
2119
+ try:
2120
+ yield tmpdir
2121
+ finally:
2122
+ shutil.rmtree(tmpdir)
2123
+
2124
+
2125
+ @contextlib.contextmanager
2126
+ def temppath(*args, **kwargs):
2127
+ """Context manager for temporary files.
2128
+
2129
+ Context manager that returns the path to a closed temporary file. Its
2130
+ parameters are the same as for tempfile.mkstemp and are passed directly
2131
+ to that function. The underlying file is removed when the context is
2132
+ exited, so it should be closed at that time.
2133
+
2134
+ Windows does not allow a temporary file to be opened if it is already
2135
+ open, so the underlying file must be closed after opening before it
2136
+ can be opened again.
2137
+
2138
+ """
2139
+ fd, path = mkstemp(*args, **kwargs)
2140
+ os.close(fd)
2141
+ try:
2142
+ yield path
2143
+ finally:
2144
+ os.remove(path)
2145
+
2146
+
2147
+ class clear_and_catch_warnings(warnings.catch_warnings):
2148
+ """ Context manager that resets warning registry for catching warnings
2149
+
2150
+ Warnings can be slippery, because, whenever a warning is triggered, Python
2151
+ adds a ``__warningregistry__`` member to the *calling* module. This makes
2152
+ it impossible to retrigger the warning in this module, whatever you put in
2153
+ the warnings filters. This context manager accepts a sequence of `modules`
2154
+ as a keyword argument to its constructor and:
2155
+
2156
+ * stores and removes any ``__warningregistry__`` entries in given `modules`
2157
+ on entry;
2158
+ * resets ``__warningregistry__`` to its previous state on exit.
2159
+
2160
+ This makes it possible to trigger any warning afresh inside the context
2161
+ manager without disturbing the state of warnings outside.
2162
+
2163
+ For compatibility with Python, please consider all arguments to be
2164
+ keyword-only.
2165
+
2166
+ Parameters
2167
+ ----------
2168
+ record : bool, optional
2169
+ Specifies whether warnings should be captured by a custom
2170
+ implementation of ``warnings.showwarning()`` and be appended to a list
2171
+ returned by the context manager. Otherwise None is returned by the
2172
+ context manager. The objects appended to the list are arguments whose
2173
+ attributes mirror the arguments to ``showwarning()``.
2174
+ modules : sequence, optional
2175
+ Sequence of modules for which to reset warnings registry on entry and
2176
+ restore on exit. To work correctly, all 'ignore' filters should
2177
+ filter by one of these modules.
2178
+
2179
+ Examples
2180
+ --------
2181
+ >>> import warnings
2182
+ >>> with np.testing.clear_and_catch_warnings(
2183
+ ... modules=[np._core.fromnumeric]):
2184
+ ... warnings.simplefilter('always')
2185
+ ... warnings.filterwarnings('ignore', module='np._core.fromnumeric')
2186
+ ... # do something that raises a warning but ignore those in
2187
+ ... # np._core.fromnumeric
2188
+ """
2189
+ class_modules = ()
2190
+
2191
+ def __init__(self, record=False, modules=()):
2192
+ self.modules = set(modules).union(self.class_modules)
2193
+ self._warnreg_copies = {}
2194
+ super().__init__(record=record)
2195
+
2196
+ def __enter__(self):
2197
+ for mod in self.modules:
2198
+ if hasattr(mod, '__warningregistry__'):
2199
+ mod_reg = mod.__warningregistry__
2200
+ self._warnreg_copies[mod] = mod_reg.copy()
2201
+ mod_reg.clear()
2202
+ return super().__enter__()
2203
+
2204
+ def __exit__(self, *exc_info):
2205
+ super().__exit__(*exc_info)
2206
+ for mod in self.modules:
2207
+ if hasattr(mod, '__warningregistry__'):
2208
+ mod.__warningregistry__.clear()
2209
+ if mod in self._warnreg_copies:
2210
+ mod.__warningregistry__.update(self._warnreg_copies[mod])
2211
+
2212
+
2213
+ class suppress_warnings:
2214
+ """
2215
+ Context manager and decorator doing much the same as
2216
+ ``warnings.catch_warnings``.
2217
+
2218
+ However, it also provides a filter mechanism to work around
2219
+ https://bugs.python.org/issue4180.
2220
+
2221
+ This bug causes Python before 3.4 to not reliably show warnings again
2222
+ after they have been ignored once (even within catch_warnings). It
2223
+ means that no "ignore" filter can be used easily, since following
2224
+ tests might need to see the warning. Additionally it allows easier
2225
+ specificity for testing warnings and can be nested.
2226
+
2227
+ Parameters
2228
+ ----------
2229
+ forwarding_rule : str, optional
2230
+ One of "always", "once", "module", or "location". Analogous to
2231
+ the usual warnings module filter mode, it is useful to reduce
2232
+ noise mostly on the outmost level. Unsuppressed and unrecorded
2233
+ warnings will be forwarded based on this rule. Defaults to "always".
2234
+ "location" is equivalent to the warnings "default", match by exact
2235
+ location the warning warning originated from.
2236
+
2237
+ Notes
2238
+ -----
2239
+ Filters added inside the context manager will be discarded again
2240
+ when leaving it. Upon entering all filters defined outside a
2241
+ context will be applied automatically.
2242
+
2243
+ When a recording filter is added, matching warnings are stored in the
2244
+ ``log`` attribute as well as in the list returned by ``record``.
2245
+
2246
+ If filters are added and the ``module`` keyword is given, the
2247
+ warning registry of this module will additionally be cleared when
2248
+ applying it, entering the context, or exiting it. This could cause
2249
+ warnings to appear a second time after leaving the context if they
2250
+ were configured to be printed once (default) and were already
2251
+ printed before the context was entered.
2252
+
2253
+ Nesting this context manager will work as expected when the
2254
+ forwarding rule is "always" (default). Unfiltered and unrecorded
2255
+ warnings will be passed out and be matched by the outer level.
2256
+ On the outmost level they will be printed (or caught by another
2257
+ warnings context). The forwarding rule argument can modify this
2258
+ behaviour.
2259
+
2260
+ Like ``catch_warnings`` this context manager is not threadsafe.
2261
+
2262
+ Examples
2263
+ --------
2264
+
2265
+ With a context manager::
2266
+
2267
+ with np.testing.suppress_warnings() as sup:
2268
+ sup.filter(DeprecationWarning, "Some text")
2269
+ sup.filter(module=np.ma.core)
2270
+ log = sup.record(FutureWarning, "Does this occur?")
2271
+ command_giving_warnings()
2272
+ # The FutureWarning was given once, the filtered warnings were
2273
+ # ignored. All other warnings abide outside settings (may be
2274
+ # printed/error)
2275
+ assert_(len(log) == 1)
2276
+ assert_(len(sup.log) == 1) # also stored in log attribute
2277
+
2278
+ Or as a decorator::
2279
+
2280
+ sup = np.testing.suppress_warnings()
2281
+ sup.filter(module=np.ma.core) # module must match exactly
2282
+ @sup
2283
+ def some_function():
2284
+ # do something which causes a warning in np.ma.core
2285
+ pass
2286
+ """
2287
+ def __init__(self, forwarding_rule="always"):
2288
+ self._entered = False
2289
+
2290
+ # Suppressions are either instance or defined inside one with block:
2291
+ self._suppressions = []
2292
+
2293
+ if forwarding_rule not in {"always", "module", "once", "location"}:
2294
+ raise ValueError("unsupported forwarding rule.")
2295
+ self._forwarding_rule = forwarding_rule
2296
+
2297
+ def _clear_registries(self):
2298
+ if hasattr(warnings, "_filters_mutated"):
2299
+ # clearing the registry should not be necessary on new pythons,
2300
+ # instead the filters should be mutated.
2301
+ warnings._filters_mutated()
2302
+ return
2303
+ # Simply clear the registry, this should normally be harmless,
2304
+ # note that on new pythons it would be invalidated anyway.
2305
+ for module in self._tmp_modules:
2306
+ if hasattr(module, "__warningregistry__"):
2307
+ module.__warningregistry__.clear()
2308
+
2309
+ def _filter(self, category=Warning, message="", module=None, record=False):
2310
+ if record:
2311
+ record = [] # The log where to store warnings
2312
+ else:
2313
+ record = None
2314
+ if self._entered:
2315
+ if module is None:
2316
+ warnings.filterwarnings(
2317
+ "always", category=category, message=message)
2318
+ else:
2319
+ module_regex = module.__name__.replace('.', r'\.') + '$'
2320
+ warnings.filterwarnings(
2321
+ "always", category=category, message=message,
2322
+ module=module_regex)
2323
+ self._tmp_modules.add(module)
2324
+ self._clear_registries()
2325
+
2326
+ self._tmp_suppressions.append(
2327
+ (category, message, re.compile(message, re.I), module, record))
2328
+ else:
2329
+ self._suppressions.append(
2330
+ (category, message, re.compile(message, re.I), module, record))
2331
+
2332
+ return record
2333
+
2334
+ def filter(self, category=Warning, message="", module=None):
2335
+ """
2336
+ Add a new suppressing filter or apply it if the state is entered.
2337
+
2338
+ Parameters
2339
+ ----------
2340
+ category : class, optional
2341
+ Warning class to filter
2342
+ message : string, optional
2343
+ Regular expression matching the warning message.
2344
+ module : module, optional
2345
+ Module to filter for. Note that the module (and its file)
2346
+ must match exactly and cannot be a submodule. This may make
2347
+ it unreliable for external modules.
2348
+
2349
+ Notes
2350
+ -----
2351
+ When added within a context, filters are only added inside
2352
+ the context and will be forgotten when the context is exited.
2353
+ """
2354
+ self._filter(category=category, message=message, module=module,
2355
+ record=False)
2356
+
2357
+ def record(self, category=Warning, message="", module=None):
2358
+ """
2359
+ Append a new recording filter or apply it if the state is entered.
2360
+
2361
+ All warnings matching will be appended to the ``log`` attribute.
2362
+
2363
+ Parameters
2364
+ ----------
2365
+ category : class, optional
2366
+ Warning class to filter
2367
+ message : string, optional
2368
+ Regular expression matching the warning message.
2369
+ module : module, optional
2370
+ Module to filter for. Note that the module (and its file)
2371
+ must match exactly and cannot be a submodule. This may make
2372
+ it unreliable for external modules.
2373
+
2374
+ Returns
2375
+ -------
2376
+ log : list
2377
+ A list which will be filled with all matched warnings.
2378
+
2379
+ Notes
2380
+ -----
2381
+ When added within a context, filters are only added inside
2382
+ the context and will be forgotten when the context is exited.
2383
+ """
2384
+ return self._filter(category=category, message=message, module=module,
2385
+ record=True)
2386
+
2387
+ def __enter__(self):
2388
+ if self._entered:
2389
+ raise RuntimeError("cannot enter suppress_warnings twice.")
2390
+
2391
+ self._orig_show = warnings.showwarning
2392
+ self._filters = warnings.filters
2393
+ warnings.filters = self._filters[:]
2394
+
2395
+ self._entered = True
2396
+ self._tmp_suppressions = []
2397
+ self._tmp_modules = set()
2398
+ self._forwarded = set()
2399
+
2400
+ self.log = [] # reset global log (no need to keep same list)
2401
+
2402
+ for cat, mess, _, mod, log in self._suppressions:
2403
+ if log is not None:
2404
+ del log[:] # clear the log
2405
+ if mod is None:
2406
+ warnings.filterwarnings(
2407
+ "always", category=cat, message=mess)
2408
+ else:
2409
+ module_regex = mod.__name__.replace('.', r'\.') + '$'
2410
+ warnings.filterwarnings(
2411
+ "always", category=cat, message=mess,
2412
+ module=module_regex)
2413
+ self._tmp_modules.add(mod)
2414
+ warnings.showwarning = self._showwarning
2415
+ self._clear_registries()
2416
+
2417
+ return self
2418
+
2419
+ def __exit__(self, *exc_info):
2420
+ warnings.showwarning = self._orig_show
2421
+ warnings.filters = self._filters
2422
+ self._clear_registries()
2423
+ self._entered = False
2424
+ del self._orig_show
2425
+ del self._filters
2426
+
2427
+ def _showwarning(self, message, category, filename, lineno,
2428
+ *args, use_warnmsg=None, **kwargs):
2429
+ for cat, _, pattern, mod, rec in (
2430
+ self._suppressions + self._tmp_suppressions)[::-1]:
2431
+ if (issubclass(category, cat) and
2432
+ pattern.match(message.args[0]) is not None):
2433
+ if mod is None:
2434
+ # Message and category match, either recorded or ignored
2435
+ if rec is not None:
2436
+ msg = WarningMessage(message, category, filename,
2437
+ lineno, **kwargs)
2438
+ self.log.append(msg)
2439
+ rec.append(msg)
2440
+ return
2441
+ # Use startswith, because warnings strips the c or o from
2442
+ # .pyc/.pyo files.
2443
+ elif mod.__file__.startswith(filename):
2444
+ # The message and module (filename) match
2445
+ if rec is not None:
2446
+ msg = WarningMessage(message, category, filename,
2447
+ lineno, **kwargs)
2448
+ self.log.append(msg)
2449
+ rec.append(msg)
2450
+ return
2451
+
2452
+ # There is no filter in place, so pass to the outside handler
2453
+ # unless we should only pass it once
2454
+ if self._forwarding_rule == "always":
2455
+ if use_warnmsg is None:
2456
+ self._orig_show(message, category, filename, lineno,
2457
+ *args, **kwargs)
2458
+ else:
2459
+ self._orig_showmsg(use_warnmsg)
2460
+ return
2461
+
2462
+ if self._forwarding_rule == "once":
2463
+ signature = (message.args, category)
2464
+ elif self._forwarding_rule == "module":
2465
+ signature = (message.args, category, filename)
2466
+ elif self._forwarding_rule == "location":
2467
+ signature = (message.args, category, filename, lineno)
2468
+
2469
+ if signature in self._forwarded:
2470
+ return
2471
+ self._forwarded.add(signature)
2472
+ if use_warnmsg is None:
2473
+ self._orig_show(message, category, filename, lineno, *args,
2474
+ **kwargs)
2475
+ else:
2476
+ self._orig_showmsg(use_warnmsg)
2477
+
2478
+ def __call__(self, func):
2479
+ """
2480
+ Function decorator to apply certain suppressions to a whole
2481
+ function.
2482
+ """
2483
+ @wraps(func)
2484
+ def new_func(*args, **kwargs):
2485
+ with self:
2486
+ return func(*args, **kwargs)
2487
+
2488
+ return new_func
2489
+
2490
+
2491
+ @contextlib.contextmanager
2492
+ def _assert_no_gc_cycles_context(name=None):
2493
+ __tracebackhide__ = True # Hide traceback for py.test
2494
+
2495
+ # not meaningful to test if there is no refcounting
2496
+ if not HAS_REFCOUNT:
2497
+ yield
2498
+ return
2499
+
2500
+ assert_(gc.isenabled())
2501
+ gc.disable()
2502
+ gc_debug = gc.get_debug()
2503
+ try:
2504
+ for i in range(100):
2505
+ if gc.collect() == 0:
2506
+ break
2507
+ else:
2508
+ raise RuntimeError(
2509
+ "Unable to fully collect garbage - perhaps a __del__ method "
2510
+ "is creating more reference cycles?")
2511
+
2512
+ gc.set_debug(gc.DEBUG_SAVEALL)
2513
+ yield
2514
+ # gc.collect returns the number of unreachable objects in cycles that
2515
+ # were found -- we are checking that no cycles were created in the context
2516
+ n_objects_in_cycles = gc.collect()
2517
+ objects_in_cycles = gc.garbage[:]
2518
+ finally:
2519
+ del gc.garbage[:]
2520
+ gc.set_debug(gc_debug)
2521
+ gc.enable()
2522
+
2523
+ if n_objects_in_cycles:
2524
+ name_str = f' when calling {name}' if name is not None else ''
2525
+ raise AssertionError(
2526
+ "Reference cycles were found{}: {} objects were collected, "
2527
+ "of which {} are shown below:{}"
2528
+ .format(
2529
+ name_str,
2530
+ n_objects_in_cycles,
2531
+ len(objects_in_cycles),
2532
+ ''.join(
2533
+ "\n {} object with id={}:\n {}".format(
2534
+ type(o).__name__,
2535
+ id(o),
2536
+ pprint.pformat(o).replace('\n', '\n ')
2537
+ ) for o in objects_in_cycles
2538
+ )
2539
+ )
2540
+ )
2541
+
2542
+
2543
+ def assert_no_gc_cycles(*args, **kwargs):
2544
+ """
2545
+ Fail if the given callable produces any reference cycles.
2546
+
2547
+ If called with all arguments omitted, may be used as a context manager::
2548
+
2549
+ with assert_no_gc_cycles():
2550
+ do_something()
2551
+
2552
+ Parameters
2553
+ ----------
2554
+ func : callable
2555
+ The callable to test.
2556
+ \\*args : Arguments
2557
+ Arguments passed to `func`.
2558
+ \\*\\*kwargs : Kwargs
2559
+ Keyword arguments passed to `func`.
2560
+
2561
+ Returns
2562
+ -------
2563
+ Nothing. The result is deliberately discarded to ensure that all cycles
2564
+ are found.
2565
+
2566
+ """
2567
+ if not args:
2568
+ return _assert_no_gc_cycles_context()
2569
+
2570
+ func = args[0]
2571
+ args = args[1:]
2572
+ with _assert_no_gc_cycles_context(name=func.__name__):
2573
+ func(*args, **kwargs)
2574
+
2575
+
2576
+ def break_cycles():
2577
+ """
2578
+ Break reference cycles by calling gc.collect
2579
+ Objects can call other objects' methods (for instance, another object's
2580
+ __del__) inside their own __del__. On PyPy, the interpreter only runs
2581
+ between calls to gc.collect, so multiple calls are needed to completely
2582
+ release all cycles.
2583
+ """
2584
+
2585
+ gc.collect()
2586
+ if IS_PYPY:
2587
+ # a few more, just to make sure all the finalizers are called
2588
+ gc.collect()
2589
+ gc.collect()
2590
+ gc.collect()
2591
+ gc.collect()
2592
+
2593
+
2594
+ def requires_memory(free_bytes):
2595
+ """Decorator to skip a test if not enough memory is available"""
2596
+ import pytest
2597
+
2598
+ def decorator(func):
2599
+ @wraps(func)
2600
+ def wrapper(*a, **kw):
2601
+ msg = check_free_memory(free_bytes)
2602
+ if msg is not None:
2603
+ pytest.skip(msg)
2604
+
2605
+ try:
2606
+ return func(*a, **kw)
2607
+ except MemoryError:
2608
+ # Probably ran out of memory regardless: don't regard as failure
2609
+ pytest.xfail("MemoryError raised")
2610
+
2611
+ return wrapper
2612
+
2613
+ return decorator
2614
+
2615
+
2616
+ def check_free_memory(free_bytes):
2617
+ """
2618
+ Check whether `free_bytes` amount of memory is currently free.
2619
+ Returns: None if enough memory available, otherwise error message
2620
+ """
2621
+ env_var = 'NPY_AVAILABLE_MEM'
2622
+ env_value = os.environ.get(env_var)
2623
+ if env_value is not None:
2624
+ try:
2625
+ mem_free = _parse_size(env_value)
2626
+ except ValueError as exc:
2627
+ raise ValueError(f'Invalid environment variable {env_var}: {exc}')
2628
+
2629
+ msg = (f'{free_bytes / 1e9} GB memory required, but environment variable '
2630
+ f'NPY_AVAILABLE_MEM={env_value} set')
2631
+ else:
2632
+ mem_free = _get_mem_available()
2633
+
2634
+ if mem_free is None:
2635
+ msg = ("Could not determine available memory; set NPY_AVAILABLE_MEM "
2636
+ "environment variable (e.g. NPY_AVAILABLE_MEM=16GB) to run "
2637
+ "the test.")
2638
+ mem_free = -1
2639
+ else:
2640
+ free_bytes_gb = free_bytes / 1e9
2641
+ mem_free_gb = mem_free / 1e9
2642
+ msg = f'{free_bytes_gb} GB memory required, but {mem_free_gb} GB available'
2643
+
2644
+ return msg if mem_free < free_bytes else None
2645
+
2646
+
2647
+ def _parse_size(size_str):
2648
+ """Convert memory size strings ('12 GB' etc.) to float"""
2649
+ suffixes = {'': 1, 'b': 1,
2650
+ 'k': 1000, 'm': 1000**2, 'g': 1000**3, 't': 1000**4,
2651
+ 'kb': 1000, 'mb': 1000**2, 'gb': 1000**3, 'tb': 1000**4,
2652
+ 'kib': 1024, 'mib': 1024**2, 'gib': 1024**3, 'tib': 1024**4}
2653
+
2654
+ pipe_suffixes = "|".join(suffixes.keys())
2655
+
2656
+ size_re = re.compile(fr'^\s*(\d+|\d+\.\d+)\s*({pipe_suffixes})\s*$', re.I)
2657
+
2658
+ m = size_re.match(size_str.lower())
2659
+ if not m or m.group(2) not in suffixes:
2660
+ raise ValueError(f'value {size_str!r} not a valid size')
2661
+ return int(float(m.group(1)) * suffixes[m.group(2)])
2662
+
2663
+
2664
+ def _get_mem_available():
2665
+ """Return available memory in bytes, or None if unknown."""
2666
+ try:
2667
+ import psutil
2668
+ return psutil.virtual_memory().available
2669
+ except (ImportError, AttributeError):
2670
+ pass
2671
+
2672
+ if sys.platform.startswith('linux'):
2673
+ info = {}
2674
+ with open('/proc/meminfo') as f:
2675
+ for line in f:
2676
+ p = line.split()
2677
+ info[p[0].strip(':').lower()] = int(p[1]) * 1024
2678
+
2679
+ if 'memavailable' in info:
2680
+ # Linux >= 3.14
2681
+ return info['memavailable']
2682
+ else:
2683
+ return info['memfree'] + info['cached']
2684
+
2685
+ return None
2686
+
2687
+
2688
+ def _no_tracing(func):
2689
+ """
2690
+ Decorator to temporarily turn off tracing for the duration of a test.
2691
+ Needed in tests that check refcounting, otherwise the tracing itself
2692
+ influences the refcounts
2693
+ """
2694
+ if not hasattr(sys, 'gettrace'):
2695
+ return func
2696
+ else:
2697
+ @wraps(func)
2698
+ def wrapper(*args, **kwargs):
2699
+ original_trace = sys.gettrace()
2700
+ try:
2701
+ sys.settrace(None)
2702
+ return func(*args, **kwargs)
2703
+ finally:
2704
+ sys.settrace(original_trace)
2705
+ return wrapper
2706
+
2707
+
2708
+ def _get_glibc_version():
2709
+ try:
2710
+ ver = os.confstr('CS_GNU_LIBC_VERSION').rsplit(' ')[1]
2711
+ except Exception:
2712
+ ver = '0.0'
2713
+
2714
+ return ver
2715
+
2716
+
2717
+ _glibcver = _get_glibc_version()
2718
+ _glibc_older_than = lambda x: (_glibcver != '0.0' and _glibcver < x)
2719
+
2720
+
2721
+ def run_threaded(func, max_workers=8, pass_count=False,
2722
+ pass_barrier=False, outer_iterations=1,
2723
+ prepare_args=None):
2724
+ """Runs a function many times in parallel"""
2725
+ for _ in range(outer_iterations):
2726
+ with (concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
2727
+ as tpe):
2728
+ if prepare_args is None:
2729
+ args = []
2730
+ else:
2731
+ args = prepare_args()
2732
+ if pass_barrier:
2733
+ barrier = threading.Barrier(max_workers)
2734
+ args.append(barrier)
2735
+ if pass_count:
2736
+ all_args = [(func, i, *args) for i in range(max_workers)]
2737
+ else:
2738
+ all_args = [(func, *args) for i in range(max_workers)]
2739
+ try:
2740
+ futures = []
2741
+ for arg in all_args:
2742
+ futures.append(tpe.submit(*arg))
2743
+ except RuntimeError as e:
2744
+ import pytest
2745
+ pytest.skip(f"Spawning {max_workers} threads failed with "
2746
+ f"error {e!r} (likely due to resource limits on the "
2747
+ "system running the tests)")
2748
+ finally:
2749
+ if len(futures) < max_workers and pass_barrier:
2750
+ barrier.abort()
2751
+ for f in futures:
2752
+ f.result()