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