numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,4573 @@
1
+ import decimal
2
+ import math
3
+ import operator
4
+ import sys
5
+ import warnings
6
+ from fractions import Fraction
7
+ from functools import partial
8
+
9
+ import hypothesis
10
+ import hypothesis.strategies as st
11
+ import pytest
12
+ from hypothesis.extra.numpy import arrays
13
+
14
+ import numpy as np
15
+ import numpy.lib._function_base_impl as nfb
16
+ from numpy import (
17
+ angle,
18
+ average,
19
+ bartlett,
20
+ blackman,
21
+ corrcoef,
22
+ cov,
23
+ delete,
24
+ diff,
25
+ digitize,
26
+ extract,
27
+ flipud,
28
+ gradient,
29
+ hamming,
30
+ hanning,
31
+ i0,
32
+ insert,
33
+ interp,
34
+ kaiser,
35
+ ma,
36
+ meshgrid,
37
+ piecewise,
38
+ place,
39
+ rot90,
40
+ select,
41
+ setxor1d,
42
+ sinc,
43
+ trapezoid,
44
+ trim_zeros,
45
+ unique,
46
+ unwrap,
47
+ vectorize,
48
+ )
49
+ from numpy._core.numeric import normalize_axis_tuple
50
+ from numpy.exceptions import AxisError
51
+ from numpy.random import rand
52
+ from numpy.testing import (
53
+ HAS_REFCOUNT,
54
+ IS_WASM,
55
+ NOGIL_BUILD,
56
+ assert_,
57
+ assert_allclose,
58
+ assert_almost_equal,
59
+ assert_array_almost_equal,
60
+ assert_array_equal,
61
+ assert_equal,
62
+ assert_raises,
63
+ assert_raises_regex,
64
+ assert_warns,
65
+ suppress_warnings,
66
+ )
67
+
68
+
69
+ def get_mat(n):
70
+ data = np.arange(n)
71
+ data = np.add.outer(data, data)
72
+ return data
73
+
74
+
75
+ def _make_complex(real, imag):
76
+ """
77
+ Like real + 1j * imag, but behaves as expected when imag contains non-finite
78
+ values
79
+ """
80
+ ret = np.zeros(np.broadcast(real, imag).shape, np.complex128)
81
+ ret.real = real
82
+ ret.imag = imag
83
+ return ret
84
+
85
+
86
+ class TestRot90:
87
+ def test_basic(self):
88
+ assert_raises(ValueError, rot90, np.ones(4))
89
+ assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(0, 1, 2))
90
+ assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(0, 2))
91
+ assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(1, 1))
92
+ assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(-2, 1))
93
+
94
+ a = [[0, 1, 2],
95
+ [3, 4, 5]]
96
+ b1 = [[2, 5],
97
+ [1, 4],
98
+ [0, 3]]
99
+ b2 = [[5, 4, 3],
100
+ [2, 1, 0]]
101
+ b3 = [[3, 0],
102
+ [4, 1],
103
+ [5, 2]]
104
+ b4 = [[0, 1, 2],
105
+ [3, 4, 5]]
106
+
107
+ for k in range(-3, 13, 4):
108
+ assert_equal(rot90(a, k=k), b1)
109
+ for k in range(-2, 13, 4):
110
+ assert_equal(rot90(a, k=k), b2)
111
+ for k in range(-1, 13, 4):
112
+ assert_equal(rot90(a, k=k), b3)
113
+ for k in range(0, 13, 4):
114
+ assert_equal(rot90(a, k=k), b4)
115
+
116
+ assert_equal(rot90(rot90(a, axes=(0, 1)), axes=(1, 0)), a)
117
+ assert_equal(rot90(a, k=1, axes=(1, 0)), rot90(a, k=-1, axes=(0, 1)))
118
+
119
+ def test_axes(self):
120
+ a = np.ones((50, 40, 3))
121
+ assert_equal(rot90(a).shape, (40, 50, 3))
122
+ assert_equal(rot90(a, axes=(0, 2)), rot90(a, axes=(0, -1)))
123
+ assert_equal(rot90(a, axes=(1, 2)), rot90(a, axes=(-2, -1)))
124
+
125
+ def test_rotation_axes(self):
126
+ a = np.arange(8).reshape((2, 2, 2))
127
+
128
+ a_rot90_01 = [[[2, 3],
129
+ [6, 7]],
130
+ [[0, 1],
131
+ [4, 5]]]
132
+ a_rot90_12 = [[[1, 3],
133
+ [0, 2]],
134
+ [[5, 7],
135
+ [4, 6]]]
136
+ a_rot90_20 = [[[4, 0],
137
+ [6, 2]],
138
+ [[5, 1],
139
+ [7, 3]]]
140
+ a_rot90_10 = [[[4, 5],
141
+ [0, 1]],
142
+ [[6, 7],
143
+ [2, 3]]]
144
+
145
+ assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)
146
+ assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)
147
+ assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)
148
+
149
+ for k in range(1, 5):
150
+ assert_equal(rot90(a, k=k, axes=(2, 0)),
151
+ rot90(a_rot90_20, k=k - 1, axes=(2, 0)))
152
+
153
+
154
+ class TestFlip:
155
+
156
+ def test_axes(self):
157
+ assert_raises(AxisError, np.flip, np.ones(4), axis=1)
158
+ assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=2)
159
+ assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=-3)
160
+ assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
161
+
162
+ def test_basic_lr(self):
163
+ a = get_mat(4)
164
+ b = a[:, ::-1]
165
+ assert_equal(np.flip(a, 1), b)
166
+ a = [[0, 1, 2],
167
+ [3, 4, 5]]
168
+ b = [[2, 1, 0],
169
+ [5, 4, 3]]
170
+ assert_equal(np.flip(a, 1), b)
171
+
172
+ def test_basic_ud(self):
173
+ a = get_mat(4)
174
+ b = a[::-1, :]
175
+ assert_equal(np.flip(a, 0), b)
176
+ a = [[0, 1, 2],
177
+ [3, 4, 5]]
178
+ b = [[3, 4, 5],
179
+ [0, 1, 2]]
180
+ assert_equal(np.flip(a, 0), b)
181
+
182
+ def test_3d_swap_axis0(self):
183
+ a = np.array([[[0, 1],
184
+ [2, 3]],
185
+ [[4, 5],
186
+ [6, 7]]])
187
+
188
+ b = np.array([[[4, 5],
189
+ [6, 7]],
190
+ [[0, 1],
191
+ [2, 3]]])
192
+
193
+ assert_equal(np.flip(a, 0), b)
194
+
195
+ def test_3d_swap_axis1(self):
196
+ a = np.array([[[0, 1],
197
+ [2, 3]],
198
+ [[4, 5],
199
+ [6, 7]]])
200
+
201
+ b = np.array([[[2, 3],
202
+ [0, 1]],
203
+ [[6, 7],
204
+ [4, 5]]])
205
+
206
+ assert_equal(np.flip(a, 1), b)
207
+
208
+ def test_3d_swap_axis2(self):
209
+ a = np.array([[[0, 1],
210
+ [2, 3]],
211
+ [[4, 5],
212
+ [6, 7]]])
213
+
214
+ b = np.array([[[1, 0],
215
+ [3, 2]],
216
+ [[5, 4],
217
+ [7, 6]]])
218
+
219
+ assert_equal(np.flip(a, 2), b)
220
+
221
+ def test_4d(self):
222
+ a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
223
+ for i in range(a.ndim):
224
+ assert_equal(np.flip(a, i),
225
+ np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
226
+
227
+ def test_default_axis(self):
228
+ a = np.array([[1, 2, 3],
229
+ [4, 5, 6]])
230
+ b = np.array([[6, 5, 4],
231
+ [3, 2, 1]])
232
+ assert_equal(np.flip(a), b)
233
+
234
+ def test_multiple_axes(self):
235
+ a = np.array([[[0, 1],
236
+ [2, 3]],
237
+ [[4, 5],
238
+ [6, 7]]])
239
+
240
+ assert_equal(np.flip(a, axis=()), a)
241
+
242
+ b = np.array([[[5, 4],
243
+ [7, 6]],
244
+ [[1, 0],
245
+ [3, 2]]])
246
+
247
+ assert_equal(np.flip(a, axis=(0, 2)), b)
248
+
249
+ c = np.array([[[3, 2],
250
+ [1, 0]],
251
+ [[7, 6],
252
+ [5, 4]]])
253
+
254
+ assert_equal(np.flip(a, axis=(1, 2)), c)
255
+
256
+
257
+ class TestAny:
258
+
259
+ def test_basic(self):
260
+ y1 = [0, 0, 1, 0]
261
+ y2 = [0, 0, 0, 0]
262
+ y3 = [1, 0, 1, 0]
263
+ assert_(np.any(y1))
264
+ assert_(np.any(y3))
265
+ assert_(not np.any(y2))
266
+
267
+ def test_nd(self):
268
+ y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
269
+ assert_(np.any(y1))
270
+ assert_array_equal(np.any(y1, axis=0), [1, 1, 0])
271
+ assert_array_equal(np.any(y1, axis=1), [0, 1, 1])
272
+
273
+
274
+ class TestAll:
275
+
276
+ def test_basic(self):
277
+ y1 = [0, 1, 1, 0]
278
+ y2 = [0, 0, 0, 0]
279
+ y3 = [1, 1, 1, 1]
280
+ assert_(not np.all(y1))
281
+ assert_(np.all(y3))
282
+ assert_(not np.all(y2))
283
+ assert_(np.all(~np.array(y2)))
284
+
285
+ def test_nd(self):
286
+ y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
287
+ assert_(not np.all(y1))
288
+ assert_array_equal(np.all(y1, axis=0), [0, 0, 1])
289
+ assert_array_equal(np.all(y1, axis=1), [0, 0, 1])
290
+
291
+
292
+ @pytest.mark.parametrize("dtype", ["i8", "U10", "object", "datetime64[ms]"])
293
+ def test_any_and_all_result_dtype(dtype):
294
+ arr = np.ones(3, dtype=dtype)
295
+ assert np.any(arr).dtype == np.bool
296
+ assert np.all(arr).dtype == np.bool
297
+
298
+
299
+ class TestCopy:
300
+
301
+ def test_basic(self):
302
+ a = np.array([[1, 2], [3, 4]])
303
+ a_copy = np.copy(a)
304
+ assert_array_equal(a, a_copy)
305
+ a_copy[0, 0] = 10
306
+ assert_equal(a[0, 0], 1)
307
+ assert_equal(a_copy[0, 0], 10)
308
+
309
+ def test_order(self):
310
+ # It turns out that people rely on np.copy() preserving order by
311
+ # default; changing this broke scikit-learn:
312
+ # github.com/scikit-learn/scikit-learn/commit/7842748cf777412c506a8c0ed28090711d3a3783
313
+ a = np.array([[1, 2], [3, 4]])
314
+ assert_(a.flags.c_contiguous)
315
+ assert_(not a.flags.f_contiguous)
316
+ a_fort = np.array([[1, 2], [3, 4]], order="F")
317
+ assert_(not a_fort.flags.c_contiguous)
318
+ assert_(a_fort.flags.f_contiguous)
319
+ a_copy = np.copy(a)
320
+ assert_(a_copy.flags.c_contiguous)
321
+ assert_(not a_copy.flags.f_contiguous)
322
+ a_fort_copy = np.copy(a_fort)
323
+ assert_(not a_fort_copy.flags.c_contiguous)
324
+ assert_(a_fort_copy.flags.f_contiguous)
325
+
326
+ def test_subok(self):
327
+ mx = ma.ones(5)
328
+ assert_(not ma.isMaskedArray(np.copy(mx, subok=False)))
329
+ assert_(ma.isMaskedArray(np.copy(mx, subok=True)))
330
+ # Default behavior
331
+ assert_(not ma.isMaskedArray(np.copy(mx)))
332
+
333
+
334
+ class TestAverage:
335
+
336
+ def test_basic(self):
337
+ y1 = np.array([1, 2, 3])
338
+ assert_(average(y1, axis=0) == 2.)
339
+ y2 = np.array([1., 2., 3.])
340
+ assert_(average(y2, axis=0) == 2.)
341
+ y3 = [0., 0., 0.]
342
+ assert_(average(y3, axis=0) == 0.)
343
+
344
+ y4 = np.ones((4, 4))
345
+ y4[0, 1] = 0
346
+ y4[1, 0] = 2
347
+ assert_almost_equal(y4.mean(0), average(y4, 0))
348
+ assert_almost_equal(y4.mean(1), average(y4, 1))
349
+
350
+ y5 = rand(5, 5)
351
+ assert_almost_equal(y5.mean(0), average(y5, 0))
352
+ assert_almost_equal(y5.mean(1), average(y5, 1))
353
+
354
+ @pytest.mark.parametrize(
355
+ 'x, axis, expected_avg, weights, expected_wavg, expected_wsum',
356
+ [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]),
357
+ ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]],
358
+ [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])],
359
+ )
360
+ def test_basic_keepdims(self, x, axis, expected_avg,
361
+ weights, expected_wavg, expected_wsum):
362
+ avg = np.average(x, axis=axis, keepdims=True)
363
+ assert avg.shape == np.shape(expected_avg)
364
+ assert_array_equal(avg, expected_avg)
365
+
366
+ wavg = np.average(x, axis=axis, weights=weights, keepdims=True)
367
+ assert wavg.shape == np.shape(expected_wavg)
368
+ assert_array_equal(wavg, expected_wavg)
369
+
370
+ wavg, wsum = np.average(x, axis=axis, weights=weights, returned=True,
371
+ keepdims=True)
372
+ assert wavg.shape == np.shape(expected_wavg)
373
+ assert_array_equal(wavg, expected_wavg)
374
+ assert wsum.shape == np.shape(expected_wsum)
375
+ assert_array_equal(wsum, expected_wsum)
376
+
377
+ def test_weights(self):
378
+ y = np.arange(10)
379
+ w = np.arange(10)
380
+ actual = average(y, weights=w)
381
+ desired = (np.arange(10) ** 2).sum() * 1. / np.arange(10).sum()
382
+ assert_almost_equal(actual, desired)
383
+
384
+ y1 = np.array([[1, 2, 3], [4, 5, 6]])
385
+ w0 = [1, 2]
386
+ actual = average(y1, weights=w0, axis=0)
387
+ desired = np.array([3., 4., 5.])
388
+ assert_almost_equal(actual, desired)
389
+
390
+ w1 = [0, 0, 1]
391
+ actual = average(y1, weights=w1, axis=1)
392
+ desired = np.array([3., 6.])
393
+ assert_almost_equal(actual, desired)
394
+
395
+ # weights and input have different shapes but no axis is specified
396
+ with pytest.raises(
397
+ TypeError,
398
+ match="Axis must be specified when shapes of a "
399
+ "and weights differ"):
400
+ average(y1, weights=w1)
401
+
402
+ # 2D Case
403
+ w2 = [[0, 0, 1], [0, 0, 2]]
404
+ desired = np.array([3., 6.])
405
+ assert_array_equal(average(y1, weights=w2, axis=1), desired)
406
+ assert_equal(average(y1, weights=w2), 5.)
407
+
408
+ y3 = rand(5).astype(np.float32)
409
+ w3 = rand(5).astype(np.float64)
410
+
411
+ assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3))
412
+
413
+ # test weights with `keepdims=False` and `keepdims=True`
414
+ x = np.array([2, 3, 4]).reshape(3, 1)
415
+ w = np.array([4, 5, 6]).reshape(3, 1)
416
+
417
+ actual = np.average(x, weights=w, axis=1, keepdims=False)
418
+ desired = np.array([2., 3., 4.])
419
+ assert_array_equal(actual, desired)
420
+
421
+ actual = np.average(x, weights=w, axis=1, keepdims=True)
422
+ desired = np.array([[2.], [3.], [4.]])
423
+ assert_array_equal(actual, desired)
424
+
425
+ def test_weight_and_input_dims_different(self):
426
+ y = np.arange(12).reshape(2, 2, 3)
427
+ w = np.array([0., 0., 1., .5, .5, 0., 0., .5, .5, 1., 0., 0.])\
428
+ .reshape(2, 2, 3)
429
+
430
+ subw0 = w[:, :, 0]
431
+ actual = average(y, axis=(0, 1), weights=subw0)
432
+ desired = np.array([7., 8., 9.])
433
+ assert_almost_equal(actual, desired)
434
+
435
+ subw1 = w[1, :, :]
436
+ actual = average(y, axis=(1, 2), weights=subw1)
437
+ desired = np.array([2.25, 8.25])
438
+ assert_almost_equal(actual, desired)
439
+
440
+ subw2 = w[:, 0, :]
441
+ actual = average(y, axis=(0, 2), weights=subw2)
442
+ desired = np.array([4.75, 7.75])
443
+ assert_almost_equal(actual, desired)
444
+
445
+ # here the weights have the wrong shape for the specified axes
446
+ with pytest.raises(
447
+ ValueError,
448
+ match="Shape of weights must be consistent with "
449
+ "shape of a along specified axis"):
450
+ average(y, axis=(0, 1, 2), weights=subw0)
451
+
452
+ with pytest.raises(
453
+ ValueError,
454
+ match="Shape of weights must be consistent with "
455
+ "shape of a along specified axis"):
456
+ average(y, axis=(0, 1), weights=subw1)
457
+
458
+ # swapping the axes should be same as transposing weights
459
+ actual = average(y, axis=(1, 0), weights=subw0)
460
+ desired = average(y, axis=(0, 1), weights=subw0.T)
461
+ assert_almost_equal(actual, desired)
462
+
463
+ # if average over all axes, should have float output
464
+ actual = average(y, axis=(0, 1, 2), weights=w)
465
+ assert_(actual.ndim == 0)
466
+
467
+ def test_returned(self):
468
+ y = np.array([[1, 2, 3], [4, 5, 6]])
469
+
470
+ # No weights
471
+ avg, scl = average(y, returned=True)
472
+ assert_equal(scl, 6.)
473
+
474
+ avg, scl = average(y, 0, returned=True)
475
+ assert_array_equal(scl, np.array([2., 2., 2.]))
476
+
477
+ avg, scl = average(y, 1, returned=True)
478
+ assert_array_equal(scl, np.array([3., 3.]))
479
+
480
+ # With weights
481
+ w0 = [1, 2]
482
+ avg, scl = average(y, weights=w0, axis=0, returned=True)
483
+ assert_array_equal(scl, np.array([3., 3., 3.]))
484
+
485
+ w1 = [1, 2, 3]
486
+ avg, scl = average(y, weights=w1, axis=1, returned=True)
487
+ assert_array_equal(scl, np.array([6., 6.]))
488
+
489
+ w2 = [[0, 0, 1], [1, 2, 3]]
490
+ avg, scl = average(y, weights=w2, axis=1, returned=True)
491
+ assert_array_equal(scl, np.array([1., 6.]))
492
+
493
+ def test_subclasses(self):
494
+ class subclass(np.ndarray):
495
+ pass
496
+ a = np.array([[1, 2], [3, 4]]).view(subclass)
497
+ w = np.array([[1, 2], [3, 4]]).view(subclass)
498
+
499
+ assert_equal(type(np.average(a)), subclass)
500
+ assert_equal(type(np.average(a, weights=w)), subclass)
501
+
502
+ def test_upcasting(self):
503
+ typs = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),
504
+ ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]
505
+ for at, wt, rt in typs:
506
+ a = np.array([[1, 2], [3, 4]], dtype=at)
507
+ w = np.array([[1, 2], [3, 4]], dtype=wt)
508
+ assert_equal(np.average(a, weights=w).dtype, np.dtype(rt))
509
+
510
+ def test_object_dtype(self):
511
+ a = np.array([decimal.Decimal(x) for x in range(10)])
512
+ w = np.array([decimal.Decimal(1) for _ in range(10)])
513
+ w /= w.sum()
514
+ assert_almost_equal(a.mean(0), average(a, weights=w))
515
+
516
+ def test_object_no_weights(self):
517
+ a = np.array([decimal.Decimal(x) for x in range(10)])
518
+ m = average(a)
519
+ assert m == decimal.Decimal('4.5')
520
+
521
+ def test_average_class_without_dtype(self):
522
+ # see gh-21988
523
+ a = np.array([Fraction(1, 5), Fraction(3, 5)])
524
+ assert_equal(np.average(a), Fraction(2, 5))
525
+
526
+
527
+ class TestSelect:
528
+ choices = [np.array([1, 2, 3]),
529
+ np.array([4, 5, 6]),
530
+ np.array([7, 8, 9])]
531
+ conditions = [np.array([False, False, False]),
532
+ np.array([False, True, False]),
533
+ np.array([False, False, True])]
534
+
535
+ def _select(self, cond, values, default=0):
536
+ output = []
537
+ for m in range(len(cond)):
538
+ output += [V[m] for V, C in zip(values, cond) if C[m]] or [default]
539
+ return output
540
+
541
+ def test_basic(self):
542
+ choices = self.choices
543
+ conditions = self.conditions
544
+ assert_array_equal(select(conditions, choices, default=15),
545
+ self._select(conditions, choices, default=15))
546
+
547
+ assert_equal(len(choices), 3)
548
+ assert_equal(len(conditions), 3)
549
+
550
+ def test_broadcasting(self):
551
+ conditions = [np.array(True), np.array([False, True, False])]
552
+ choices = [1, np.arange(12).reshape(4, 3)]
553
+ assert_array_equal(select(conditions, choices), np.ones((4, 3)))
554
+ # default can broadcast too:
555
+ assert_equal(select([True], [0], default=[0]).shape, (1,))
556
+
557
+ def test_return_dtype(self):
558
+ assert_equal(select(self.conditions, self.choices, 1j).dtype,
559
+ np.complex128)
560
+ # But the conditions need to be stronger then the scalar default
561
+ # if it is scalar.
562
+ choices = [choice.astype(np.int8) for choice in self.choices]
563
+ assert_equal(select(self.conditions, choices).dtype, np.int8)
564
+
565
+ d = np.array([1, 2, 3, np.nan, 5, 7])
566
+ m = np.isnan(d)
567
+ assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0])
568
+
569
+ def test_deprecated_empty(self):
570
+ assert_raises(ValueError, select, [], [], 3j)
571
+ assert_raises(ValueError, select, [], [])
572
+
573
+ def test_non_bool_deprecation(self):
574
+ choices = self.choices
575
+ conditions = self.conditions[:]
576
+ conditions[0] = conditions[0].astype(np.int_)
577
+ assert_raises(TypeError, select, conditions, choices)
578
+ conditions[0] = conditions[0].astype(np.uint8)
579
+ assert_raises(TypeError, select, conditions, choices)
580
+ assert_raises(TypeError, select, conditions, choices)
581
+
582
+ def test_many_arguments(self):
583
+ # This used to be limited by NPY_MAXARGS == 32
584
+ conditions = [np.array([False])] * 100
585
+ choices = [np.array([1])] * 100
586
+ select(conditions, choices)
587
+
588
+
589
+ class TestInsert:
590
+
591
+ def test_basic(self):
592
+ a = [1, 2, 3]
593
+ assert_equal(insert(a, 0, 1), [1, 1, 2, 3])
594
+ assert_equal(insert(a, 3, 1), [1, 2, 3, 1])
595
+ assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3])
596
+ assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3])
597
+ assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9])
598
+ assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3])
599
+ assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9])
600
+ b = np.array([0, 1], dtype=np.float64)
601
+ assert_equal(insert(b, 0, b[0]), [0., 0., 1.])
602
+ assert_equal(insert(b, [], []), b)
603
+ assert_equal(insert(a, np.array([True] * 4), 9), [9, 1, 9, 2, 9, 3, 9])
604
+ assert_equal(insert(a, np.array([True, False, True, False]), 9),
605
+ [9, 1, 2, 9, 3])
606
+
607
+ def test_multidim(self):
608
+ a = [[1, 1, 1]]
609
+ r = [[2, 2, 2],
610
+ [1, 1, 1]]
611
+ assert_equal(insert(a, 0, [1]), [1, 1, 1, 1])
612
+ assert_equal(insert(a, 0, [2, 2, 2], axis=0), r)
613
+ assert_equal(insert(a, 0, 2, axis=0), r)
614
+ assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]])
615
+
616
+ a = np.array([[1, 1], [2, 2], [3, 3]])
617
+ b = np.arange(1, 4).repeat(3).reshape(3, 3)
618
+ c = np.concatenate(
619
+ (a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T,
620
+ a[:, 1:2]), axis=1)
621
+ assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b)
622
+ assert_equal(insert(a, [1], [1, 2, 3], axis=1), c)
623
+ # scalars behave differently, in this case exactly opposite:
624
+ assert_equal(insert(a, 1, [1, 2, 3], axis=1), b)
625
+ assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c)
626
+
627
+ a = np.arange(4).reshape(2, 2)
628
+ assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a)
629
+ assert_equal(insert(a[:1, :], 1, a[1, :], axis=0), a)
630
+
631
+ # negative axis value
632
+ a = np.arange(24).reshape((2, 3, 4))
633
+ assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
634
+ insert(a, 1, a[:, :, 3], axis=2))
635
+ assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
636
+ insert(a, 1, a[:, 2, :], axis=1))
637
+
638
+ # invalid axis value
639
+ assert_raises(AxisError, insert, a, 1, a[:, 2, :], axis=3)
640
+ assert_raises(AxisError, insert, a, 1, a[:, 2, :], axis=-4)
641
+
642
+ # negative axis value
643
+ a = np.arange(24).reshape((2, 3, 4))
644
+ assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
645
+ insert(a, 1, a[:, :, 3], axis=2))
646
+ assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
647
+ insert(a, 1, a[:, 2, :], axis=1))
648
+
649
+ def test_0d(self):
650
+ a = np.array(1)
651
+ with pytest.raises(AxisError):
652
+ insert(a, [], 2, axis=0)
653
+ with pytest.raises(TypeError):
654
+ insert(a, [], 2, axis="nonsense")
655
+
656
+ def test_subclass(self):
657
+ class SubClass(np.ndarray):
658
+ pass
659
+ a = np.arange(10).view(SubClass)
660
+ assert_(isinstance(np.insert(a, 0, [0]), SubClass))
661
+ assert_(isinstance(np.insert(a, [], []), SubClass))
662
+ assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass))
663
+ assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass))
664
+ assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass))
665
+ # This is an error in the future:
666
+ a = np.array(1).view(SubClass)
667
+ assert_(isinstance(np.insert(a, 0, [0]), SubClass))
668
+
669
+ def test_index_array_copied(self):
670
+ x = np.array([1, 1, 1])
671
+ np.insert([0, 1, 2], x, [3, 4, 5])
672
+ assert_equal(x, np.array([1, 1, 1]))
673
+
674
+ def test_structured_array(self):
675
+ a = np.array([(1, 'a'), (2, 'b'), (3, 'c')],
676
+ dtype=[('foo', 'i'), ('bar', 'S1')])
677
+ val = (4, 'd')
678
+ b = np.insert(a, 0, val)
679
+ assert_array_equal(b[0], np.array(val, dtype=b.dtype))
680
+ val = [(4, 'd')] * 2
681
+ b = np.insert(a, [0, 2], val)
682
+ assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))
683
+
684
+ def test_index_floats(self):
685
+ with pytest.raises(IndexError):
686
+ np.insert([0, 1, 2], np.array([1.0, 2.0]), [10, 20])
687
+ with pytest.raises(IndexError):
688
+ np.insert([0, 1, 2], np.array([], dtype=float), [])
689
+
690
+ @pytest.mark.parametrize('idx', [4, -4])
691
+ def test_index_out_of_bounds(self, idx):
692
+ with pytest.raises(IndexError, match='out of bounds'):
693
+ np.insert([0, 1, 2], [idx], [3, 4])
694
+
695
+
696
+ class TestAmax:
697
+
698
+ def test_basic(self):
699
+ a = [3, 4, 5, 10, -3, -5, 6.0]
700
+ assert_equal(np.amax(a), 10.0)
701
+ b = [[3, 6.0, 9.0],
702
+ [4, 10.0, 5.0],
703
+ [8, 3.0, 2.0]]
704
+ assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0])
705
+ assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
706
+
707
+
708
+ class TestAmin:
709
+
710
+ def test_basic(self):
711
+ a = [3, 4, 5, 10, -3, -5, 6.0]
712
+ assert_equal(np.amin(a), -5.0)
713
+ b = [[3, 6.0, 9.0],
714
+ [4, 10.0, 5.0],
715
+ [8, 3.0, 2.0]]
716
+ assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])
717
+ assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
718
+
719
+
720
+ class TestPtp:
721
+
722
+ def test_basic(self):
723
+ a = np.array([3, 4, 5, 10, -3, -5, 6.0])
724
+ assert_equal(np.ptp(a, axis=0), 15.0)
725
+ b = np.array([[3, 6.0, 9.0],
726
+ [4, 10.0, 5.0],
727
+ [8, 3.0, 2.0]])
728
+ assert_equal(np.ptp(b, axis=0), [5.0, 7.0, 7.0])
729
+ assert_equal(np.ptp(b, axis=-1), [6.0, 6.0, 6.0])
730
+
731
+ assert_equal(np.ptp(b, axis=0, keepdims=True), [[5.0, 7.0, 7.0]])
732
+ assert_equal(np.ptp(b, axis=(0, 1), keepdims=True), [[8.0]])
733
+
734
+
735
+ class TestCumsum:
736
+
737
+ @pytest.mark.parametrize("cumsum", [np.cumsum, np.cumulative_sum])
738
+ def test_basic(self, cumsum):
739
+ ba = [1, 2, 10, 11, 6, 5, 4]
740
+ ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
741
+ for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,
742
+ np.uint32, np.float32, np.float64, np.complex64,
743
+ np.complex128]:
744
+ a = np.array(ba, ctype)
745
+ a2 = np.array(ba2, ctype)
746
+
747
+ tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
748
+ assert_array_equal(cumsum(a, axis=0), tgt)
749
+
750
+ tgt = np.array(
751
+ [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
752
+ assert_array_equal(cumsum(a2, axis=0), tgt)
753
+
754
+ tgt = np.array(
755
+ [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
756
+ assert_array_equal(cumsum(a2, axis=1), tgt)
757
+
758
+
759
+ class TestProd:
760
+
761
+ def test_basic(self):
762
+ ba = [1, 2, 10, 11, 6, 5, 4]
763
+ ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
764
+ for ctype in [np.int16, np.uint16, np.int32, np.uint32,
765
+ np.float32, np.float64, np.complex64, np.complex128]:
766
+ a = np.array(ba, ctype)
767
+ a2 = np.array(ba2, ctype)
768
+ if ctype in ['1', 'b']:
769
+ assert_raises(ArithmeticError, np.prod, a)
770
+ assert_raises(ArithmeticError, np.prod, a2, 1)
771
+ else:
772
+ assert_equal(a.prod(axis=0), 26400)
773
+ assert_array_equal(a2.prod(axis=0),
774
+ np.array([50, 36, 84, 180], ctype))
775
+ assert_array_equal(a2.prod(axis=-1),
776
+ np.array([24, 1890, 600], ctype))
777
+
778
+
779
+ class TestCumprod:
780
+
781
+ @pytest.mark.parametrize("cumprod", [np.cumprod, np.cumulative_prod])
782
+ def test_basic(self, cumprod):
783
+ ba = [1, 2, 10, 11, 6, 5, 4]
784
+ ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
785
+ for ctype in [np.int16, np.uint16, np.int32, np.uint32,
786
+ np.float32, np.float64, np.complex64, np.complex128]:
787
+ a = np.array(ba, ctype)
788
+ a2 = np.array(ba2, ctype)
789
+ if ctype in ['1', 'b']:
790
+ assert_raises(ArithmeticError, cumprod, a)
791
+ assert_raises(ArithmeticError, cumprod, a2, 1)
792
+ assert_raises(ArithmeticError, cumprod, a)
793
+ else:
794
+ assert_array_equal(cumprod(a, axis=-1),
795
+ np.array([1, 2, 20, 220,
796
+ 1320, 6600, 26400], ctype))
797
+ assert_array_equal(cumprod(a2, axis=0),
798
+ np.array([[1, 2, 3, 4],
799
+ [5, 12, 21, 36],
800
+ [50, 36, 84, 180]], ctype))
801
+ assert_array_equal(cumprod(a2, axis=-1),
802
+ np.array([[1, 2, 6, 24],
803
+ [5, 30, 210, 1890],
804
+ [10, 30, 120, 600]], ctype))
805
+
806
+
807
+ def test_cumulative_include_initial():
808
+ arr = np.arange(8).reshape((2, 2, 2))
809
+
810
+ expected = np.array([
811
+ [[0, 0], [0, 1], [2, 4]], [[0, 0], [4, 5], [10, 12]]
812
+ ])
813
+ assert_array_equal(
814
+ np.cumulative_sum(arr, axis=1, include_initial=True), expected
815
+ )
816
+
817
+ expected = np.array([
818
+ [[1, 0, 0], [1, 2, 6]], [[1, 4, 20], [1, 6, 42]]
819
+ ])
820
+ assert_array_equal(
821
+ np.cumulative_prod(arr, axis=2, include_initial=True), expected
822
+ )
823
+
824
+ out = np.zeros((3, 2), dtype=np.float64)
825
+ expected = np.array([[0, 0], [1, 2], [4, 6]], dtype=np.float64)
826
+ arr = np.arange(1, 5).reshape((2, 2))
827
+ np.cumulative_sum(arr, axis=0, out=out, include_initial=True)
828
+ assert_array_equal(out, expected)
829
+
830
+ expected = np.array([1, 2, 4])
831
+ assert_array_equal(
832
+ np.cumulative_prod(np.array([2, 2]), include_initial=True), expected
833
+ )
834
+
835
+
836
+ class TestDiff:
837
+
838
+ def test_basic(self):
839
+ x = [1, 4, 6, 7, 12]
840
+ out = np.array([3, 2, 1, 5])
841
+ out2 = np.array([-1, -1, 4])
842
+ out3 = np.array([0, 5])
843
+ assert_array_equal(diff(x), out)
844
+ assert_array_equal(diff(x, n=2), out2)
845
+ assert_array_equal(diff(x, n=3), out3)
846
+
847
+ x = [1.1, 2.2, 3.0, -0.2, -0.1]
848
+ out = np.array([1.1, 0.8, -3.2, 0.1])
849
+ assert_almost_equal(diff(x), out)
850
+
851
+ x = [True, True, False, False]
852
+ out = np.array([False, True, False])
853
+ out2 = np.array([True, True])
854
+ assert_array_equal(diff(x), out)
855
+ assert_array_equal(diff(x, n=2), out2)
856
+
857
+ def test_axis(self):
858
+ x = np.zeros((10, 20, 30))
859
+ x[:, 1::2, :] = 1
860
+ exp = np.ones((10, 19, 30))
861
+ exp[:, 1::2, :] = -1
862
+ assert_array_equal(diff(x), np.zeros((10, 20, 29)))
863
+ assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29)))
864
+ assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30)))
865
+ assert_array_equal(diff(x, axis=1), exp)
866
+ assert_array_equal(diff(x, axis=-2), exp)
867
+ assert_raises(AxisError, diff, x, axis=3)
868
+ assert_raises(AxisError, diff, x, axis=-4)
869
+
870
+ x = np.array(1.11111111111, np.float64)
871
+ assert_raises(ValueError, diff, x)
872
+
873
+ def test_nd(self):
874
+ x = 20 * rand(10, 20, 30)
875
+ out1 = x[:, :, 1:] - x[:, :, :-1]
876
+ out2 = out1[:, :, 1:] - out1[:, :, :-1]
877
+ out3 = x[1:, :, :] - x[:-1, :, :]
878
+ out4 = out3[1:, :, :] - out3[:-1, :, :]
879
+ assert_array_equal(diff(x), out1)
880
+ assert_array_equal(diff(x, n=2), out2)
881
+ assert_array_equal(diff(x, axis=0), out3)
882
+ assert_array_equal(diff(x, n=2, axis=0), out4)
883
+
884
+ def test_n(self):
885
+ x = list(range(3))
886
+ assert_raises(ValueError, diff, x, n=-1)
887
+ output = [diff(x, n=n) for n in range(1, 5)]
888
+ expected = [[1, 1], [0], [], []]
889
+ assert_(diff(x, n=0) is x)
890
+ for n, (expected_n, output_n) in enumerate(zip(expected, output), start=1):
891
+ assert_(type(output_n) is np.ndarray)
892
+ assert_array_equal(output_n, expected_n)
893
+ assert_equal(output_n.dtype, np.int_)
894
+ assert_equal(len(output_n), max(0, len(x) - n))
895
+
896
+ def test_times(self):
897
+ x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
898
+ expected = [
899
+ np.array([1, 1], dtype='timedelta64[D]'),
900
+ np.array([0], dtype='timedelta64[D]'),
901
+ ]
902
+ expected.extend([np.array([], dtype='timedelta64[D]')] * 3)
903
+ for n, exp in enumerate(expected, start=1):
904
+ out = diff(x, n=n)
905
+ assert_array_equal(out, exp)
906
+ assert_equal(out.dtype, exp.dtype)
907
+
908
+ def test_subclass(self):
909
+ x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
910
+ mask=[[False, False], [True, False],
911
+ [False, True], [True, True], [False, False]])
912
+ out = diff(x)
913
+ assert_array_equal(out.data, [[1], [1], [1], [1], [1]])
914
+ assert_array_equal(out.mask, [[False], [True],
915
+ [True], [True], [False]])
916
+ assert_(type(out) is type(x))
917
+
918
+ out3 = diff(x, n=3)
919
+ assert_array_equal(out3.data, [[], [], [], [], []])
920
+ assert_array_equal(out3.mask, [[], [], [], [], []])
921
+ assert_(type(out3) is type(x))
922
+
923
+ def test_prepend(self):
924
+ x = np.arange(5) + 1
925
+ assert_array_equal(diff(x, prepend=0), np.ones(5))
926
+ assert_array_equal(diff(x, prepend=[0]), np.ones(5))
927
+ assert_array_equal(np.cumsum(np.diff(x, prepend=0)), x)
928
+ assert_array_equal(diff(x, prepend=[-1, 0]), np.ones(6))
929
+
930
+ x = np.arange(4).reshape(2, 2)
931
+ result = np.diff(x, axis=1, prepend=0)
932
+ expected = [[0, 1], [2, 1]]
933
+ assert_array_equal(result, expected)
934
+ result = np.diff(x, axis=1, prepend=[[0], [0]])
935
+ assert_array_equal(result, expected)
936
+
937
+ result = np.diff(x, axis=0, prepend=0)
938
+ expected = [[0, 1], [2, 2]]
939
+ assert_array_equal(result, expected)
940
+ result = np.diff(x, axis=0, prepend=[[0, 0]])
941
+ assert_array_equal(result, expected)
942
+
943
+ assert_raises(ValueError, np.diff, x, prepend=np.zeros((3, 3)))
944
+
945
+ assert_raises(AxisError, diff, x, prepend=0, axis=3)
946
+
947
+ def test_append(self):
948
+ x = np.arange(5)
949
+ result = diff(x, append=0)
950
+ expected = [1, 1, 1, 1, -4]
951
+ assert_array_equal(result, expected)
952
+ result = diff(x, append=[0])
953
+ assert_array_equal(result, expected)
954
+ result = diff(x, append=[0, 2])
955
+ expected = expected + [2]
956
+ assert_array_equal(result, expected)
957
+
958
+ x = np.arange(4).reshape(2, 2)
959
+ result = np.diff(x, axis=1, append=0)
960
+ expected = [[1, -1], [1, -3]]
961
+ assert_array_equal(result, expected)
962
+ result = np.diff(x, axis=1, append=[[0], [0]])
963
+ assert_array_equal(result, expected)
964
+
965
+ result = np.diff(x, axis=0, append=0)
966
+ expected = [[2, 2], [-2, -3]]
967
+ assert_array_equal(result, expected)
968
+ result = np.diff(x, axis=0, append=[[0, 0]])
969
+ assert_array_equal(result, expected)
970
+
971
+ assert_raises(ValueError, np.diff, x, append=np.zeros((3, 3)))
972
+
973
+ assert_raises(AxisError, diff, x, append=0, axis=3)
974
+
975
+
976
+ class TestDelete:
977
+
978
+ def setup_method(self):
979
+ self.a = np.arange(5)
980
+ self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)
981
+
982
+ def _check_inverse_of_slicing(self, indices):
983
+ a_del = delete(self.a, indices)
984
+ nd_a_del = delete(self.nd_a, indices, axis=1)
985
+ msg = f'Delete failed for obj: {indices!r}'
986
+ assert_array_equal(setxor1d(a_del, self.a[indices, ]), self.a,
987
+ err_msg=msg)
988
+ xor = setxor1d(nd_a_del[0, :, 0], self.nd_a[0, indices, 0])
989
+ assert_array_equal(xor, self.nd_a[0, :, 0], err_msg=msg)
990
+
991
+ def test_slices(self):
992
+ lims = [-6, -2, 0, 1, 2, 4, 5]
993
+ steps = [-3, -1, 1, 3]
994
+ for start in lims:
995
+ for stop in lims:
996
+ for step in steps:
997
+ s = slice(start, stop, step)
998
+ self._check_inverse_of_slicing(s)
999
+
1000
+ def test_fancy(self):
1001
+ self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]]))
1002
+ with pytest.raises(IndexError):
1003
+ delete(self.a, [100])
1004
+ with pytest.raises(IndexError):
1005
+ delete(self.a, [-100])
1006
+
1007
+ self._check_inverse_of_slicing([0, -1, 2, 2])
1008
+
1009
+ self._check_inverse_of_slicing([True, False, False, True, False])
1010
+
1011
+ # not legal, indexing with these would change the dimension
1012
+ with pytest.raises(ValueError):
1013
+ delete(self.a, True)
1014
+ with pytest.raises(ValueError):
1015
+ delete(self.a, False)
1016
+
1017
+ # not enough items
1018
+ with pytest.raises(ValueError):
1019
+ delete(self.a, [False] * 4)
1020
+
1021
+ def test_single(self):
1022
+ self._check_inverse_of_slicing(0)
1023
+ self._check_inverse_of_slicing(-4)
1024
+
1025
+ def test_0d(self):
1026
+ a = np.array(1)
1027
+ with pytest.raises(AxisError):
1028
+ delete(a, [], axis=0)
1029
+ with pytest.raises(TypeError):
1030
+ delete(a, [], axis="nonsense")
1031
+
1032
+ def test_subclass(self):
1033
+ class SubClass(np.ndarray):
1034
+ pass
1035
+ a = self.a.view(SubClass)
1036
+ assert_(isinstance(delete(a, 0), SubClass))
1037
+ assert_(isinstance(delete(a, []), SubClass))
1038
+ assert_(isinstance(delete(a, [0, 1]), SubClass))
1039
+ assert_(isinstance(delete(a, slice(1, 2)), SubClass))
1040
+ assert_(isinstance(delete(a, slice(1, -2)), SubClass))
1041
+
1042
+ def test_array_order_preserve(self):
1043
+ # See gh-7113
1044
+ k = np.arange(10).reshape(2, 5, order='F')
1045
+ m = delete(k, slice(60, None), axis=1)
1046
+
1047
+ # 'k' is Fortran ordered, and 'm' should have the
1048
+ # same ordering as 'k' and NOT become C ordered
1049
+ assert_equal(m.flags.c_contiguous, k.flags.c_contiguous)
1050
+ assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)
1051
+
1052
+ def test_index_floats(self):
1053
+ with pytest.raises(IndexError):
1054
+ np.delete([0, 1, 2], np.array([1.0, 2.0]))
1055
+ with pytest.raises(IndexError):
1056
+ np.delete([0, 1, 2], np.array([], dtype=float))
1057
+
1058
+ @pytest.mark.parametrize("indexer", [np.array([1]), [1]])
1059
+ def test_single_item_array(self, indexer):
1060
+ a_del_int = delete(self.a, 1)
1061
+ a_del = delete(self.a, indexer)
1062
+ assert_equal(a_del_int, a_del)
1063
+
1064
+ nd_a_del_int = delete(self.nd_a, 1, axis=1)
1065
+ nd_a_del = delete(self.nd_a, np.array([1]), axis=1)
1066
+ assert_equal(nd_a_del_int, nd_a_del)
1067
+
1068
+ def test_single_item_array_non_int(self):
1069
+ # Special handling for integer arrays must not affect non-integer ones.
1070
+ # If `False` was cast to `0` it would delete the element:
1071
+ res = delete(np.ones(1), np.array([False]))
1072
+ assert_array_equal(res, np.ones(1))
1073
+
1074
+ # Test the more complicated (with axis) case from gh-21840
1075
+ x = np.ones((3, 1))
1076
+ false_mask = np.array([False], dtype=bool)
1077
+ true_mask = np.array([True], dtype=bool)
1078
+
1079
+ res = delete(x, false_mask, axis=-1)
1080
+ assert_array_equal(res, x)
1081
+ res = delete(x, true_mask, axis=-1)
1082
+ assert_array_equal(res, x[:, :0])
1083
+
1084
+ # Object or e.g. timedeltas should *not* be allowed
1085
+ with pytest.raises(IndexError):
1086
+ delete(np.ones(2), np.array([0], dtype=object))
1087
+
1088
+ with pytest.raises(IndexError):
1089
+ # timedeltas are sometimes "integral, but clearly not allowed:
1090
+ delete(np.ones(2), np.array([0], dtype="m8[ns]"))
1091
+
1092
+
1093
+ class TestGradient:
1094
+
1095
+ def test_basic(self):
1096
+ v = [[1, 1], [3, 4]]
1097
+ x = np.array(v)
1098
+ dx = [np.array([[2., 3.], [2., 3.]]),
1099
+ np.array([[0., 0.], [1., 1.]])]
1100
+ assert_array_equal(gradient(x), dx)
1101
+ assert_array_equal(gradient(v), dx)
1102
+
1103
+ def test_args(self):
1104
+ dx = np.cumsum(np.ones(5))
1105
+ dx_uneven = [1., 2., 5., 9., 11.]
1106
+ f_2d = np.arange(25).reshape(5, 5)
1107
+
1108
+ # distances must be scalars or have size equal to gradient[axis]
1109
+ gradient(np.arange(5), 3.)
1110
+ gradient(np.arange(5), np.array(3.))
1111
+ gradient(np.arange(5), dx)
1112
+ # dy is set equal to dx because scalar
1113
+ gradient(f_2d, 1.5)
1114
+ gradient(f_2d, np.array(1.5))
1115
+
1116
+ gradient(f_2d, dx_uneven, dx_uneven)
1117
+ # mix between even and uneven spaces and
1118
+ # mix between scalar and vector
1119
+ gradient(f_2d, dx, 2)
1120
+
1121
+ # 2D but axis specified
1122
+ gradient(f_2d, dx, axis=1)
1123
+
1124
+ # 2d coordinate arguments are not yet allowed
1125
+ assert_raises_regex(ValueError, '.*scalars or 1d',
1126
+ gradient, f_2d, np.stack([dx] * 2, axis=-1), 1)
1127
+
1128
+ def test_badargs(self):
1129
+ f_2d = np.arange(25).reshape(5, 5)
1130
+ x = np.cumsum(np.ones(5))
1131
+
1132
+ # wrong sizes
1133
+ assert_raises(ValueError, gradient, f_2d, x, np.ones(2))
1134
+ assert_raises(ValueError, gradient, f_2d, 1, np.ones(2))
1135
+ assert_raises(ValueError, gradient, f_2d, np.ones(2), np.ones(2))
1136
+ # wrong number of arguments
1137
+ assert_raises(TypeError, gradient, f_2d, x)
1138
+ assert_raises(TypeError, gradient, f_2d, x, axis=(0, 1))
1139
+ assert_raises(TypeError, gradient, f_2d, x, x, x)
1140
+ assert_raises(TypeError, gradient, f_2d, 1, 1, 1)
1141
+ assert_raises(TypeError, gradient, f_2d, x, x, axis=1)
1142
+ assert_raises(TypeError, gradient, f_2d, 1, 1, axis=1)
1143
+
1144
+ def test_datetime64(self):
1145
+ # Make sure gradient() can handle special types like datetime64
1146
+ x = np.array(
1147
+ ['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',
1148
+ '1910-10-12', '1910-12-12', '1912-12-12'],
1149
+ dtype='datetime64[D]')
1150
+ dx = np.array(
1151
+ [-5, -3, 0, 31, 61, 396, 731],
1152
+ dtype='timedelta64[D]')
1153
+ assert_array_equal(gradient(x), dx)
1154
+ assert_(dx.dtype == np.dtype('timedelta64[D]'))
1155
+
1156
+ def test_masked(self):
1157
+ # Make sure that gradient supports subclasses like masked arrays
1158
+ x = np.ma.array([[1, 1], [3, 4]],
1159
+ mask=[[False, False], [False, False]])
1160
+ out = gradient(x)[0]
1161
+ assert_equal(type(out), type(x))
1162
+ # And make sure that the output and input don't have aliased mask
1163
+ # arrays
1164
+ assert_(x._mask is not out._mask)
1165
+ # Also check that edge_order=2 doesn't alter the original mask
1166
+ x2 = np.ma.arange(5)
1167
+ x2[2] = np.ma.masked
1168
+ np.gradient(x2, edge_order=2)
1169
+ assert_array_equal(x2.mask, [False, False, True, False, False])
1170
+
1171
+ def test_second_order_accurate(self):
1172
+ # Testing that the relative numerical error is less that 3% for
1173
+ # this example problem. This corresponds to second order
1174
+ # accurate finite differences for all interior and boundary
1175
+ # points.
1176
+ x = np.linspace(0, 1, 10)
1177
+ dx = x[1] - x[0]
1178
+ y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
1179
+ analytical = 6 * x ** 2 + 8 * x + 2
1180
+ num_error = np.abs((np.gradient(y, dx, edge_order=2) / analytical) - 1)
1181
+ assert_(np.all(num_error < 0.03) == True)
1182
+
1183
+ # test with unevenly spaced
1184
+ np.random.seed(0)
1185
+ x = np.sort(np.random.random(10))
1186
+ y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
1187
+ analytical = 6 * x ** 2 + 8 * x + 2
1188
+ num_error = np.abs((np.gradient(y, x, edge_order=2) / analytical) - 1)
1189
+ assert_(np.all(num_error < 0.03) == True)
1190
+
1191
+ def test_spacing(self):
1192
+ f = np.array([0, 2., 3., 4., 5., 5.])
1193
+ f = np.tile(f, (6, 1)) + f.reshape(-1, 1)
1194
+ x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])
1195
+ x_even = np.arange(6.)
1196
+
1197
+ fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6, 1))
1198
+ fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6, 1))
1199
+ fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6, 1))
1200
+ fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6, 1))
1201
+
1202
+ # evenly spaced
1203
+ for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:
1204
+ res1 = gradient(f, 1., axis=(0, 1), edge_order=edge_order)
1205
+ res2 = gradient(f, x_even, x_even,
1206
+ axis=(0, 1), edge_order=edge_order)
1207
+ res3 = gradient(f, x_even, x_even,
1208
+ axis=None, edge_order=edge_order)
1209
+ assert_array_equal(res1, res2)
1210
+ assert_array_equal(res2, res3)
1211
+ assert_almost_equal(res1[0], exp_res.T)
1212
+ assert_almost_equal(res1[1], exp_res)
1213
+
1214
+ res1 = gradient(f, 1., axis=0, edge_order=edge_order)
1215
+ res2 = gradient(f, x_even, axis=0, edge_order=edge_order)
1216
+ assert_(res1.shape == res2.shape)
1217
+ assert_almost_equal(res2, exp_res.T)
1218
+
1219
+ res1 = gradient(f, 1., axis=1, edge_order=edge_order)
1220
+ res2 = gradient(f, x_even, axis=1, edge_order=edge_order)
1221
+ assert_(res1.shape == res2.shape)
1222
+ assert_array_equal(res2, exp_res)
1223
+
1224
+ # unevenly spaced
1225
+ for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:
1226
+ res1 = gradient(f, x_uneven, x_uneven,
1227
+ axis=(0, 1), edge_order=edge_order)
1228
+ res2 = gradient(f, x_uneven, x_uneven,
1229
+ axis=None, edge_order=edge_order)
1230
+ assert_array_equal(res1, res2)
1231
+ assert_almost_equal(res1[0], exp_res.T)
1232
+ assert_almost_equal(res1[1], exp_res)
1233
+
1234
+ res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)
1235
+ assert_almost_equal(res1, exp_res.T)
1236
+
1237
+ res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)
1238
+ assert_almost_equal(res1, exp_res)
1239
+
1240
+ # mixed
1241
+ res1 = gradient(f, x_even, x_uneven, axis=(0, 1), edge_order=1)
1242
+ res2 = gradient(f, x_uneven, x_even, axis=(1, 0), edge_order=1)
1243
+ assert_array_equal(res1[0], res2[1])
1244
+ assert_array_equal(res1[1], res2[0])
1245
+ assert_almost_equal(res1[0], fdx_even_ord1.T)
1246
+ assert_almost_equal(res1[1], fdx_uneven_ord1)
1247
+
1248
+ res1 = gradient(f, x_even, x_uneven, axis=(0, 1), edge_order=2)
1249
+ res2 = gradient(f, x_uneven, x_even, axis=(1, 0), edge_order=2)
1250
+ assert_array_equal(res1[0], res2[1])
1251
+ assert_array_equal(res1[1], res2[0])
1252
+ assert_almost_equal(res1[0], fdx_even_ord2.T)
1253
+ assert_almost_equal(res1[1], fdx_uneven_ord2)
1254
+
1255
+ def test_specific_axes(self):
1256
+ # Testing that gradient can work on a given axis only
1257
+ v = [[1, 1], [3, 4]]
1258
+ x = np.array(v)
1259
+ dx = [np.array([[2., 3.], [2., 3.]]),
1260
+ np.array([[0., 0.], [1., 1.]])]
1261
+ assert_array_equal(gradient(x, axis=0), dx[0])
1262
+ assert_array_equal(gradient(x, axis=1), dx[1])
1263
+ assert_array_equal(gradient(x, axis=-1), dx[1])
1264
+ assert_array_equal(gradient(x, axis=(1, 0)), [dx[1], dx[0]])
1265
+
1266
+ # test axis=None which means all axes
1267
+ assert_almost_equal(gradient(x, axis=None), [dx[0], dx[1]])
1268
+ # and is the same as no axis keyword given
1269
+ assert_almost_equal(gradient(x, axis=None), gradient(x))
1270
+
1271
+ # test vararg order
1272
+ assert_array_equal(gradient(x, 2, 3, axis=(1, 0)),
1273
+ [dx[1] / 2.0, dx[0] / 3.0])
1274
+ # test maximal number of varargs
1275
+ assert_raises(TypeError, gradient, x, 1, 2, axis=1)
1276
+
1277
+ assert_raises(AxisError, gradient, x, axis=3)
1278
+ assert_raises(AxisError, gradient, x, axis=-3)
1279
+ # assert_raises(TypeError, gradient, x, axis=[1,])
1280
+
1281
+ def test_timedelta64(self):
1282
+ # Make sure gradient() can handle special types like timedelta64
1283
+ x = np.array(
1284
+ [-5, -3, 10, 12, 61, 321, 300],
1285
+ dtype='timedelta64[D]')
1286
+ dx = np.array(
1287
+ [2, 7, 7, 25, 154, 119, -21],
1288
+ dtype='timedelta64[D]')
1289
+ assert_array_equal(gradient(x), dx)
1290
+ assert_(dx.dtype == np.dtype('timedelta64[D]'))
1291
+
1292
+ def test_inexact_dtypes(self):
1293
+ for dt in [np.float16, np.float32, np.float64]:
1294
+ # dtypes should not be promoted in a different way to what diff does
1295
+ x = np.array([1, 2, 3], dtype=dt)
1296
+ assert_equal(gradient(x).dtype, np.diff(x).dtype)
1297
+
1298
+ def test_values(self):
1299
+ # needs at least 2 points for edge_order ==1
1300
+ gradient(np.arange(2), edge_order=1)
1301
+ # needs at least 3 points for edge_order ==1
1302
+ gradient(np.arange(3), edge_order=2)
1303
+
1304
+ assert_raises(ValueError, gradient, np.arange(0), edge_order=1)
1305
+ assert_raises(ValueError, gradient, np.arange(0), edge_order=2)
1306
+ assert_raises(ValueError, gradient, np.arange(1), edge_order=1)
1307
+ assert_raises(ValueError, gradient, np.arange(1), edge_order=2)
1308
+ assert_raises(ValueError, gradient, np.arange(2), edge_order=2)
1309
+
1310
+ @pytest.mark.parametrize('f_dtype', [np.uint8, np.uint16,
1311
+ np.uint32, np.uint64])
1312
+ def test_f_decreasing_unsigned_int(self, f_dtype):
1313
+ f = np.array([5, 4, 3, 2, 1], dtype=f_dtype)
1314
+ g = gradient(f)
1315
+ assert_array_equal(g, [-1] * len(f))
1316
+
1317
+ @pytest.mark.parametrize('f_dtype', [np.int8, np.int16,
1318
+ np.int32, np.int64])
1319
+ def test_f_signed_int_big_jump(self, f_dtype):
1320
+ maxint = np.iinfo(f_dtype).max
1321
+ x = np.array([1, 3])
1322
+ f = np.array([-1, maxint], dtype=f_dtype)
1323
+ dfdx = gradient(f, x)
1324
+ assert_array_equal(dfdx, [(maxint + 1) // 2] * 2)
1325
+
1326
+ @pytest.mark.parametrize('x_dtype', [np.uint8, np.uint16,
1327
+ np.uint32, np.uint64])
1328
+ def test_x_decreasing_unsigned(self, x_dtype):
1329
+ x = np.array([3, 2, 1], dtype=x_dtype)
1330
+ f = np.array([0, 2, 4])
1331
+ dfdx = gradient(f, x)
1332
+ assert_array_equal(dfdx, [-2] * len(x))
1333
+
1334
+ @pytest.mark.parametrize('x_dtype', [np.int8, np.int16,
1335
+ np.int32, np.int64])
1336
+ def test_x_signed_int_big_jump(self, x_dtype):
1337
+ minint = np.iinfo(x_dtype).min
1338
+ maxint = np.iinfo(x_dtype).max
1339
+ x = np.array([-1, maxint], dtype=x_dtype)
1340
+ f = np.array([minint // 2, 0])
1341
+ dfdx = gradient(f, x)
1342
+ assert_array_equal(dfdx, [0.5, 0.5])
1343
+
1344
+ def test_return_type(self):
1345
+ res = np.gradient(([1, 2], [2, 3]))
1346
+ assert type(res) is tuple
1347
+
1348
+
1349
+ class TestAngle:
1350
+
1351
+ def test_basic(self):
1352
+ x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
1353
+ 1, 1j, -1, -1j, 1 - 3j, -1 + 3j]
1354
+ y = angle(x)
1355
+ yo = [
1356
+ np.arctan(3.0 / 1.0),
1357
+ np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,
1358
+ -np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)]
1359
+ z = angle(x, deg=True)
1360
+ zo = np.array(yo) * 180 / np.pi
1361
+ assert_array_almost_equal(y, yo, 11)
1362
+ assert_array_almost_equal(z, zo, 11)
1363
+
1364
+ def test_subclass(self):
1365
+ x = np.ma.array([1 + 3j, 1, np.sqrt(2) / 2 * (1 + 1j)])
1366
+ x[1] = np.ma.masked
1367
+ expected = np.ma.array([np.arctan(3.0 / 1.0), 0, np.arctan(1.0)])
1368
+ expected[1] = np.ma.masked
1369
+ actual = angle(x)
1370
+ assert_equal(type(actual), type(expected))
1371
+ assert_equal(actual.mask, expected.mask)
1372
+ assert_equal(actual, expected)
1373
+
1374
+
1375
+ class TestTrimZeros:
1376
+
1377
+ a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
1378
+ b = a.astype(float)
1379
+ c = a.astype(complex)
1380
+ d = a.astype(object)
1381
+
1382
+ def values(self):
1383
+ attr_names = ('a', 'b', 'c', 'd')
1384
+ return (getattr(self, name) for name in attr_names)
1385
+
1386
+ def test_basic(self):
1387
+ slc = np.s_[2:-1]
1388
+ for arr in self.values():
1389
+ res = trim_zeros(arr)
1390
+ assert_array_equal(res, arr[slc])
1391
+
1392
+ def test_leading_skip(self):
1393
+ slc = np.s_[:-1]
1394
+ for arr in self.values():
1395
+ res = trim_zeros(arr, trim='b')
1396
+ assert_array_equal(res, arr[slc])
1397
+
1398
+ def test_trailing_skip(self):
1399
+ slc = np.s_[2:]
1400
+ for arr in self.values():
1401
+ res = trim_zeros(arr, trim='F')
1402
+ assert_array_equal(res, arr[slc])
1403
+
1404
+ def test_all_zero(self):
1405
+ for _arr in self.values():
1406
+ arr = np.zeros_like(_arr, dtype=_arr.dtype)
1407
+
1408
+ res1 = trim_zeros(arr, trim='B')
1409
+ assert len(res1) == 0
1410
+
1411
+ res2 = trim_zeros(arr, trim='f')
1412
+ assert len(res2) == 0
1413
+
1414
+ def test_size_zero(self):
1415
+ arr = np.zeros(0)
1416
+ res = trim_zeros(arr)
1417
+ assert_array_equal(arr, res)
1418
+
1419
+ @pytest.mark.parametrize(
1420
+ 'arr',
1421
+ [np.array([0, 2**62, 0]),
1422
+ np.array([0, 2**63, 0]),
1423
+ np.array([0, 2**64, 0])]
1424
+ )
1425
+ def test_overflow(self, arr):
1426
+ slc = np.s_[1:2]
1427
+ res = trim_zeros(arr)
1428
+ assert_array_equal(res, arr[slc])
1429
+
1430
+ def test_no_trim(self):
1431
+ arr = np.array([None, 1, None])
1432
+ res = trim_zeros(arr)
1433
+ assert_array_equal(arr, res)
1434
+
1435
+ def test_list_to_list(self):
1436
+ res = trim_zeros(self.a.tolist())
1437
+ assert isinstance(res, list)
1438
+
1439
+ @pytest.mark.parametrize("ndim", (0, 1, 2, 3, 10))
1440
+ def test_nd_basic(self, ndim):
1441
+ a = np.ones((2,) * ndim)
1442
+ b = np.pad(a, (2, 1), mode="constant", constant_values=0)
1443
+ res = trim_zeros(b, axis=None)
1444
+ assert_array_equal(a, res)
1445
+
1446
+ @pytest.mark.parametrize("ndim", (0, 1, 2, 3))
1447
+ def test_allzero(self, ndim):
1448
+ a = np.zeros((3,) * ndim)
1449
+ res = trim_zeros(a, axis=None)
1450
+ assert_array_equal(res, np.zeros((0,) * ndim))
1451
+
1452
+ def test_trim_arg(self):
1453
+ a = np.array([0, 1, 2, 0])
1454
+
1455
+ res = trim_zeros(a, trim='f')
1456
+ assert_array_equal(res, [1, 2, 0])
1457
+
1458
+ res = trim_zeros(a, trim='b')
1459
+ assert_array_equal(res, [0, 1, 2])
1460
+
1461
+ @pytest.mark.parametrize("trim", ("front", ""))
1462
+ def test_unexpected_trim_value(self, trim):
1463
+ arr = self.a
1464
+ with pytest.raises(ValueError, match=r"unexpected character\(s\) in `trim`"):
1465
+ trim_zeros(arr, trim=trim)
1466
+
1467
+
1468
+ class TestExtins:
1469
+
1470
+ def test_basic(self):
1471
+ a = np.array([1, 3, 2, 1, 2, 3, 3])
1472
+ b = extract(a > 1, a)
1473
+ assert_array_equal(b, [3, 2, 2, 3, 3])
1474
+
1475
+ def test_place(self):
1476
+ # Make sure that non-np.ndarray objects
1477
+ # raise an error instead of doing nothing
1478
+ assert_raises(TypeError, place, [1, 2, 3], [True, False], [0, 1])
1479
+
1480
+ a = np.array([1, 4, 3, 2, 5, 8, 7])
1481
+ place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6])
1482
+ assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7])
1483
+
1484
+ place(a, np.zeros(7), [])
1485
+ assert_array_equal(a, np.arange(1, 8))
1486
+
1487
+ place(a, [1, 0, 1, 0, 1, 0, 1], [8, 9])
1488
+ assert_array_equal(a, [8, 2, 9, 4, 8, 6, 9])
1489
+ assert_raises_regex(ValueError, "Cannot insert from an empty array",
1490
+ lambda: place(a, [0, 0, 0, 0, 0, 1, 0], []))
1491
+
1492
+ # See Issue #6974
1493
+ a = np.array(['12', '34'])
1494
+ place(a, [0, 1], '9')
1495
+ assert_array_equal(a, ['12', '9'])
1496
+
1497
+ def test_both(self):
1498
+ a = rand(10)
1499
+ mask = a > 0.5
1500
+ ac = a.copy()
1501
+ c = extract(mask, a)
1502
+ place(a, mask, 0)
1503
+ place(a, mask, c)
1504
+ assert_array_equal(a, ac)
1505
+
1506
+
1507
+ # _foo1 and _foo2 are used in some tests in TestVectorize.
1508
+
1509
+ def _foo1(x, y=1.0):
1510
+ return y * math.floor(x)
1511
+
1512
+
1513
+ def _foo2(x, y=1.0, z=0.0):
1514
+ return y * math.floor(x) + z
1515
+
1516
+
1517
+ class TestVectorize:
1518
+
1519
+ def test_simple(self):
1520
+ def addsubtract(a, b):
1521
+ if a > b:
1522
+ return a - b
1523
+ else:
1524
+ return a + b
1525
+
1526
+ f = vectorize(addsubtract)
1527
+ r = f([0, 3, 6, 9], [1, 3, 5, 7])
1528
+ assert_array_equal(r, [1, 6, 1, 2])
1529
+
1530
+ def test_scalar(self):
1531
+ def addsubtract(a, b):
1532
+ if a > b:
1533
+ return a - b
1534
+ else:
1535
+ return a + b
1536
+
1537
+ f = vectorize(addsubtract)
1538
+ r = f([0, 3, 6, 9], 5)
1539
+ assert_array_equal(r, [5, 8, 1, 4])
1540
+
1541
+ def test_large(self):
1542
+ x = np.linspace(-3, 2, 10000)
1543
+ f = vectorize(lambda x: x)
1544
+ y = f(x)
1545
+ assert_array_equal(y, x)
1546
+
1547
+ def test_ufunc(self):
1548
+ f = vectorize(math.cos)
1549
+ args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])
1550
+ r1 = f(args)
1551
+ r2 = np.cos(args)
1552
+ assert_array_almost_equal(r1, r2)
1553
+
1554
+ def test_keywords(self):
1555
+
1556
+ def foo(a, b=1):
1557
+ return a + b
1558
+
1559
+ f = vectorize(foo)
1560
+ args = np.array([1, 2, 3])
1561
+ r1 = f(args)
1562
+ r2 = np.array([2, 3, 4])
1563
+ assert_array_equal(r1, r2)
1564
+ r1 = f(args, 2)
1565
+ r2 = np.array([3, 4, 5])
1566
+ assert_array_equal(r1, r2)
1567
+
1568
+ def test_keywords_with_otypes_order1(self):
1569
+ # gh-1620: The second call of f would crash with
1570
+ # `ValueError: invalid number of arguments`.
1571
+ f = vectorize(_foo1, otypes=[float])
1572
+ # We're testing the caching of ufuncs by vectorize, so the order
1573
+ # of these function calls is an important part of the test.
1574
+ r1 = f(np.arange(3.0), 1.0)
1575
+ r2 = f(np.arange(3.0))
1576
+ assert_array_equal(r1, r2)
1577
+
1578
+ def test_keywords_with_otypes_order2(self):
1579
+ # gh-1620: The second call of f would crash with
1580
+ # `ValueError: non-broadcastable output operand with shape ()
1581
+ # doesn't match the broadcast shape (3,)`.
1582
+ f = vectorize(_foo1, otypes=[float])
1583
+ # We're testing the caching of ufuncs by vectorize, so the order
1584
+ # of these function calls is an important part of the test.
1585
+ r1 = f(np.arange(3.0))
1586
+ r2 = f(np.arange(3.0), 1.0)
1587
+ assert_array_equal(r1, r2)
1588
+
1589
+ def test_keywords_with_otypes_order3(self):
1590
+ # gh-1620: The third call of f would crash with
1591
+ # `ValueError: invalid number of arguments`.
1592
+ f = vectorize(_foo1, otypes=[float])
1593
+ # We're testing the caching of ufuncs by vectorize, so the order
1594
+ # of these function calls is an important part of the test.
1595
+ r1 = f(np.arange(3.0))
1596
+ r2 = f(np.arange(3.0), y=1.0)
1597
+ r3 = f(np.arange(3.0))
1598
+ assert_array_equal(r1, r2)
1599
+ assert_array_equal(r1, r3)
1600
+
1601
+ def test_keywords_with_otypes_several_kwd_args1(self):
1602
+ # gh-1620 Make sure different uses of keyword arguments
1603
+ # don't break the vectorized function.
1604
+ f = vectorize(_foo2, otypes=[float])
1605
+ # We're testing the caching of ufuncs by vectorize, so the order
1606
+ # of these function calls is an important part of the test.
1607
+ r1 = f(10.4, z=100)
1608
+ r2 = f(10.4, y=-1)
1609
+ r3 = f(10.4)
1610
+ assert_equal(r1, _foo2(10.4, z=100))
1611
+ assert_equal(r2, _foo2(10.4, y=-1))
1612
+ assert_equal(r3, _foo2(10.4))
1613
+
1614
+ def test_keywords_with_otypes_several_kwd_args2(self):
1615
+ # gh-1620 Make sure different uses of keyword arguments
1616
+ # don't break the vectorized function.
1617
+ f = vectorize(_foo2, otypes=[float])
1618
+ # We're testing the caching of ufuncs by vectorize, so the order
1619
+ # of these function calls is an important part of the test.
1620
+ r1 = f(z=100, x=10.4, y=-1)
1621
+ r2 = f(1, 2, 3)
1622
+ assert_equal(r1, _foo2(z=100, x=10.4, y=-1))
1623
+ assert_equal(r2, _foo2(1, 2, 3))
1624
+
1625
+ def test_keywords_no_func_code(self):
1626
+ # This needs to test a function that has keywords but
1627
+ # no func_code attribute, since otherwise vectorize will
1628
+ # inspect the func_code.
1629
+ import random
1630
+ try:
1631
+ vectorize(random.randrange) # Should succeed
1632
+ except Exception:
1633
+ raise AssertionError
1634
+
1635
+ def test_keywords2_ticket_2100(self):
1636
+ # Test kwarg support: enhancement ticket 2100
1637
+
1638
+ def foo(a, b=1):
1639
+ return a + b
1640
+
1641
+ f = vectorize(foo)
1642
+ args = np.array([1, 2, 3])
1643
+ r1 = f(a=args)
1644
+ r2 = np.array([2, 3, 4])
1645
+ assert_array_equal(r1, r2)
1646
+ r1 = f(b=1, a=args)
1647
+ assert_array_equal(r1, r2)
1648
+ r1 = f(args, b=2)
1649
+ r2 = np.array([3, 4, 5])
1650
+ assert_array_equal(r1, r2)
1651
+
1652
+ def test_keywords3_ticket_2100(self):
1653
+ # Test excluded with mixed positional and kwargs: ticket 2100
1654
+ def mypolyval(x, p):
1655
+ _p = list(p)
1656
+ res = _p.pop(0)
1657
+ while _p:
1658
+ res = res * x + _p.pop(0)
1659
+ return res
1660
+
1661
+ vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
1662
+ ans = [3, 6]
1663
+ assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
1664
+ assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
1665
+ assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))
1666
+
1667
+ def test_keywords4_ticket_2100(self):
1668
+ # Test vectorizing function with no positional args.
1669
+ @vectorize
1670
+ def f(**kw):
1671
+ res = 1.0
1672
+ for _k in kw:
1673
+ res *= kw[_k]
1674
+ return res
1675
+
1676
+ assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])
1677
+
1678
+ def test_keywords5_ticket_2100(self):
1679
+ # Test vectorizing function with no kwargs args.
1680
+ @vectorize
1681
+ def f(*v):
1682
+ return np.prod(v)
1683
+
1684
+ assert_array_equal(f([1, 2], [3, 4]), [3, 8])
1685
+
1686
+ def test_coverage1_ticket_2100(self):
1687
+ def foo():
1688
+ return 1
1689
+
1690
+ f = vectorize(foo)
1691
+ assert_array_equal(f(), 1)
1692
+
1693
+ def test_assigning_docstring(self):
1694
+ def foo(x):
1695
+ """Original documentation"""
1696
+ return x
1697
+
1698
+ f = vectorize(foo)
1699
+ assert_equal(f.__doc__, foo.__doc__)
1700
+
1701
+ doc = "Provided documentation"
1702
+ f = vectorize(foo, doc=doc)
1703
+ assert_equal(f.__doc__, doc)
1704
+
1705
+ def test_UnboundMethod_ticket_1156(self):
1706
+ # Regression test for issue 1156
1707
+ class Foo:
1708
+ b = 2
1709
+
1710
+ def bar(self, a):
1711
+ return a ** self.b
1712
+
1713
+ assert_array_equal(vectorize(Foo().bar)(np.arange(9)),
1714
+ np.arange(9) ** 2)
1715
+ assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),
1716
+ np.arange(9) ** 2)
1717
+
1718
+ def test_execution_order_ticket_1487(self):
1719
+ # Regression test for dependence on execution order: issue 1487
1720
+ f1 = vectorize(lambda x: x)
1721
+ res1a = f1(np.arange(3))
1722
+ res1b = f1(np.arange(0.1, 3))
1723
+ f2 = vectorize(lambda x: x)
1724
+ res2b = f2(np.arange(0.1, 3))
1725
+ res2a = f2(np.arange(3))
1726
+ assert_equal(res1a, res2a)
1727
+ assert_equal(res1b, res2b)
1728
+
1729
+ def test_string_ticket_1892(self):
1730
+ # Test vectorization over strings: issue 1892.
1731
+ f = np.vectorize(lambda x: x)
1732
+ s = '0123456789' * 10
1733
+ assert_equal(s, f(s))
1734
+
1735
+ def test_dtype_promotion_gh_29189(self):
1736
+ # dtype should not be silently promoted (int32 -> int64)
1737
+ dtypes = [np.int16, np.int32, np.int64, np.float16, np.float32, np.float64]
1738
+
1739
+ for dtype in dtypes:
1740
+ x = np.asarray([1, 2, 3], dtype=dtype)
1741
+ y = np.vectorize(lambda x: x + x)(x)
1742
+ assert x.dtype == y.dtype
1743
+
1744
+ def test_cache(self):
1745
+ # Ensure that vectorized func called exactly once per argument.
1746
+ _calls = [0]
1747
+
1748
+ @vectorize
1749
+ def f(x):
1750
+ _calls[0] += 1
1751
+ return x ** 2
1752
+
1753
+ f.cache = True
1754
+ x = np.arange(5)
1755
+ assert_array_equal(f(x), x * x)
1756
+ assert_equal(_calls[0], len(x))
1757
+
1758
+ def test_otypes(self):
1759
+ f = np.vectorize(lambda x: x)
1760
+ f.otypes = 'i'
1761
+ x = np.arange(5)
1762
+ assert_array_equal(f(x), x)
1763
+
1764
+ def test_otypes_object_28624(self):
1765
+ # with object otype, the vectorized function should return y
1766
+ # wrapped into an object array
1767
+ y = np.arange(3)
1768
+ f = vectorize(lambda x: y, otypes=[object])
1769
+
1770
+ assert f(None).item() is y
1771
+ assert f([None]).item() is y
1772
+
1773
+ y = [1, 2, 3]
1774
+ f = vectorize(lambda x: y, otypes=[object])
1775
+
1776
+ assert f(None).item() is y
1777
+ assert f([None]).item() is y
1778
+
1779
+ def test_parse_gufunc_signature(self):
1780
+ assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))
1781
+ assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),
1782
+ ([('x', 'y')], [()]))
1783
+ assert_equal(nfb._parse_gufunc_signature('(x),(y)->()'),
1784
+ ([('x',), ('y',)], [()]))
1785
+ assert_equal(nfb._parse_gufunc_signature('(x)->(y)'),
1786
+ ([('x',)], [('y',)]))
1787
+ assert_equal(nfb._parse_gufunc_signature('(x)->(y),()'),
1788
+ ([('x',)], [('y',), ()]))
1789
+ assert_equal(nfb._parse_gufunc_signature('(),(a,b,c),(d)->(d,e)'),
1790
+ ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
1791
+
1792
+ # Tests to check if whitespaces are ignored
1793
+ assert_equal(nfb._parse_gufunc_signature('(x )->()'), ([('x',)], [()]))
1794
+ assert_equal(nfb._parse_gufunc_signature('( x , y )->( )'),
1795
+ ([('x', 'y')], [()]))
1796
+ assert_equal(nfb._parse_gufunc_signature('(x),( y) ->()'),
1797
+ ([('x',), ('y',)], [()]))
1798
+ assert_equal(nfb._parse_gufunc_signature('( x)-> (y ) '),
1799
+ ([('x',)], [('y',)]))
1800
+ assert_equal(nfb._parse_gufunc_signature(' (x)->( y),( )'),
1801
+ ([('x',)], [('y',), ()]))
1802
+ assert_equal(nfb._parse_gufunc_signature(
1803
+ '( ), ( a, b,c ) ,( d) -> (d , e)'),
1804
+ ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
1805
+
1806
+ with assert_raises(ValueError):
1807
+ nfb._parse_gufunc_signature('(x)(y)->()')
1808
+ with assert_raises(ValueError):
1809
+ nfb._parse_gufunc_signature('(x),(y)->')
1810
+ with assert_raises(ValueError):
1811
+ nfb._parse_gufunc_signature('((x))->(x)')
1812
+
1813
+ def test_signature_simple(self):
1814
+ def addsubtract(a, b):
1815
+ if a > b:
1816
+ return a - b
1817
+ else:
1818
+ return a + b
1819
+
1820
+ f = vectorize(addsubtract, signature='(),()->()')
1821
+ r = f([0, 3, 6, 9], [1, 3, 5, 7])
1822
+ assert_array_equal(r, [1, 6, 1, 2])
1823
+
1824
+ def test_signature_mean_last(self):
1825
+ def mean(a):
1826
+ return a.mean()
1827
+
1828
+ f = vectorize(mean, signature='(n)->()')
1829
+ r = f([[1, 3], [2, 4]])
1830
+ assert_array_equal(r, [2, 3])
1831
+
1832
+ def test_signature_center(self):
1833
+ def center(a):
1834
+ return a - a.mean()
1835
+
1836
+ f = vectorize(center, signature='(n)->(n)')
1837
+ r = f([[1, 3], [2, 4]])
1838
+ assert_array_equal(r, [[-1, 1], [-1, 1]])
1839
+
1840
+ def test_signature_two_outputs(self):
1841
+ f = vectorize(lambda x: (x, x), signature='()->(),()')
1842
+ r = f([1, 2, 3])
1843
+ assert_(isinstance(r, tuple) and len(r) == 2)
1844
+ assert_array_equal(r[0], [1, 2, 3])
1845
+ assert_array_equal(r[1], [1, 2, 3])
1846
+
1847
+ def test_signature_outer(self):
1848
+ f = vectorize(np.outer, signature='(a),(b)->(a,b)')
1849
+ r = f([1, 2], [1, 2, 3])
1850
+ assert_array_equal(r, [[1, 2, 3], [2, 4, 6]])
1851
+
1852
+ r = f([[[1, 2]]], [1, 2, 3])
1853
+ assert_array_equal(r, [[[[1, 2, 3], [2, 4, 6]]]])
1854
+
1855
+ r = f([[1, 0], [2, 0]], [1, 2, 3])
1856
+ assert_array_equal(r, [[[1, 2, 3], [0, 0, 0]],
1857
+ [[2, 4, 6], [0, 0, 0]]])
1858
+
1859
+ r = f([1, 2], [[1, 2, 3], [0, 0, 0]])
1860
+ assert_array_equal(r, [[[1, 2, 3], [2, 4, 6]],
1861
+ [[0, 0, 0], [0, 0, 0]]])
1862
+
1863
+ def test_signature_computed_size(self):
1864
+ f = vectorize(lambda x: x[:-1], signature='(n)->(m)')
1865
+ r = f([1, 2, 3])
1866
+ assert_array_equal(r, [1, 2])
1867
+
1868
+ r = f([[1, 2, 3], [2, 3, 4]])
1869
+ assert_array_equal(r, [[1, 2], [2, 3]])
1870
+
1871
+ def test_signature_excluded(self):
1872
+
1873
+ def foo(a, b=1):
1874
+ return a + b
1875
+
1876
+ f = vectorize(foo, signature='()->()', excluded={'b'})
1877
+ assert_array_equal(f([1, 2, 3]), [2, 3, 4])
1878
+ assert_array_equal(f([1, 2, 3], b=0), [1, 2, 3])
1879
+
1880
+ def test_signature_otypes(self):
1881
+ f = vectorize(lambda x: x, signature='(n)->(n)', otypes=['float64'])
1882
+ r = f([1, 2, 3])
1883
+ assert_equal(r.dtype, np.dtype('float64'))
1884
+ assert_array_equal(r, [1, 2, 3])
1885
+
1886
+ def test_signature_invalid_inputs(self):
1887
+ f = vectorize(operator.add, signature='(n),(n)->(n)')
1888
+ with assert_raises_regex(TypeError, 'wrong number of positional'):
1889
+ f([1, 2])
1890
+ with assert_raises_regex(
1891
+ ValueError, 'does not have enough dimensions'):
1892
+ f(1, 2)
1893
+ with assert_raises_regex(
1894
+ ValueError, 'inconsistent size for core dimension'):
1895
+ f([1, 2], [1, 2, 3])
1896
+
1897
+ f = vectorize(operator.add, signature='()->()')
1898
+ with assert_raises_regex(TypeError, 'wrong number of positional'):
1899
+ f(1, 2)
1900
+
1901
+ def test_signature_invalid_outputs(self):
1902
+
1903
+ f = vectorize(lambda x: x[:-1], signature='(n)->(n)')
1904
+ with assert_raises_regex(
1905
+ ValueError, 'inconsistent size for core dimension'):
1906
+ f([1, 2, 3])
1907
+
1908
+ f = vectorize(lambda x: x, signature='()->(),()')
1909
+ with assert_raises_regex(ValueError, 'wrong number of outputs'):
1910
+ f(1)
1911
+
1912
+ f = vectorize(lambda x: (x, x), signature='()->()')
1913
+ with assert_raises_regex(ValueError, 'wrong number of outputs'):
1914
+ f([1, 2])
1915
+
1916
+ def test_size_zero_output(self):
1917
+ # see issue 5868
1918
+ f = np.vectorize(lambda x: x)
1919
+ x = np.zeros([0, 5], dtype=int)
1920
+ with assert_raises_regex(ValueError, 'otypes'):
1921
+ f(x)
1922
+
1923
+ f.otypes = 'i'
1924
+ assert_array_equal(f(x), x)
1925
+
1926
+ f = np.vectorize(lambda x: x, signature='()->()')
1927
+ with assert_raises_regex(ValueError, 'otypes'):
1928
+ f(x)
1929
+
1930
+ f = np.vectorize(lambda x: x, signature='()->()', otypes='i')
1931
+ assert_array_equal(f(x), x)
1932
+
1933
+ f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i')
1934
+ assert_array_equal(f(x), x)
1935
+
1936
+ f = np.vectorize(lambda x: x, signature='(n)->(n)')
1937
+ assert_array_equal(f(x.T), x.T)
1938
+
1939
+ f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i')
1940
+ with assert_raises_regex(ValueError, 'new output dimensions'):
1941
+ f(x)
1942
+
1943
+ def test_subclasses(self):
1944
+ class subclass(np.ndarray):
1945
+ pass
1946
+
1947
+ m = np.array([[1., 0., 0.],
1948
+ [0., 0., 1.],
1949
+ [0., 1., 0.]]).view(subclass)
1950
+ v = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]).view(subclass)
1951
+ # generalized (gufunc)
1952
+ matvec = np.vectorize(np.matmul, signature='(m,m),(m)->(m)')
1953
+ r = matvec(m, v)
1954
+ assert_equal(type(r), subclass)
1955
+ assert_equal(r, [[1., 3., 2.], [4., 6., 5.], [7., 9., 8.]])
1956
+
1957
+ # element-wise (ufunc)
1958
+ mult = np.vectorize(lambda x, y: x * y)
1959
+ r = mult(m, v)
1960
+ assert_equal(type(r), subclass)
1961
+ assert_equal(r, m * v)
1962
+
1963
+ def test_name(self):
1964
+ # gh-23021
1965
+ @np.vectorize
1966
+ def f2(a, b):
1967
+ return a + b
1968
+
1969
+ assert f2.__name__ == 'f2'
1970
+
1971
+ def test_decorator(self):
1972
+ @vectorize
1973
+ def addsubtract(a, b):
1974
+ if a > b:
1975
+ return a - b
1976
+ else:
1977
+ return a + b
1978
+
1979
+ r = addsubtract([0, 3, 6, 9], [1, 3, 5, 7])
1980
+ assert_array_equal(r, [1, 6, 1, 2])
1981
+
1982
+ def test_docstring(self):
1983
+ @vectorize
1984
+ def f(x):
1985
+ """Docstring"""
1986
+ return x
1987
+
1988
+ if sys.flags.optimize < 2:
1989
+ assert f.__doc__ == "Docstring"
1990
+
1991
+ def test_partial(self):
1992
+ def foo(x, y):
1993
+ return x + y
1994
+
1995
+ bar = partial(foo, 3)
1996
+ vbar = np.vectorize(bar)
1997
+ assert vbar(1) == 4
1998
+
1999
+ def test_signature_otypes_decorator(self):
2000
+ @vectorize(signature='(n)->(n)', otypes=['float64'])
2001
+ def f(x):
2002
+ return x
2003
+
2004
+ r = f([1, 2, 3])
2005
+ assert_equal(r.dtype, np.dtype('float64'))
2006
+ assert_array_equal(r, [1, 2, 3])
2007
+ assert f.__name__ == 'f'
2008
+
2009
+ def test_bad_input(self):
2010
+ with assert_raises(TypeError):
2011
+ A = np.vectorize(pyfunc=3)
2012
+
2013
+ def test_no_keywords(self):
2014
+ with assert_raises(TypeError):
2015
+ @np.vectorize("string")
2016
+ def foo():
2017
+ return "bar"
2018
+
2019
+ def test_positional_regression_9477(self):
2020
+ # This supplies the first keyword argument as a positional,
2021
+ # to ensure that they are still properly forwarded after the
2022
+ # enhancement for #9477
2023
+ f = vectorize((lambda x: x), ['float64'])
2024
+ r = f([2])
2025
+ assert_equal(r.dtype, np.dtype('float64'))
2026
+
2027
+ def test_datetime_conversion(self):
2028
+ otype = "datetime64[ns]"
2029
+ arr = np.array(['2024-01-01', '2024-01-02', '2024-01-03'],
2030
+ dtype='datetime64[ns]')
2031
+ assert_array_equal(np.vectorize(lambda x: x, signature="(i)->(j)",
2032
+ otypes=[otype])(arr), arr)
2033
+
2034
+
2035
+ class TestLeaks:
2036
+ class A:
2037
+ iters = 20
2038
+
2039
+ def bound(self, *args):
2040
+ return 0
2041
+
2042
+ @staticmethod
2043
+ def unbound(*args):
2044
+ return 0
2045
+
2046
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2047
+ @pytest.mark.skipif(NOGIL_BUILD,
2048
+ reason=("Functions are immortalized if a thread is "
2049
+ "launched, making this test flaky"))
2050
+ @pytest.mark.parametrize('name, incr', [
2051
+ ('bound', A.iters),
2052
+ ('unbound', 0),
2053
+ ])
2054
+ def test_frompyfunc_leaks(self, name, incr):
2055
+ # exposed in gh-11867 as np.vectorized, but the problem stems from
2056
+ # frompyfunc.
2057
+ # class.attribute = np.frompyfunc(<method>) creates a
2058
+ # reference cycle if <method> is a bound class method.
2059
+ # It requires a gc collection cycle to break the cycle.
2060
+ import gc
2061
+ A_func = getattr(self.A, name)
2062
+ gc.disable()
2063
+ try:
2064
+ refcount = sys.getrefcount(A_func)
2065
+ for i in range(self.A.iters):
2066
+ a = self.A()
2067
+ a.f = np.frompyfunc(getattr(a, name), 1, 1)
2068
+ out = a.f(np.arange(10))
2069
+ a = None
2070
+ # A.func is part of a reference cycle if incr is non-zero
2071
+ assert_equal(sys.getrefcount(A_func), refcount + incr)
2072
+ for i in range(5):
2073
+ gc.collect()
2074
+ assert_equal(sys.getrefcount(A_func), refcount)
2075
+ finally:
2076
+ gc.enable()
2077
+
2078
+
2079
+ class TestDigitize:
2080
+
2081
+ def test_forward(self):
2082
+ x = np.arange(-6, 5)
2083
+ bins = np.arange(-5, 5)
2084
+ assert_array_equal(digitize(x, bins), np.arange(11))
2085
+
2086
+ def test_reverse(self):
2087
+ x = np.arange(5, -6, -1)
2088
+ bins = np.arange(5, -5, -1)
2089
+ assert_array_equal(digitize(x, bins), np.arange(11))
2090
+
2091
+ def test_random(self):
2092
+ x = rand(10)
2093
+ bin = np.linspace(x.min(), x.max(), 10)
2094
+ assert_(np.all(digitize(x, bin) != 0))
2095
+
2096
+ def test_right_basic(self):
2097
+ x = [1, 5, 4, 10, 8, 11, 0]
2098
+ bins = [1, 5, 10]
2099
+ default_answer = [1, 2, 1, 3, 2, 3, 0]
2100
+ assert_array_equal(digitize(x, bins), default_answer)
2101
+ right_answer = [0, 1, 1, 2, 2, 3, 0]
2102
+ assert_array_equal(digitize(x, bins, True), right_answer)
2103
+
2104
+ def test_right_open(self):
2105
+ x = np.arange(-6, 5)
2106
+ bins = np.arange(-6, 4)
2107
+ assert_array_equal(digitize(x, bins, True), np.arange(11))
2108
+
2109
+ def test_right_open_reverse(self):
2110
+ x = np.arange(5, -6, -1)
2111
+ bins = np.arange(4, -6, -1)
2112
+ assert_array_equal(digitize(x, bins, True), np.arange(11))
2113
+
2114
+ def test_right_open_random(self):
2115
+ x = rand(10)
2116
+ bins = np.linspace(x.min(), x.max(), 10)
2117
+ assert_(np.all(digitize(x, bins, True) != 10))
2118
+
2119
+ def test_monotonic(self):
2120
+ x = [-1, 0, 1, 2]
2121
+ bins = [0, 0, 1]
2122
+ assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3])
2123
+ assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3])
2124
+ bins = [1, 1, 0]
2125
+ assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0])
2126
+ assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0])
2127
+ bins = [1, 1, 1, 1]
2128
+ assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4])
2129
+ assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4])
2130
+ bins = [0, 0, 1, 0]
2131
+ assert_raises(ValueError, digitize, x, bins)
2132
+ bins = [1, 1, 0, 1]
2133
+ assert_raises(ValueError, digitize, x, bins)
2134
+
2135
+ def test_casting_error(self):
2136
+ x = [1, 2, 3 + 1.j]
2137
+ bins = [1, 2, 3]
2138
+ assert_raises(TypeError, digitize, x, bins)
2139
+ x, bins = bins, x
2140
+ assert_raises(TypeError, digitize, x, bins)
2141
+
2142
+ def test_return_type(self):
2143
+ # Functions returning indices should always return base ndarrays
2144
+ class A(np.ndarray):
2145
+ pass
2146
+ a = np.arange(5).view(A)
2147
+ b = np.arange(1, 3).view(A)
2148
+ assert_(not isinstance(digitize(b, a, False), A))
2149
+ assert_(not isinstance(digitize(b, a, True), A))
2150
+
2151
+ def test_large_integers_increasing(self):
2152
+ # gh-11022
2153
+ x = 2**54 # loses precision in a float
2154
+ assert_equal(np.digitize(x, [x - 1, x + 1]), 1)
2155
+
2156
+ @pytest.mark.xfail(
2157
+ reason="gh-11022: np._core.multiarray._monoticity loses precision")
2158
+ def test_large_integers_decreasing(self):
2159
+ # gh-11022
2160
+ x = 2**54 # loses precision in a float
2161
+ assert_equal(np.digitize(x, [x + 1, x - 1]), 1)
2162
+
2163
+
2164
+ class TestUnwrap:
2165
+
2166
+ def test_simple(self):
2167
+ # check that unwrap removes jumps greater that 2*pi
2168
+ assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])
2169
+ # check that unwrap maintains continuity
2170
+ assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
2171
+
2172
+ def test_period(self):
2173
+ # check that unwrap removes jumps greater that 255
2174
+ assert_array_equal(unwrap([1, 1 + 256], period=255), [1, 2])
2175
+ # check that unwrap maintains continuity
2176
+ assert_(np.all(diff(unwrap(rand(10) * 1000, period=255)) < 255))
2177
+ # check simple case
2178
+ simple_seq = np.array([0, 75, 150, 225, 300])
2179
+ wrap_seq = np.mod(simple_seq, 255)
2180
+ assert_array_equal(unwrap(wrap_seq, period=255), simple_seq)
2181
+ # check custom discont value
2182
+ uneven_seq = np.array([0, 75, 150, 225, 300, 430])
2183
+ wrap_uneven = np.mod(uneven_seq, 250)
2184
+ no_discont = unwrap(wrap_uneven, period=250)
2185
+ assert_array_equal(no_discont, [0, 75, 150, 225, 300, 180])
2186
+ sm_discont = unwrap(wrap_uneven, period=250, discont=140)
2187
+ assert_array_equal(sm_discont, [0, 75, 150, 225, 300, 430])
2188
+ assert sm_discont.dtype == wrap_uneven.dtype
2189
+
2190
+
2191
+ @pytest.mark.parametrize(
2192
+ "dtype", "O" + np.typecodes["AllInteger"] + np.typecodes["Float"]
2193
+ )
2194
+ @pytest.mark.parametrize("M", [0, 1, 10])
2195
+ class TestFilterwindows:
2196
+
2197
+ def test_hanning(self, dtype: str, M: int) -> None:
2198
+ scalar = np.array(M, dtype=dtype)[()]
2199
+
2200
+ w = hanning(scalar)
2201
+ if dtype == "O":
2202
+ ref_dtype = np.float64
2203
+ else:
2204
+ ref_dtype = np.result_type(scalar.dtype, np.float64)
2205
+ assert w.dtype == ref_dtype
2206
+
2207
+ # check symmetry
2208
+ assert_equal(w, flipud(w))
2209
+
2210
+ # check known value
2211
+ if scalar < 1:
2212
+ assert_array_equal(w, np.array([]))
2213
+ elif scalar == 1:
2214
+ assert_array_equal(w, np.ones(1))
2215
+ else:
2216
+ assert_almost_equal(np.sum(w, axis=0), 4.500, 4)
2217
+
2218
+ def test_hamming(self, dtype: str, M: int) -> None:
2219
+ scalar = np.array(M, dtype=dtype)[()]
2220
+
2221
+ w = hamming(scalar)
2222
+ if dtype == "O":
2223
+ ref_dtype = np.float64
2224
+ else:
2225
+ ref_dtype = np.result_type(scalar.dtype, np.float64)
2226
+ assert w.dtype == ref_dtype
2227
+
2228
+ # check symmetry
2229
+ assert_equal(w, flipud(w))
2230
+
2231
+ # check known value
2232
+ if scalar < 1:
2233
+ assert_array_equal(w, np.array([]))
2234
+ elif scalar == 1:
2235
+ assert_array_equal(w, np.ones(1))
2236
+ else:
2237
+ assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)
2238
+
2239
+ def test_bartlett(self, dtype: str, M: int) -> None:
2240
+ scalar = np.array(M, dtype=dtype)[()]
2241
+
2242
+ w = bartlett(scalar)
2243
+ if dtype == "O":
2244
+ ref_dtype = np.float64
2245
+ else:
2246
+ ref_dtype = np.result_type(scalar.dtype, np.float64)
2247
+ assert w.dtype == ref_dtype
2248
+
2249
+ # check symmetry
2250
+ assert_equal(w, flipud(w))
2251
+
2252
+ # check known value
2253
+ if scalar < 1:
2254
+ assert_array_equal(w, np.array([]))
2255
+ elif scalar == 1:
2256
+ assert_array_equal(w, np.ones(1))
2257
+ else:
2258
+ assert_almost_equal(np.sum(w, axis=0), 4.4444, 4)
2259
+
2260
+ def test_blackman(self, dtype: str, M: int) -> None:
2261
+ scalar = np.array(M, dtype=dtype)[()]
2262
+
2263
+ w = blackman(scalar)
2264
+ if dtype == "O":
2265
+ ref_dtype = np.float64
2266
+ else:
2267
+ ref_dtype = np.result_type(scalar.dtype, np.float64)
2268
+ assert w.dtype == ref_dtype
2269
+
2270
+ # check symmetry
2271
+ assert_equal(w, flipud(w))
2272
+
2273
+ # check known value
2274
+ if scalar < 1:
2275
+ assert_array_equal(w, np.array([]))
2276
+ elif scalar == 1:
2277
+ assert_array_equal(w, np.ones(1))
2278
+ else:
2279
+ assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
2280
+
2281
+ def test_kaiser(self, dtype: str, M: int) -> None:
2282
+ scalar = np.array(M, dtype=dtype)[()]
2283
+
2284
+ w = kaiser(scalar, 0)
2285
+ if dtype == "O":
2286
+ ref_dtype = np.float64
2287
+ else:
2288
+ ref_dtype = np.result_type(scalar.dtype, np.float64)
2289
+ assert w.dtype == ref_dtype
2290
+
2291
+ # check symmetry
2292
+ assert_equal(w, flipud(w))
2293
+
2294
+ # check known value
2295
+ if scalar < 1:
2296
+ assert_array_equal(w, np.array([]))
2297
+ elif scalar == 1:
2298
+ assert_array_equal(w, np.ones(1))
2299
+ else:
2300
+ assert_almost_equal(np.sum(w, axis=0), 10, 15)
2301
+
2302
+
2303
+ class TestTrapezoid:
2304
+
2305
+ def test_simple(self):
2306
+ x = np.arange(-10, 10, .1)
2307
+ r = trapezoid(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
2308
+ # check integral of normal equals 1
2309
+ assert_almost_equal(r, 1, 7)
2310
+
2311
+ def test_ndim(self):
2312
+ x = np.linspace(0, 1, 3)
2313
+ y = np.linspace(0, 2, 8)
2314
+ z = np.linspace(0, 3, 13)
2315
+
2316
+ wx = np.ones_like(x) * (x[1] - x[0])
2317
+ wx[0] /= 2
2318
+ wx[-1] /= 2
2319
+ wy = np.ones_like(y) * (y[1] - y[0])
2320
+ wy[0] /= 2
2321
+ wy[-1] /= 2
2322
+ wz = np.ones_like(z) * (z[1] - z[0])
2323
+ wz[0] /= 2
2324
+ wz[-1] /= 2
2325
+
2326
+ q = x[:, None, None] + y[None, :, None] + z[None, None, :]
2327
+
2328
+ qx = (q * wx[:, None, None]).sum(axis=0)
2329
+ qy = (q * wy[None, :, None]).sum(axis=1)
2330
+ qz = (q * wz[None, None, :]).sum(axis=2)
2331
+
2332
+ # n-d `x`
2333
+ r = trapezoid(q, x=x[:, None, None], axis=0)
2334
+ assert_almost_equal(r, qx)
2335
+ r = trapezoid(q, x=y[None, :, None], axis=1)
2336
+ assert_almost_equal(r, qy)
2337
+ r = trapezoid(q, x=z[None, None, :], axis=2)
2338
+ assert_almost_equal(r, qz)
2339
+
2340
+ # 1-d `x`
2341
+ r = trapezoid(q, x=x, axis=0)
2342
+ assert_almost_equal(r, qx)
2343
+ r = trapezoid(q, x=y, axis=1)
2344
+ assert_almost_equal(r, qy)
2345
+ r = trapezoid(q, x=z, axis=2)
2346
+ assert_almost_equal(r, qz)
2347
+
2348
+ def test_masked(self):
2349
+ # Testing that masked arrays behave as if the function is 0 where
2350
+ # masked
2351
+ x = np.arange(5)
2352
+ y = x * x
2353
+ mask = x == 2
2354
+ ym = np.ma.array(y, mask=mask)
2355
+ r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
2356
+ assert_almost_equal(trapezoid(ym, x), r)
2357
+
2358
+ xm = np.ma.array(x, mask=mask)
2359
+ assert_almost_equal(trapezoid(ym, xm), r)
2360
+
2361
+ xm = np.ma.array(x, mask=mask)
2362
+ assert_almost_equal(trapezoid(y, xm), r)
2363
+
2364
+
2365
+ class TestSinc:
2366
+
2367
+ def test_simple(self):
2368
+ assert_(sinc(0) == 1)
2369
+ w = sinc(np.linspace(-1, 1, 100))
2370
+ # check symmetry
2371
+ assert_array_almost_equal(w, flipud(w), 7)
2372
+
2373
+ def test_array_like(self):
2374
+ x = [0, 0.5]
2375
+ y1 = sinc(np.array(x))
2376
+ y2 = sinc(list(x))
2377
+ y3 = sinc(tuple(x))
2378
+ assert_array_equal(y1, y2)
2379
+ assert_array_equal(y1, y3)
2380
+
2381
+ def test_bool_dtype(self):
2382
+ x = (np.arange(4, dtype=np.uint8) % 2 == 1)
2383
+ actual = sinc(x)
2384
+ expected = sinc(x.astype(np.float64))
2385
+ assert_allclose(actual, expected)
2386
+ assert actual.dtype == np.float64
2387
+
2388
+ @pytest.mark.parametrize('dtype', [np.uint8, np.int16, np.uint64])
2389
+ def test_int_dtypes(self, dtype):
2390
+ x = np.arange(4, dtype=dtype)
2391
+ actual = sinc(x)
2392
+ expected = sinc(x.astype(np.float64))
2393
+ assert_allclose(actual, expected)
2394
+ assert actual.dtype == np.float64
2395
+
2396
+ @pytest.mark.parametrize(
2397
+ 'dtype',
2398
+ [np.float16, np.float32, np.longdouble, np.complex64, np.complex128]
2399
+ )
2400
+ def test_float_dtypes(self, dtype):
2401
+ x = np.arange(4, dtype=dtype)
2402
+ assert sinc(x).dtype == x.dtype
2403
+
2404
+ def test_float16_underflow(self):
2405
+ x = np.float16(0)
2406
+ # before gh-27784, fill value for 0 in input would underflow float16,
2407
+ # resulting in nan
2408
+ assert_array_equal(sinc(x), np.asarray(1.0))
2409
+
2410
+ class TestUnique:
2411
+
2412
+ def test_simple(self):
2413
+ x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
2414
+ assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))
2415
+ assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))
2416
+ x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
2417
+ assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
2418
+ x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j])
2419
+ assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))
2420
+
2421
+
2422
+ class TestCheckFinite:
2423
+
2424
+ def test_simple(self):
2425
+ a = [1, 2, 3]
2426
+ b = [1, 2, np.inf]
2427
+ c = [1, 2, np.nan]
2428
+ np.asarray_chkfinite(a)
2429
+ assert_raises(ValueError, np.asarray_chkfinite, b)
2430
+ assert_raises(ValueError, np.asarray_chkfinite, c)
2431
+
2432
+ def test_dtype_order(self):
2433
+ # Regression test for missing dtype and order arguments
2434
+ a = [1, 2, 3]
2435
+ a = np.asarray_chkfinite(a, order='F', dtype=np.float64)
2436
+ assert_(a.dtype == np.float64)
2437
+
2438
+
2439
+ class TestCorrCoef:
2440
+ A = np.array(
2441
+ [[0.15391142, 0.18045767, 0.14197213],
2442
+ [0.70461506, 0.96474128, 0.27906989],
2443
+ [0.9297531, 0.32296769, 0.19267156]])
2444
+ B = np.array(
2445
+ [[0.10377691, 0.5417086, 0.49807457],
2446
+ [0.82872117, 0.77801674, 0.39226705],
2447
+ [0.9314666, 0.66800209, 0.03538394]])
2448
+ res1 = np.array(
2449
+ [[1., 0.9379533, -0.04931983],
2450
+ [0.9379533, 1., 0.30007991],
2451
+ [-0.04931983, 0.30007991, 1.]])
2452
+ res2 = np.array(
2453
+ [[1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523],
2454
+ [0.9379533, 1., 0.30007991, -0.04781421, 0.88157256, 0.78052386],
2455
+ [-0.04931983, 0.30007991, 1., -0.96717111, 0.71483595, 0.83053601],
2456
+ [0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113],
2457
+ [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],
2458
+ [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])
2459
+
2460
+ def test_non_array(self):
2461
+ assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
2462
+ [[1., -1.], [-1., 1.]])
2463
+
2464
+ def test_simple(self):
2465
+ tgt1 = corrcoef(self.A)
2466
+ assert_almost_equal(tgt1, self.res1)
2467
+ assert_(np.all(np.abs(tgt1) <= 1.0))
2468
+
2469
+ tgt2 = corrcoef(self.A, self.B)
2470
+ assert_almost_equal(tgt2, self.res2)
2471
+ assert_(np.all(np.abs(tgt2) <= 1.0))
2472
+
2473
+ def test_ddof(self):
2474
+ # ddof raises DeprecationWarning
2475
+ with suppress_warnings() as sup:
2476
+ warnings.simplefilter("always")
2477
+ assert_warns(DeprecationWarning, corrcoef, self.A, ddof=-1)
2478
+ sup.filter(DeprecationWarning)
2479
+ # ddof has no or negligible effect on the function
2480
+ assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1)
2481
+ assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2)
2482
+ assert_almost_equal(corrcoef(self.A, ddof=3), self.res1)
2483
+ assert_almost_equal(corrcoef(self.A, self.B, ddof=3), self.res2)
2484
+
2485
+ def test_bias(self):
2486
+ # bias raises DeprecationWarning
2487
+ with suppress_warnings() as sup:
2488
+ warnings.simplefilter("always")
2489
+ assert_warns(DeprecationWarning, corrcoef, self.A, self.B, 1, 0)
2490
+ assert_warns(DeprecationWarning, corrcoef, self.A, bias=0)
2491
+ sup.filter(DeprecationWarning)
2492
+ # bias has no or negligible effect on the function
2493
+ assert_almost_equal(corrcoef(self.A, bias=1), self.res1)
2494
+
2495
+ def test_complex(self):
2496
+ x = np.array([[1, 2, 3], [1j, 2j, 3j]])
2497
+ res = corrcoef(x)
2498
+ tgt = np.array([[1., -1.j], [1.j, 1.]])
2499
+ assert_allclose(res, tgt)
2500
+ assert_(np.all(np.abs(res) <= 1.0))
2501
+
2502
+ def test_xy(self):
2503
+ x = np.array([[1, 2, 3]])
2504
+ y = np.array([[1j, 2j, 3j]])
2505
+ assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))
2506
+
2507
+ def test_empty(self):
2508
+ with warnings.catch_warnings(record=True):
2509
+ warnings.simplefilter('always', RuntimeWarning)
2510
+ assert_array_equal(corrcoef(np.array([])), np.nan)
2511
+ assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),
2512
+ np.array([]).reshape(0, 0))
2513
+ assert_array_equal(corrcoef(np.array([]).reshape(2, 0)),
2514
+ np.array([[np.nan, np.nan], [np.nan, np.nan]]))
2515
+
2516
+ def test_extreme(self):
2517
+ x = [[1e-100, 1e100], [1e100, 1e-100]]
2518
+ with np.errstate(all='raise'):
2519
+ c = corrcoef(x)
2520
+ assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))
2521
+ assert_(np.all(np.abs(c) <= 1.0))
2522
+
2523
+ @pytest.mark.parametrize("test_type", [np.half, np.single, np.double, np.longdouble])
2524
+ def test_corrcoef_dtype(self, test_type):
2525
+ cast_A = self.A.astype(test_type)
2526
+ res = corrcoef(cast_A, dtype=test_type)
2527
+ assert test_type == res.dtype
2528
+
2529
+
2530
+ class TestCov:
2531
+ x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
2532
+ res1 = np.array([[1., -1.], [-1., 1.]])
2533
+ x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
2534
+ frequencies = np.array([1, 4, 1])
2535
+ x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T
2536
+ res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])
2537
+ unit_frequencies = np.ones(3, dtype=np.int_)
2538
+ weights = np.array([1.0, 4.0, 1.0])
2539
+ res3 = np.array([[2. / 3., -2. / 3.], [-2. / 3., 2. / 3.]])
2540
+ unit_weights = np.ones(3)
2541
+ x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])
2542
+
2543
+ def test_basic(self):
2544
+ assert_allclose(cov(self.x1), self.res1)
2545
+
2546
+ def test_complex(self):
2547
+ x = np.array([[1, 2, 3], [1j, 2j, 3j]])
2548
+ res = np.array([[1., -1.j], [1.j, 1.]])
2549
+ assert_allclose(cov(x), res)
2550
+ assert_allclose(cov(x, aweights=np.ones(3)), res)
2551
+
2552
+ def test_xy(self):
2553
+ x = np.array([[1, 2, 3]])
2554
+ y = np.array([[1j, 2j, 3j]])
2555
+ assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))
2556
+
2557
+ def test_empty(self):
2558
+ with warnings.catch_warnings(record=True):
2559
+ warnings.simplefilter('always', RuntimeWarning)
2560
+ assert_array_equal(cov(np.array([])), np.nan)
2561
+ assert_array_equal(cov(np.array([]).reshape(0, 2)),
2562
+ np.array([]).reshape(0, 0))
2563
+ assert_array_equal(cov(np.array([]).reshape(2, 0)),
2564
+ np.array([[np.nan, np.nan], [np.nan, np.nan]]))
2565
+
2566
+ def test_wrong_ddof(self):
2567
+ with warnings.catch_warnings(record=True):
2568
+ warnings.simplefilter('always', RuntimeWarning)
2569
+ assert_array_equal(cov(self.x1, ddof=5),
2570
+ np.array([[np.inf, -np.inf],
2571
+ [-np.inf, np.inf]]))
2572
+
2573
+ def test_1D_rowvar(self):
2574
+ assert_allclose(cov(self.x3), cov(self.x3, rowvar=False))
2575
+ y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501])
2576
+ assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=False))
2577
+
2578
+ def test_1D_variance(self):
2579
+ assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1))
2580
+
2581
+ def test_fweights(self):
2582
+ assert_allclose(cov(self.x2, fweights=self.frequencies),
2583
+ cov(self.x2_repeats))
2584
+ assert_allclose(cov(self.x1, fweights=self.frequencies),
2585
+ self.res2)
2586
+ assert_allclose(cov(self.x1, fweights=self.unit_frequencies),
2587
+ self.res1)
2588
+ nonint = self.frequencies + 0.5
2589
+ assert_raises(TypeError, cov, self.x1, fweights=nonint)
2590
+ f = np.ones((2, 3), dtype=np.int_)
2591
+ assert_raises(RuntimeError, cov, self.x1, fweights=f)
2592
+ f = np.ones(2, dtype=np.int_)
2593
+ assert_raises(RuntimeError, cov, self.x1, fweights=f)
2594
+ f = -1 * np.ones(3, dtype=np.int_)
2595
+ assert_raises(ValueError, cov, self.x1, fweights=f)
2596
+
2597
+ def test_aweights(self):
2598
+ assert_allclose(cov(self.x1, aweights=self.weights), self.res3)
2599
+ assert_allclose(cov(self.x1, aweights=3.0 * self.weights),
2600
+ cov(self.x1, aweights=self.weights))
2601
+ assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1)
2602
+ w = np.ones((2, 3))
2603
+ assert_raises(RuntimeError, cov, self.x1, aweights=w)
2604
+ w = np.ones(2)
2605
+ assert_raises(RuntimeError, cov, self.x1, aweights=w)
2606
+ w = -1.0 * np.ones(3)
2607
+ assert_raises(ValueError, cov, self.x1, aweights=w)
2608
+
2609
+ def test_unit_fweights_and_aweights(self):
2610
+ assert_allclose(cov(self.x2, fweights=self.frequencies,
2611
+ aweights=self.unit_weights),
2612
+ cov(self.x2_repeats))
2613
+ assert_allclose(cov(self.x1, fweights=self.frequencies,
2614
+ aweights=self.unit_weights),
2615
+ self.res2)
2616
+ assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
2617
+ aweights=self.unit_weights),
2618
+ self.res1)
2619
+ assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
2620
+ aweights=self.weights),
2621
+ self.res3)
2622
+ assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
2623
+ aweights=3.0 * self.weights),
2624
+ cov(self.x1, aweights=self.weights))
2625
+ assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
2626
+ aweights=self.unit_weights),
2627
+ self.res1)
2628
+
2629
+ @pytest.mark.parametrize("test_type", [np.half, np.single, np.double, np.longdouble])
2630
+ def test_cov_dtype(self, test_type):
2631
+ cast_x1 = self.x1.astype(test_type)
2632
+ res = cov(cast_x1, dtype=test_type)
2633
+ assert test_type == res.dtype
2634
+
2635
+ def test_gh_27658(self):
2636
+ x = np.ones((3, 1))
2637
+ expected = np.cov(x, ddof=0, rowvar=True)
2638
+ actual = np.cov(x.T, ddof=0, rowvar=False)
2639
+ assert_allclose(actual, expected, strict=True)
2640
+
2641
+
2642
+ class Test_I0:
2643
+
2644
+ def test_simple(self):
2645
+ assert_almost_equal(
2646
+ i0(0.5),
2647
+ np.array(1.0634833707413234))
2648
+
2649
+ # need at least one test above 8, as the implementation is piecewise
2650
+ A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0])
2651
+ expected = np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049, 2815.71662847])
2652
+ assert_almost_equal(i0(A), expected)
2653
+ assert_almost_equal(i0(-A), expected)
2654
+
2655
+ B = np.array([[0.827002, 0.99959078],
2656
+ [0.89694769, 0.39298162],
2657
+ [0.37954418, 0.05206293],
2658
+ [0.36465447, 0.72446427],
2659
+ [0.48164949, 0.50324519]])
2660
+ assert_almost_equal(
2661
+ i0(B),
2662
+ np.array([[1.17843223, 1.26583466],
2663
+ [1.21147086, 1.03898290],
2664
+ [1.03633899, 1.00067775],
2665
+ [1.03352052, 1.13557954],
2666
+ [1.05884290, 1.06432317]]))
2667
+ # Regression test for gh-11205
2668
+ i0_0 = np.i0([0.])
2669
+ assert_equal(i0_0.shape, (1,))
2670
+ assert_array_equal(np.i0([0.]), np.array([1.]))
2671
+
2672
+ def test_non_array(self):
2673
+ a = np.arange(4)
2674
+
2675
+ class array_like:
2676
+ __array_interface__ = a.__array_interface__
2677
+
2678
+ def __array_wrap__(self, arr, context, return_scalar):
2679
+ return self
2680
+
2681
+ # E.g. pandas series survive ufunc calls through array-wrap:
2682
+ assert isinstance(np.abs(array_like()), array_like)
2683
+ exp = np.i0(a)
2684
+ res = np.i0(array_like())
2685
+
2686
+ assert_array_equal(exp, res)
2687
+
2688
+ def test_complex(self):
2689
+ a = np.array([0, 1 + 2j])
2690
+ with pytest.raises(TypeError, match="i0 not supported for complex values"):
2691
+ res = i0(a)
2692
+
2693
+
2694
+ class TestKaiser:
2695
+
2696
+ def test_simple(self):
2697
+ assert_(np.isfinite(kaiser(1, 1.0)))
2698
+ assert_almost_equal(kaiser(0, 1.0),
2699
+ np.array([]))
2700
+ assert_almost_equal(kaiser(2, 1.0),
2701
+ np.array([0.78984831, 0.78984831]))
2702
+ assert_almost_equal(kaiser(5, 1.0),
2703
+ np.array([0.78984831, 0.94503323, 1.,
2704
+ 0.94503323, 0.78984831]))
2705
+ assert_almost_equal(kaiser(5, 1.56789),
2706
+ np.array([0.58285404, 0.88409679, 1.,
2707
+ 0.88409679, 0.58285404]))
2708
+
2709
+ def test_int_beta(self):
2710
+ kaiser(3, 4)
2711
+
2712
+
2713
+ class TestMeshgrid:
2714
+
2715
+ def test_simple(self):
2716
+ [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
2717
+ assert_array_equal(X, np.array([[1, 2, 3],
2718
+ [1, 2, 3],
2719
+ [1, 2, 3],
2720
+ [1, 2, 3]]))
2721
+ assert_array_equal(Y, np.array([[4, 4, 4],
2722
+ [5, 5, 5],
2723
+ [6, 6, 6],
2724
+ [7, 7, 7]]))
2725
+
2726
+ def test_single_input(self):
2727
+ [X] = meshgrid([1, 2, 3, 4])
2728
+ assert_array_equal(X, np.array([1, 2, 3, 4]))
2729
+
2730
+ def test_no_input(self):
2731
+ args = []
2732
+ assert_array_equal([], meshgrid(*args))
2733
+ assert_array_equal([], meshgrid(*args, copy=False))
2734
+
2735
+ def test_indexing(self):
2736
+ x = [1, 2, 3]
2737
+ y = [4, 5, 6, 7]
2738
+ [X, Y] = meshgrid(x, y, indexing='ij')
2739
+ assert_array_equal(X, np.array([[1, 1, 1, 1],
2740
+ [2, 2, 2, 2],
2741
+ [3, 3, 3, 3]]))
2742
+ assert_array_equal(Y, np.array([[4, 5, 6, 7],
2743
+ [4, 5, 6, 7],
2744
+ [4, 5, 6, 7]]))
2745
+
2746
+ # Test expected shapes:
2747
+ z = [8, 9]
2748
+ assert_(meshgrid(x, y)[0].shape == (4, 3))
2749
+ assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
2750
+ assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
2751
+ assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))
2752
+
2753
+ assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
2754
+
2755
+ def test_sparse(self):
2756
+ [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
2757
+ assert_array_equal(X, np.array([[1, 2, 3]]))
2758
+ assert_array_equal(Y, np.array([[4], [5], [6], [7]]))
2759
+
2760
+ def test_invalid_arguments(self):
2761
+ # Test that meshgrid complains about invalid arguments
2762
+ # Regression test for issue #4755:
2763
+ # https://github.com/numpy/numpy/issues/4755
2764
+ assert_raises(TypeError, meshgrid,
2765
+ [1, 2, 3], [4, 5, 6, 7], indices='ij')
2766
+
2767
+ def test_return_type(self):
2768
+ # Test for appropriate dtype in returned arrays.
2769
+ # Regression test for issue #5297
2770
+ # https://github.com/numpy/numpy/issues/5297
2771
+ x = np.arange(0, 10, dtype=np.float32)
2772
+ y = np.arange(10, 20, dtype=np.float64)
2773
+
2774
+ X, Y = np.meshgrid(x, y)
2775
+
2776
+ assert_(X.dtype == x.dtype)
2777
+ assert_(Y.dtype == y.dtype)
2778
+
2779
+ # copy
2780
+ X, Y = np.meshgrid(x, y, copy=True)
2781
+
2782
+ assert_(X.dtype == x.dtype)
2783
+ assert_(Y.dtype == y.dtype)
2784
+
2785
+ # sparse
2786
+ X, Y = np.meshgrid(x, y, sparse=True)
2787
+
2788
+ assert_(X.dtype == x.dtype)
2789
+ assert_(Y.dtype == y.dtype)
2790
+
2791
+ def test_writeback(self):
2792
+ # Issue 8561
2793
+ X = np.array([1.1, 2.2])
2794
+ Y = np.array([3.3, 4.4])
2795
+ x, y = np.meshgrid(X, Y, sparse=False, copy=True)
2796
+
2797
+ x[0, :] = 0
2798
+ assert_equal(x[0, :], 0)
2799
+ assert_equal(x[1, :], X)
2800
+
2801
+ def test_nd_shape(self):
2802
+ a, b, c, d, e = np.meshgrid(*([0] * i for i in range(1, 6)))
2803
+ expected_shape = (2, 1, 3, 4, 5)
2804
+ assert_equal(a.shape, expected_shape)
2805
+ assert_equal(b.shape, expected_shape)
2806
+ assert_equal(c.shape, expected_shape)
2807
+ assert_equal(d.shape, expected_shape)
2808
+ assert_equal(e.shape, expected_shape)
2809
+
2810
+ def test_nd_values(self):
2811
+ a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5])
2812
+ assert_equal(a, [[[0, 0, 0]], [[0, 0, 0]]])
2813
+ assert_equal(b, [[[1, 1, 1]], [[2, 2, 2]]])
2814
+ assert_equal(c, [[[3, 4, 5]], [[3, 4, 5]]])
2815
+
2816
+ def test_nd_indexing(self):
2817
+ a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5], indexing='ij')
2818
+ assert_equal(a, [[[0, 0, 0], [0, 0, 0]]])
2819
+ assert_equal(b, [[[1, 1, 1], [2, 2, 2]]])
2820
+ assert_equal(c, [[[3, 4, 5], [3, 4, 5]]])
2821
+
2822
+
2823
+ class TestPiecewise:
2824
+
2825
+ def test_simple(self):
2826
+ # Condition is single bool list
2827
+ x = piecewise([0, 0], [True, False], [1])
2828
+ assert_array_equal(x, [1, 0])
2829
+
2830
+ # List of conditions: single bool list
2831
+ x = piecewise([0, 0], [[True, False]], [1])
2832
+ assert_array_equal(x, [1, 0])
2833
+
2834
+ # Conditions is single bool array
2835
+ x = piecewise([0, 0], np.array([True, False]), [1])
2836
+ assert_array_equal(x, [1, 0])
2837
+
2838
+ # Condition is single int array
2839
+ x = piecewise([0, 0], np.array([1, 0]), [1])
2840
+ assert_array_equal(x, [1, 0])
2841
+
2842
+ # List of conditions: int array
2843
+ x = piecewise([0, 0], [np.array([1, 0])], [1])
2844
+ assert_array_equal(x, [1, 0])
2845
+
2846
+ x = piecewise([0, 0], [[False, True]], [lambda x:-1])
2847
+ assert_array_equal(x, [0, -1])
2848
+
2849
+ assert_raises_regex(ValueError, '1 or 2 functions are expected',
2850
+ piecewise, [0, 0], [[False, True]], [])
2851
+ assert_raises_regex(ValueError, '1 or 2 functions are expected',
2852
+ piecewise, [0, 0], [[False, True]], [1, 2, 3])
2853
+
2854
+ def test_two_conditions(self):
2855
+ x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
2856
+ assert_array_equal(x, [3, 4])
2857
+
2858
+ def test_scalar_domains_three_conditions(self):
2859
+ x = piecewise(3, [True, False, False], [4, 2, 0])
2860
+ assert_equal(x, 4)
2861
+
2862
+ def test_default(self):
2863
+ # No value specified for x[1], should be 0
2864
+ x = piecewise([1, 2], [True, False], [2])
2865
+ assert_array_equal(x, [2, 0])
2866
+
2867
+ # Should set x[1] to 3
2868
+ x = piecewise([1, 2], [True, False], [2, 3])
2869
+ assert_array_equal(x, [2, 3])
2870
+
2871
+ def test_0d(self):
2872
+ x = np.array(3)
2873
+ y = piecewise(x, x > 3, [4, 0])
2874
+ assert_(y.ndim == 0)
2875
+ assert_(y == 0)
2876
+
2877
+ x = 5
2878
+ y = piecewise(x, [True, False], [1, 0])
2879
+ assert_(y.ndim == 0)
2880
+ assert_(y == 1)
2881
+
2882
+ # With 3 ranges (It was failing, before)
2883
+ y = piecewise(x, [False, False, True], [1, 2, 3])
2884
+ assert_array_equal(y, 3)
2885
+
2886
+ def test_0d_comparison(self):
2887
+ x = 3
2888
+ y = piecewise(x, [x <= 3, x > 3], [4, 0]) # Should succeed.
2889
+ assert_equal(y, 4)
2890
+
2891
+ # With 3 ranges (It was failing, before)
2892
+ x = 4
2893
+ y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3])
2894
+ assert_array_equal(y, 2)
2895
+
2896
+ assert_raises_regex(ValueError, '2 or 3 functions are expected',
2897
+ piecewise, x, [x <= 3, x > 3], [1])
2898
+ assert_raises_regex(ValueError, '2 or 3 functions are expected',
2899
+ piecewise, x, [x <= 3, x > 3], [1, 1, 1, 1])
2900
+
2901
+ def test_0d_0d_condition(self):
2902
+ x = np.array(3)
2903
+ c = np.array(x > 3)
2904
+ y = piecewise(x, [c], [1, 2])
2905
+ assert_equal(y, 2)
2906
+
2907
+ def test_multidimensional_extrafunc(self):
2908
+ x = np.array([[-2.5, -1.5, -0.5],
2909
+ [0.5, 1.5, 2.5]])
2910
+ y = piecewise(x, [x < 0, x >= 2], [-1, 1, 3])
2911
+ assert_array_equal(y, np.array([[-1., -1., -1.],
2912
+ [3., 3., 1.]]))
2913
+
2914
+ def test_subclasses(self):
2915
+ class subclass(np.ndarray):
2916
+ pass
2917
+ x = np.arange(5.).view(subclass)
2918
+ r = piecewise(x, [x < 2., x >= 4], [-1., 1., 0.])
2919
+ assert_equal(type(r), subclass)
2920
+ assert_equal(r, [-1., -1., 0., 0., 1.])
2921
+
2922
+
2923
+ class TestBincount:
2924
+
2925
+ def test_simple(self):
2926
+ y = np.bincount(np.arange(4))
2927
+ assert_array_equal(y, np.ones(4))
2928
+
2929
+ def test_simple2(self):
2930
+ y = np.bincount(np.array([1, 5, 2, 4, 1]))
2931
+ assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1]))
2932
+
2933
+ def test_simple_weight(self):
2934
+ x = np.arange(4)
2935
+ w = np.array([0.2, 0.3, 0.5, 0.1])
2936
+ y = np.bincount(x, w)
2937
+ assert_array_equal(y, w)
2938
+
2939
+ def test_simple_weight2(self):
2940
+ x = np.array([1, 2, 4, 5, 2])
2941
+ w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
2942
+ y = np.bincount(x, w)
2943
+ assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1]))
2944
+
2945
+ def test_with_minlength(self):
2946
+ x = np.array([0, 1, 0, 1, 1])
2947
+ y = np.bincount(x, minlength=3)
2948
+ assert_array_equal(y, np.array([2, 3, 0]))
2949
+ x = []
2950
+ y = np.bincount(x, minlength=0)
2951
+ assert_array_equal(y, np.array([]))
2952
+
2953
+ def test_with_minlength_smaller_than_maxvalue(self):
2954
+ x = np.array([0, 1, 1, 2, 2, 3, 3])
2955
+ y = np.bincount(x, minlength=2)
2956
+ assert_array_equal(y, np.array([1, 2, 2, 2]))
2957
+ y = np.bincount(x, minlength=0)
2958
+ assert_array_equal(y, np.array([1, 2, 2, 2]))
2959
+
2960
+ def test_with_minlength_and_weights(self):
2961
+ x = np.array([1, 2, 4, 5, 2])
2962
+ w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
2963
+ y = np.bincount(x, w, 8)
2964
+ assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0]))
2965
+
2966
+ def test_empty(self):
2967
+ x = np.array([], dtype=int)
2968
+ y = np.bincount(x)
2969
+ assert_array_equal(x, y)
2970
+
2971
+ def test_empty_with_minlength(self):
2972
+ x = np.array([], dtype=int)
2973
+ y = np.bincount(x, minlength=5)
2974
+ assert_array_equal(y, np.zeros(5, dtype=int))
2975
+
2976
+ @pytest.mark.parametrize('minlength', [0, 3])
2977
+ def test_empty_list(self, minlength):
2978
+ assert_array_equal(np.bincount([], minlength=minlength),
2979
+ np.zeros(minlength, dtype=int))
2980
+
2981
+ def test_with_incorrect_minlength(self):
2982
+ x = np.array([], dtype=int)
2983
+ assert_raises_regex(TypeError,
2984
+ "'str' object cannot be interpreted",
2985
+ lambda: np.bincount(x, minlength="foobar"))
2986
+ assert_raises_regex(ValueError,
2987
+ "must not be negative",
2988
+ lambda: np.bincount(x, minlength=-1))
2989
+
2990
+ x = np.arange(5)
2991
+ assert_raises_regex(TypeError,
2992
+ "'str' object cannot be interpreted",
2993
+ lambda: np.bincount(x, minlength="foobar"))
2994
+ assert_raises_regex(ValueError,
2995
+ "must not be negative",
2996
+ lambda: np.bincount(x, minlength=-1))
2997
+
2998
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2999
+ def test_dtype_reference_leaks(self):
3000
+ # gh-6805
3001
+ intp_refcount = sys.getrefcount(np.dtype(np.intp))
3002
+ double_refcount = sys.getrefcount(np.dtype(np.double))
3003
+
3004
+ for j in range(10):
3005
+ np.bincount([1, 2, 3])
3006
+ assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
3007
+ assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
3008
+
3009
+ for j in range(10):
3010
+ np.bincount([1, 2, 3], [4, 5, 6])
3011
+ assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
3012
+ assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
3013
+
3014
+ @pytest.mark.parametrize("vals", [[[2, 2]], 2])
3015
+ def test_error_not_1d(self, vals):
3016
+ # Test that values has to be 1-D (both as array and nested list)
3017
+ vals_arr = np.asarray(vals)
3018
+ with assert_raises(ValueError):
3019
+ np.bincount(vals_arr)
3020
+ with assert_raises(ValueError):
3021
+ np.bincount(vals)
3022
+
3023
+ @pytest.mark.parametrize("dt", np.typecodes["AllInteger"])
3024
+ def test_gh_28354(self, dt):
3025
+ a = np.array([0, 1, 1, 3, 2, 1, 7], dtype=dt)
3026
+ actual = np.bincount(a)
3027
+ expected = [1, 3, 1, 1, 0, 0, 0, 1]
3028
+ assert_array_equal(actual, expected)
3029
+
3030
+ def test_contiguous_handling(self):
3031
+ # check for absence of hard crash
3032
+ np.bincount(np.arange(10000)[::2])
3033
+
3034
+ def test_gh_28354_array_like(self):
3035
+ class A:
3036
+ def __array__(self):
3037
+ return np.array([0, 1, 1, 3, 2, 1, 7], dtype=np.uint64)
3038
+
3039
+ a = A()
3040
+ actual = np.bincount(a)
3041
+ expected = [1, 3, 1, 1, 0, 0, 0, 1]
3042
+ assert_array_equal(actual, expected)
3043
+
3044
+
3045
+ class TestInterp:
3046
+
3047
+ def test_exceptions(self):
3048
+ assert_raises(ValueError, interp, 0, [], [])
3049
+ assert_raises(ValueError, interp, 0, [0], [1, 2])
3050
+ assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)
3051
+ assert_raises(ValueError, interp, 0, [], [], period=360)
3052
+ assert_raises(ValueError, interp, 0, [0], [1, 2], period=360)
3053
+
3054
+ def test_basic(self):
3055
+ x = np.linspace(0, 1, 5)
3056
+ y = np.linspace(0, 1, 5)
3057
+ x0 = np.linspace(0, 1, 50)
3058
+ assert_almost_equal(np.interp(x0, x, y), x0)
3059
+
3060
+ def test_right_left_behavior(self):
3061
+ # Needs range of sizes to test different code paths.
3062
+ # size ==1 is special cased, 1 < size < 5 is linear search, and
3063
+ # size >= 5 goes through local search and possibly binary search.
3064
+ for size in range(1, 10):
3065
+ xp = np.arange(size, dtype=np.double)
3066
+ yp = np.ones(size, dtype=np.double)
3067
+ incpts = np.array([-1, 0, size - 1, size], dtype=np.double)
3068
+ decpts = incpts[::-1]
3069
+
3070
+ incres = interp(incpts, xp, yp)
3071
+ decres = interp(decpts, xp, yp)
3072
+ inctgt = np.array([1, 1, 1, 1], dtype=float)
3073
+ dectgt = inctgt[::-1]
3074
+ assert_equal(incres, inctgt)
3075
+ assert_equal(decres, dectgt)
3076
+
3077
+ incres = interp(incpts, xp, yp, left=0)
3078
+ decres = interp(decpts, xp, yp, left=0)
3079
+ inctgt = np.array([0, 1, 1, 1], dtype=float)
3080
+ dectgt = inctgt[::-1]
3081
+ assert_equal(incres, inctgt)
3082
+ assert_equal(decres, dectgt)
3083
+
3084
+ incres = interp(incpts, xp, yp, right=2)
3085
+ decres = interp(decpts, xp, yp, right=2)
3086
+ inctgt = np.array([1, 1, 1, 2], dtype=float)
3087
+ dectgt = inctgt[::-1]
3088
+ assert_equal(incres, inctgt)
3089
+ assert_equal(decres, dectgt)
3090
+
3091
+ incres = interp(incpts, xp, yp, left=0, right=2)
3092
+ decres = interp(decpts, xp, yp, left=0, right=2)
3093
+ inctgt = np.array([0, 1, 1, 2], dtype=float)
3094
+ dectgt = inctgt[::-1]
3095
+ assert_equal(incres, inctgt)
3096
+ assert_equal(decres, dectgt)
3097
+
3098
+ def test_scalar_interpolation_point(self):
3099
+ x = np.linspace(0, 1, 5)
3100
+ y = np.linspace(0, 1, 5)
3101
+ x0 = 0
3102
+ assert_almost_equal(np.interp(x0, x, y), x0)
3103
+ x0 = .3
3104
+ assert_almost_equal(np.interp(x0, x, y), x0)
3105
+ x0 = np.float32(.3)
3106
+ assert_almost_equal(np.interp(x0, x, y), x0)
3107
+ x0 = np.float64(.3)
3108
+ assert_almost_equal(np.interp(x0, x, y), x0)
3109
+ x0 = np.nan
3110
+ assert_almost_equal(np.interp(x0, x, y), x0)
3111
+
3112
+ def test_non_finite_behavior_exact_x(self):
3113
+ x = [1, 2, 2.5, 3, 4]
3114
+ xp = [1, 2, 3, 4]
3115
+ fp = [1, 2, np.inf, 4]
3116
+ assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.inf, np.inf, 4])
3117
+ fp = [1, 2, np.nan, 4]
3118
+ assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])
3119
+
3120
+ @pytest.fixture(params=[
3121
+ np.float64,
3122
+ lambda x: _make_complex(x, 0),
3123
+ lambda x: _make_complex(0, x),
3124
+ lambda x: _make_complex(x, np.multiply(x, -2))
3125
+ ], ids=[
3126
+ 'real',
3127
+ 'complex-real',
3128
+ 'complex-imag',
3129
+ 'complex-both'
3130
+ ])
3131
+ def sc(self, request):
3132
+ """ scale function used by the below tests """
3133
+ return request.param
3134
+
3135
+ def test_non_finite_any_nan(self, sc):
3136
+ """ test that nans are propagated """
3137
+ assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan))
3138
+ assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan))
3139
+ assert_equal(np.interp(0.5, [ 0, 1], sc([np.nan, 10])), sc(np.nan))
3140
+ assert_equal(np.interp(0.5, [ 0, 1], sc([ 0, np.nan])), sc(np.nan))
3141
+
3142
+ def test_non_finite_inf(self, sc):
3143
+ """ Test that interp between opposite infs gives nan """
3144
+ assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 0, 10])), sc(np.nan))
3145
+ assert_equal(np.interp(0.5, [ 0, 1], sc([-np.inf, +np.inf])), sc(np.nan))
3146
+ assert_equal(np.interp(0.5, [ 0, 1], sc([+np.inf, -np.inf])), sc(np.nan))
3147
+
3148
+ # unless the y values are equal
3149
+ assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 10, 10])), sc(10))
3150
+
3151
+ def test_non_finite_half_inf_xf(self, sc):
3152
+ """ Test that interp where both axes have a bound at inf gives nan """
3153
+ assert_equal(np.interp(0.5, [-np.inf, 1], sc([-np.inf, 10])), sc(np.nan))
3154
+ assert_equal(np.interp(0.5, [-np.inf, 1], sc([+np.inf, 10])), sc(np.nan))
3155
+ assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, -np.inf])), sc(np.nan))
3156
+ assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, +np.inf])), sc(np.nan))
3157
+ assert_equal(np.interp(0.5, [ 0, +np.inf], sc([-np.inf, 10])), sc(np.nan))
3158
+ assert_equal(np.interp(0.5, [ 0, +np.inf], sc([+np.inf, 10])), sc(np.nan))
3159
+ assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, -np.inf])), sc(np.nan))
3160
+ assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, +np.inf])), sc(np.nan))
3161
+
3162
+ def test_non_finite_half_inf_x(self, sc):
3163
+ """ Test interp where the x axis has a bound at inf """
3164
+ assert_equal(np.interp(0.5, [-np.inf, -np.inf], sc([0, 10])), sc(10))
3165
+ assert_equal(np.interp(0.5, [-np.inf, 1 ], sc([0, 10])), sc(10)) # noqa: E202
3166
+ assert_equal(np.interp(0.5, [ 0, +np.inf], sc([0, 10])), sc(0))
3167
+ assert_equal(np.interp(0.5, [+np.inf, +np.inf], sc([0, 10])), sc(0))
3168
+
3169
+ def test_non_finite_half_inf_f(self, sc):
3170
+ """ Test interp where the f axis has a bound at inf """
3171
+ assert_equal(np.interp(0.5, [0, 1], sc([ 0, -np.inf])), sc(-np.inf))
3172
+ assert_equal(np.interp(0.5, [0, 1], sc([ 0, +np.inf])), sc(+np.inf))
3173
+ assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, 10])), sc(-np.inf))
3174
+ assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, 10])), sc(+np.inf))
3175
+ assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, -np.inf])), sc(-np.inf))
3176
+ assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, +np.inf])), sc(+np.inf))
3177
+
3178
+ def test_complex_interp(self):
3179
+ # test complex interpolation
3180
+ x = np.linspace(0, 1, 5)
3181
+ y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5)) * 1.0j
3182
+ x0 = 0.3
3183
+ y0 = x0 + (1 + x0) * 1.0j
3184
+ assert_almost_equal(np.interp(x0, x, y), y0)
3185
+ # test complex left and right
3186
+ x0 = -1
3187
+ left = 2 + 3.0j
3188
+ assert_almost_equal(np.interp(x0, x, y, left=left), left)
3189
+ x0 = 2.0
3190
+ right = 2 + 3.0j
3191
+ assert_almost_equal(np.interp(x0, x, y, right=right), right)
3192
+ # test complex non finite
3193
+ x = [1, 2, 2.5, 3, 4]
3194
+ xp = [1, 2, 3, 4]
3195
+ fp = [1, 2 + 1j, np.inf, 4]
3196
+ y = [1, 2 + 1j, np.inf + 0.5j, np.inf, 4]
3197
+ assert_almost_equal(np.interp(x, xp, fp), y)
3198
+ # test complex periodic
3199
+ x = [-180, -170, -185, 185, -10, -5, 0, 365]
3200
+ xp = [190, -190, 350, -350]
3201
+ fp = [5 + 1.0j, 10 + 2j, 3 + 3j, 4 + 4j]
3202
+ y = [7.5 + 1.5j, 5. + 1.0j, 8.75 + 1.75j, 6.25 + 1.25j, 3. + 3j, 3.25 + 3.25j,
3203
+ 3.5 + 3.5j, 3.75 + 3.75j]
3204
+ assert_almost_equal(np.interp(x, xp, fp, period=360), y)
3205
+
3206
+ def test_zero_dimensional_interpolation_point(self):
3207
+ x = np.linspace(0, 1, 5)
3208
+ y = np.linspace(0, 1, 5)
3209
+ x0 = np.array(.3)
3210
+ assert_almost_equal(np.interp(x0, x, y), x0)
3211
+
3212
+ xp = np.array([0, 2, 4])
3213
+ fp = np.array([1, -1, 1])
3214
+
3215
+ actual = np.interp(np.array(1), xp, fp)
3216
+ assert_equal(actual, 0)
3217
+ assert_(isinstance(actual, np.float64))
3218
+
3219
+ actual = np.interp(np.array(4.5), xp, fp, period=4)
3220
+ assert_equal(actual, 0.5)
3221
+ assert_(isinstance(actual, np.float64))
3222
+
3223
+ def test_if_len_x_is_small(self):
3224
+ xp = np.arange(0, 10, 0.0001)
3225
+ fp = np.sin(xp)
3226
+ assert_almost_equal(np.interp(np.pi, xp, fp), 0.0)
3227
+
3228
+ def test_period(self):
3229
+ x = [-180, -170, -185, 185, -10, -5, 0, 365]
3230
+ xp = [190, -190, 350, -350]
3231
+ fp = [5, 10, 3, 4]
3232
+ y = [7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]
3233
+ assert_almost_equal(np.interp(x, xp, fp, period=360), y)
3234
+ x = np.array(x, order='F').reshape(2, -1)
3235
+ y = np.array(y, order='C').reshape(2, -1)
3236
+ assert_almost_equal(np.interp(x, xp, fp, period=360), y)
3237
+
3238
+
3239
+ class TestPercentile:
3240
+
3241
+ def test_basic(self):
3242
+ x = np.arange(8) * 0.5
3243
+ assert_equal(np.percentile(x, 0), 0.)
3244
+ assert_equal(np.percentile(x, 100), 3.5)
3245
+ assert_equal(np.percentile(x, 50), 1.75)
3246
+ x[1] = np.nan
3247
+ assert_equal(np.percentile(x, 0), np.nan)
3248
+ assert_equal(np.percentile(x, 0, method='nearest'), np.nan)
3249
+ assert_equal(np.percentile(x, 0, method='inverted_cdf'), np.nan)
3250
+ assert_equal(
3251
+ np.percentile(x, 0, method='inverted_cdf',
3252
+ weights=np.ones_like(x)),
3253
+ np.nan,
3254
+ )
3255
+
3256
+ def test_fraction(self):
3257
+ x = [Fraction(i, 2) for i in range(8)]
3258
+
3259
+ p = np.percentile(x, Fraction(0))
3260
+ assert_equal(p, Fraction(0))
3261
+ assert_equal(type(p), Fraction)
3262
+
3263
+ p = np.percentile(x, Fraction(100))
3264
+ assert_equal(p, Fraction(7, 2))
3265
+ assert_equal(type(p), Fraction)
3266
+
3267
+ p = np.percentile(x, Fraction(50))
3268
+ assert_equal(p, Fraction(7, 4))
3269
+ assert_equal(type(p), Fraction)
3270
+
3271
+ p = np.percentile(x, [Fraction(50)])
3272
+ assert_equal(p, np.array([Fraction(7, 4)]))
3273
+ assert_equal(type(p), np.ndarray)
3274
+
3275
+ def test_api(self):
3276
+ d = np.ones(5)
3277
+ np.percentile(d, 5, None, None, False)
3278
+ np.percentile(d, 5, None, None, False, 'linear')
3279
+ o = np.ones((1,))
3280
+ np.percentile(d, 5, None, o, False, 'linear')
3281
+
3282
+ def test_complex(self):
3283
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G')
3284
+ assert_raises(TypeError, np.percentile, arr_c, 0.5)
3285
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D')
3286
+ assert_raises(TypeError, np.percentile, arr_c, 0.5)
3287
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='F')
3288
+ assert_raises(TypeError, np.percentile, arr_c, 0.5)
3289
+
3290
+ def test_2D(self):
3291
+ x = np.array([[1, 1, 1],
3292
+ [1, 1, 1],
3293
+ [4, 4, 3],
3294
+ [1, 1, 1],
3295
+ [1, 1, 1]])
3296
+ assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1])
3297
+
3298
+ @pytest.mark.parametrize("dtype", np.typecodes["Float"])
3299
+ def test_linear_nan_1D(self, dtype):
3300
+ # METHOD 1 of H&F
3301
+ arr = np.asarray([15.0, np.nan, 35.0, 40.0, 50.0], dtype=dtype)
3302
+ res = np.percentile(
3303
+ arr,
3304
+ 40.0,
3305
+ method="linear")
3306
+ np.testing.assert_equal(res, np.nan)
3307
+ np.testing.assert_equal(res.dtype, arr.dtype)
3308
+
3309
+ H_F_TYPE_CODES = [(int_type, np.float64)
3310
+ for int_type in np.typecodes["AllInteger"]
3311
+ ] + [(np.float16, np.float16),
3312
+ (np.float32, np.float32),
3313
+ (np.float64, np.float64),
3314
+ (np.longdouble, np.longdouble),
3315
+ (np.dtype("O"), np.float64)]
3316
+
3317
+ @pytest.mark.parametrize(["function", "quantile"],
3318
+ [(np.quantile, 0.4),
3319
+ (np.percentile, 40.0)])
3320
+ @pytest.mark.parametrize(["input_dtype", "expected_dtype"], H_F_TYPE_CODES)
3321
+ @pytest.mark.parametrize(["method", "weighted", "expected"],
3322
+ [("inverted_cdf", False, 20),
3323
+ ("inverted_cdf", True, 20),
3324
+ ("averaged_inverted_cdf", False, 27.5),
3325
+ ("closest_observation", False, 20),
3326
+ ("interpolated_inverted_cdf", False, 20),
3327
+ ("hazen", False, 27.5),
3328
+ ("weibull", False, 26),
3329
+ ("linear", False, 29),
3330
+ ("median_unbiased", False, 27),
3331
+ ("normal_unbiased", False, 27.125),
3332
+ ])
3333
+ def test_linear_interpolation(self,
3334
+ function,
3335
+ quantile,
3336
+ method,
3337
+ weighted,
3338
+ expected,
3339
+ input_dtype,
3340
+ expected_dtype):
3341
+ expected_dtype = np.dtype(expected_dtype)
3342
+
3343
+ arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype)
3344
+ weights = np.ones_like(arr) if weighted else None
3345
+ if input_dtype is np.longdouble:
3346
+ if function is np.quantile:
3347
+ # 0.4 is not exactly representable and it matters
3348
+ # for "averaged_inverted_cdf", so we need to cheat.
3349
+ quantile = input_dtype("0.4")
3350
+ # We want to use nulp, but that does not work for longdouble
3351
+ test_function = np.testing.assert_almost_equal
3352
+ else:
3353
+ test_function = np.testing.assert_array_almost_equal_nulp
3354
+
3355
+ actual = function(arr, quantile, method=method, weights=weights)
3356
+
3357
+ test_function(actual, expected_dtype.type(expected))
3358
+
3359
+ if method in ["inverted_cdf", "closest_observation"]:
3360
+ if input_dtype == "O":
3361
+ np.testing.assert_equal(np.asarray(actual).dtype, np.float64)
3362
+ else:
3363
+ np.testing.assert_equal(np.asarray(actual).dtype,
3364
+ np.dtype(input_dtype))
3365
+ else:
3366
+ np.testing.assert_equal(np.asarray(actual).dtype,
3367
+ np.dtype(expected_dtype))
3368
+
3369
+ TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["Float"] + "O"
3370
+
3371
+ @pytest.mark.parametrize("dtype", TYPE_CODES)
3372
+ def test_lower_higher(self, dtype):
3373
+ assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,
3374
+ method='lower'), 4)
3375
+ assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,
3376
+ method='higher'), 5)
3377
+
3378
+ @pytest.mark.parametrize("dtype", TYPE_CODES)
3379
+ def test_midpoint(self, dtype):
3380
+ assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,
3381
+ method='midpoint'), 4.5)
3382
+ assert_equal(np.percentile(np.arange(9, dtype=dtype) + 1, 50,
3383
+ method='midpoint'), 5)
3384
+ assert_equal(np.percentile(np.arange(11, dtype=dtype), 51,
3385
+ method='midpoint'), 5.5)
3386
+ assert_equal(np.percentile(np.arange(11, dtype=dtype), 50,
3387
+ method='midpoint'), 5)
3388
+
3389
+ @pytest.mark.parametrize("dtype", TYPE_CODES)
3390
+ def test_nearest(self, dtype):
3391
+ assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,
3392
+ method='nearest'), 5)
3393
+ assert_equal(np.percentile(np.arange(10, dtype=dtype), 49,
3394
+ method='nearest'), 4)
3395
+
3396
+ def test_linear_interpolation_extrapolation(self):
3397
+ arr = np.random.rand(5)
3398
+
3399
+ actual = np.percentile(arr, 100)
3400
+ np.testing.assert_equal(actual, arr.max())
3401
+
3402
+ actual = np.percentile(arr, 0)
3403
+ np.testing.assert_equal(actual, arr.min())
3404
+
3405
+ def test_sequence(self):
3406
+ x = np.arange(8) * 0.5
3407
+ assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75])
3408
+
3409
+ def test_axis(self):
3410
+ x = np.arange(12).reshape(3, 4)
3411
+
3412
+ assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0])
3413
+
3414
+ r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]
3415
+ assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0)
3416
+
3417
+ r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]]
3418
+ assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T)
3419
+
3420
+ # ensure qth axis is always first as with np.array(old_percentile(..))
3421
+ x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
3422
+ assert_equal(np.percentile(x, (25, 50)).shape, (2,))
3423
+ assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,))
3424
+ assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6))
3425
+ assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6))
3426
+ assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6))
3427
+ assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5))
3428
+ assert_equal(
3429
+ np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6))
3430
+ assert_equal(np.percentile(x, (25, 50),
3431
+ method="higher").shape, (2,))
3432
+ assert_equal(np.percentile(x, (25, 50, 75),
3433
+ method="higher").shape, (3,))
3434
+ assert_equal(np.percentile(x, (25, 50), axis=0,
3435
+ method="higher").shape, (2, 4, 5, 6))
3436
+ assert_equal(np.percentile(x, (25, 50), axis=1,
3437
+ method="higher").shape, (2, 3, 5, 6))
3438
+ assert_equal(np.percentile(x, (25, 50), axis=2,
3439
+ method="higher").shape, (2, 3, 4, 6))
3440
+ assert_equal(np.percentile(x, (25, 50), axis=3,
3441
+ method="higher").shape, (2, 3, 4, 5))
3442
+ assert_equal(np.percentile(x, (25, 50, 75), axis=1,
3443
+ method="higher").shape, (3, 3, 5, 6))
3444
+
3445
+ def test_scalar_q(self):
3446
+ # test for no empty dimensions for compatibility with old percentile
3447
+ x = np.arange(12).reshape(3, 4)
3448
+ assert_equal(np.percentile(x, 50), 5.5)
3449
+ assert_(np.isscalar(np.percentile(x, 50)))
3450
+ r0 = np.array([4., 5., 6., 7.])
3451
+ assert_equal(np.percentile(x, 50, axis=0), r0)
3452
+ assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
3453
+ r1 = np.array([1.5, 5.5, 9.5])
3454
+ assert_almost_equal(np.percentile(x, 50, axis=1), r1)
3455
+ assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)
3456
+
3457
+ out = np.empty(1)
3458
+ assert_equal(np.percentile(x, 50, out=out), 5.5)
3459
+ assert_equal(out, 5.5)
3460
+ out = np.empty(4)
3461
+ assert_equal(np.percentile(x, 50, axis=0, out=out), r0)
3462
+ assert_equal(out, r0)
3463
+ out = np.empty(3)
3464
+ assert_equal(np.percentile(x, 50, axis=1, out=out), r1)
3465
+ assert_equal(out, r1)
3466
+
3467
+ # test for no empty dimensions for compatibility with old percentile
3468
+ x = np.arange(12).reshape(3, 4)
3469
+ assert_equal(np.percentile(x, 50, method='lower'), 5.)
3470
+ assert_(np.isscalar(np.percentile(x, 50)))
3471
+ r0 = np.array([4., 5., 6., 7.])
3472
+ c0 = np.percentile(x, 50, method='lower', axis=0)
3473
+ assert_equal(c0, r0)
3474
+ assert_equal(c0.shape, r0.shape)
3475
+ r1 = np.array([1., 5., 9.])
3476
+ c1 = np.percentile(x, 50, method='lower', axis=1)
3477
+ assert_almost_equal(c1, r1)
3478
+ assert_equal(c1.shape, r1.shape)
3479
+
3480
+ out = np.empty((), dtype=x.dtype)
3481
+ c = np.percentile(x, 50, method='lower', out=out)
3482
+ assert_equal(c, 5)
3483
+ assert_equal(out, 5)
3484
+ out = np.empty(4, dtype=x.dtype)
3485
+ c = np.percentile(x, 50, method='lower', axis=0, out=out)
3486
+ assert_equal(c, r0)
3487
+ assert_equal(out, r0)
3488
+ out = np.empty(3, dtype=x.dtype)
3489
+ c = np.percentile(x, 50, method='lower', axis=1, out=out)
3490
+ assert_equal(c, r1)
3491
+ assert_equal(out, r1)
3492
+
3493
+ def test_exception(self):
3494
+ assert_raises(ValueError, np.percentile, [1, 2], 56,
3495
+ method='foobar')
3496
+ assert_raises(ValueError, np.percentile, [1], 101)
3497
+ assert_raises(ValueError, np.percentile, [1], -1)
3498
+ assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101])
3499
+ assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1])
3500
+
3501
+ def test_percentile_list(self):
3502
+ assert_equal(np.percentile([1, 2, 3], 0), 1)
3503
+
3504
+ @pytest.mark.parametrize(
3505
+ "percentile, with_weights",
3506
+ [
3507
+ (np.percentile, False),
3508
+ (partial(np.percentile, method="inverted_cdf"), True),
3509
+ ]
3510
+ )
3511
+ def test_percentile_out(self, percentile, with_weights):
3512
+ out_dtype = int if with_weights else float
3513
+ x = np.array([1, 2, 3])
3514
+ y = np.zeros((3,), dtype=out_dtype)
3515
+ p = (1, 2, 3)
3516
+ weights = np.ones_like(x) if with_weights else None
3517
+ r = percentile(x, p, out=y, weights=weights)
3518
+ assert r is y
3519
+ assert_equal(percentile(x, p, weights=weights), y)
3520
+
3521
+ x = np.array([[1, 2, 3],
3522
+ [4, 5, 6]])
3523
+ y = np.zeros((3, 3), dtype=out_dtype)
3524
+ weights = np.ones_like(x) if with_weights else None
3525
+ r = percentile(x, p, axis=0, out=y, weights=weights)
3526
+ assert r is y
3527
+ assert_equal(percentile(x, p, weights=weights, axis=0), y)
3528
+
3529
+ y = np.zeros((3, 2), dtype=out_dtype)
3530
+ percentile(x, p, axis=1, out=y, weights=weights)
3531
+ assert_equal(percentile(x, p, weights=weights, axis=1), y)
3532
+
3533
+ x = np.arange(12).reshape(3, 4)
3534
+ # q.dim > 1, float
3535
+ if with_weights:
3536
+ r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
3537
+ else:
3538
+ r0 = np.array([[2., 3., 4., 5.], [4., 5., 6., 7.]])
3539
+ out = np.empty((2, 4), dtype=out_dtype)
3540
+ weights = np.ones_like(x) if with_weights else None
3541
+ assert_equal(
3542
+ percentile(x, (25, 50), axis=0, out=out, weights=weights), r0
3543
+ )
3544
+ assert_equal(out, r0)
3545
+ r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]])
3546
+ out = np.empty((2, 3))
3547
+ assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)
3548
+ assert_equal(out, r1)
3549
+
3550
+ # q.dim > 1, int
3551
+ r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
3552
+ out = np.empty((2, 4), dtype=x.dtype)
3553
+ c = np.percentile(x, (25, 50), method='lower', axis=0, out=out)
3554
+ assert_equal(c, r0)
3555
+ assert_equal(out, r0)
3556
+ r1 = np.array([[0, 4, 8], [1, 5, 9]])
3557
+ out = np.empty((2, 3), dtype=x.dtype)
3558
+ c = np.percentile(x, (25, 50), method='lower', axis=1, out=out)
3559
+ assert_equal(c, r1)
3560
+ assert_equal(out, r1)
3561
+
3562
+ def test_percentile_empty_dim(self):
3563
+ # empty dims are preserved
3564
+ d = np.arange(11 * 2).reshape(11, 1, 2, 1)
3565
+ assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1))
3566
+ assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1))
3567
+ assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1))
3568
+ assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2))
3569
+ assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2))
3570
+ assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1))
3571
+ assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1))
3572
+ assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1))
3573
+
3574
+ assert_array_equal(np.percentile(d, 50, axis=2,
3575
+ method='midpoint').shape,
3576
+ (11, 1, 1))
3577
+ assert_array_equal(np.percentile(d, 50, axis=-2,
3578
+ method='midpoint').shape,
3579
+ (11, 1, 1))
3580
+
3581
+ assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape,
3582
+ (2, 1, 2, 1))
3583
+ assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape,
3584
+ (2, 11, 2, 1))
3585
+ assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape,
3586
+ (2, 11, 1, 1))
3587
+ assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape,
3588
+ (2, 11, 1, 2))
3589
+
3590
+ def test_percentile_no_overwrite(self):
3591
+ a = np.array([2, 3, 4, 1])
3592
+ np.percentile(a, [50], overwrite_input=False)
3593
+ assert_equal(a, np.array([2, 3, 4, 1]))
3594
+
3595
+ a = np.array([2, 3, 4, 1])
3596
+ np.percentile(a, [50])
3597
+ assert_equal(a, np.array([2, 3, 4, 1]))
3598
+
3599
+ def test_no_p_overwrite(self):
3600
+ p = np.linspace(0., 100., num=5)
3601
+ np.percentile(np.arange(100.), p, method="midpoint")
3602
+ assert_array_equal(p, np.linspace(0., 100., num=5))
3603
+ p = np.linspace(0., 100., num=5).tolist()
3604
+ np.percentile(np.arange(100.), p, method="midpoint")
3605
+ assert_array_equal(p, np.linspace(0., 100., num=5).tolist())
3606
+
3607
+ def test_percentile_overwrite(self):
3608
+ a = np.array([2, 3, 4, 1])
3609
+ b = np.percentile(a, [50], overwrite_input=True)
3610
+ assert_equal(b, np.array([2.5]))
3611
+
3612
+ b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True)
3613
+ assert_equal(b, np.array([2.5]))
3614
+
3615
+ def test_extended_axis(self):
3616
+ o = np.random.normal(size=(71, 23))
3617
+ x = np.dstack([o] * 10)
3618
+ assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))
3619
+ x = np.moveaxis(x, -1, 0)
3620
+ assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))
3621
+ x = x.swapaxes(0, 1).copy()
3622
+ assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))
3623
+ x = x.swapaxes(0, 1).copy()
3624
+
3625
+ assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),
3626
+ np.percentile(x, [25, 60], axis=None))
3627
+ assert_equal(np.percentile(x, [25, 60], axis=(0,)),
3628
+ np.percentile(x, [25, 60], axis=0))
3629
+
3630
+ d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
3631
+ np.random.shuffle(d.ravel())
3632
+ assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0],
3633
+ np.percentile(d[:, :, :, 0].flatten(), 25))
3634
+ assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
3635
+ np.percentile(d[:, :, 1, :].flatten(), [10, 90]))
3636
+ assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],
3637
+ np.percentile(d[:, :, 2, :].flatten(), 25))
3638
+ assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],
3639
+ np.percentile(d[2, :, :, :].flatten(), 25))
3640
+ assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],
3641
+ np.percentile(d[2, 1, :, :].flatten(), 25))
3642
+ assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],
3643
+ np.percentile(d[2, :, :, 1].flatten(), 25))
3644
+ assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],
3645
+ np.percentile(d[2, :, 2, :].flatten(), 25))
3646
+
3647
+ def test_extended_axis_invalid(self):
3648
+ d = np.ones((3, 5, 7, 11))
3649
+ assert_raises(AxisError, np.percentile, d, axis=-5, q=25)
3650
+ assert_raises(AxisError, np.percentile, d, axis=(0, -5), q=25)
3651
+ assert_raises(AxisError, np.percentile, d, axis=4, q=25)
3652
+ assert_raises(AxisError, np.percentile, d, axis=(0, 4), q=25)
3653
+ # each of these refers to the same axis twice
3654
+ assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25)
3655
+ assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25)
3656
+ assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25)
3657
+
3658
+ def test_keepdims(self):
3659
+ d = np.ones((3, 5, 7, 11))
3660
+ assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape,
3661
+ (1, 1, 1, 1))
3662
+ assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape,
3663
+ (1, 1, 7, 11))
3664
+ assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape,
3665
+ (1, 5, 7, 1))
3666
+ assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape,
3667
+ (3, 1, 7, 11))
3668
+ assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape,
3669
+ (1, 1, 1, 1))
3670
+ assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape,
3671
+ (1, 1, 7, 1))
3672
+
3673
+ assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3),
3674
+ keepdims=True).shape, (2, 1, 1, 7, 1))
3675
+ assert_equal(np.percentile(d, [1, 7], axis=(0, 3),
3676
+ keepdims=True).shape, (2, 1, 5, 7, 1))
3677
+
3678
+ @pytest.mark.parametrize('q', [7, [1, 7]])
3679
+ @pytest.mark.parametrize(
3680
+ argnames='axis',
3681
+ argvalues=[
3682
+ None,
3683
+ 1,
3684
+ (1,),
3685
+ (0, 1),
3686
+ (-3, -1),
3687
+ ]
3688
+ )
3689
+ def test_keepdims_out(self, q, axis):
3690
+ d = np.ones((3, 5, 7, 11))
3691
+ if axis is None:
3692
+ shape_out = (1,) * d.ndim
3693
+ else:
3694
+ axis_norm = normalize_axis_tuple(axis, d.ndim)
3695
+ shape_out = tuple(
3696
+ 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
3697
+ shape_out = np.shape(q) + shape_out
3698
+
3699
+ out = np.empty(shape_out)
3700
+ result = np.percentile(d, q, axis=axis, keepdims=True, out=out)
3701
+ assert result is out
3702
+ assert_equal(result.shape, shape_out)
3703
+
3704
+ def test_out(self):
3705
+ o = np.zeros((4,))
3706
+ d = np.ones((3, 4))
3707
+ assert_equal(np.percentile(d, 0, 0, out=o), o)
3708
+ assert_equal(np.percentile(d, 0, 0, method='nearest', out=o), o)
3709
+ o = np.zeros((3,))
3710
+ assert_equal(np.percentile(d, 1, 1, out=o), o)
3711
+ assert_equal(np.percentile(d, 1, 1, method='nearest', out=o), o)
3712
+
3713
+ o = np.zeros(())
3714
+ assert_equal(np.percentile(d, 2, out=o), o)
3715
+ assert_equal(np.percentile(d, 2, method='nearest', out=o), o)
3716
+
3717
+ @pytest.mark.parametrize("method, weighted", [
3718
+ ("linear", False),
3719
+ ("nearest", False),
3720
+ ("inverted_cdf", False),
3721
+ ("inverted_cdf", True),
3722
+ ])
3723
+ def test_out_nan(self, method, weighted):
3724
+ if weighted:
3725
+ kwargs = {"weights": np.ones((3, 4)), "method": method}
3726
+ else:
3727
+ kwargs = {"method": method}
3728
+ with warnings.catch_warnings(record=True):
3729
+ warnings.filterwarnings('always', '', RuntimeWarning)
3730
+ o = np.zeros((4,))
3731
+ d = np.ones((3, 4))
3732
+ d[2, 1] = np.nan
3733
+ assert_equal(np.percentile(d, 0, 0, out=o, **kwargs), o)
3734
+
3735
+ o = np.zeros((3,))
3736
+ assert_equal(np.percentile(d, 1, 1, out=o, **kwargs), o)
3737
+
3738
+ o = np.zeros(())
3739
+ assert_equal(np.percentile(d, 1, out=o, **kwargs), o)
3740
+
3741
+ def test_nan_behavior(self):
3742
+ a = np.arange(24, dtype=float)
3743
+ a[2] = np.nan
3744
+ assert_equal(np.percentile(a, 0.3), np.nan)
3745
+ assert_equal(np.percentile(a, 0.3, axis=0), np.nan)
3746
+ assert_equal(np.percentile(a, [0.3, 0.6], axis=0),
3747
+ np.array([np.nan] * 2))
3748
+
3749
+ a = np.arange(24, dtype=float).reshape(2, 3, 4)
3750
+ a[1, 2, 3] = np.nan
3751
+ a[1, 1, 2] = np.nan
3752
+
3753
+ # no axis
3754
+ assert_equal(np.percentile(a, 0.3), np.nan)
3755
+ assert_equal(np.percentile(a, 0.3).ndim, 0)
3756
+
3757
+ # axis0 zerod
3758
+ b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0)
3759
+ b[2, 3] = np.nan
3760
+ b[1, 2] = np.nan
3761
+ assert_equal(np.percentile(a, 0.3, 0), b)
3762
+
3763
+ # axis0 not zerod
3764
+ b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
3765
+ [0.3, 0.6], 0)
3766
+ b[:, 2, 3] = np.nan
3767
+ b[:, 1, 2] = np.nan
3768
+ assert_equal(np.percentile(a, [0.3, 0.6], 0), b)
3769
+
3770
+ # axis1 zerod
3771
+ b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1)
3772
+ b[1, 3] = np.nan
3773
+ b[1, 2] = np.nan
3774
+ assert_equal(np.percentile(a, 0.3, 1), b)
3775
+ # axis1 not zerod
3776
+ b = np.percentile(
3777
+ np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1)
3778
+ b[:, 1, 3] = np.nan
3779
+ b[:, 1, 2] = np.nan
3780
+ assert_equal(np.percentile(a, [0.3, 0.6], 1), b)
3781
+
3782
+ # axis02 zerod
3783
+ b = np.percentile(
3784
+ np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2))
3785
+ b[1] = np.nan
3786
+ b[2] = np.nan
3787
+ assert_equal(np.percentile(a, 0.3, (0, 2)), b)
3788
+ # axis02 not zerod
3789
+ b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
3790
+ [0.3, 0.6], (0, 2))
3791
+ b[:, 1] = np.nan
3792
+ b[:, 2] = np.nan
3793
+ assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b)
3794
+ # axis02 not zerod with method='nearest'
3795
+ b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
3796
+ [0.3, 0.6], (0, 2), method='nearest')
3797
+ b[:, 1] = np.nan
3798
+ b[:, 2] = np.nan
3799
+ assert_equal(np.percentile(
3800
+ a, [0.3, 0.6], (0, 2), method='nearest'), b)
3801
+
3802
+ def test_nan_q(self):
3803
+ # GH18830
3804
+ with pytest.raises(ValueError, match="Percentiles must be in"):
3805
+ np.percentile([1, 2, 3, 4.0], np.nan)
3806
+ with pytest.raises(ValueError, match="Percentiles must be in"):
3807
+ np.percentile([1, 2, 3, 4.0], [np.nan])
3808
+ q = np.linspace(1.0, 99.0, 16)
3809
+ q[0] = np.nan
3810
+ with pytest.raises(ValueError, match="Percentiles must be in"):
3811
+ np.percentile([1, 2, 3, 4.0], q)
3812
+
3813
+ @pytest.mark.parametrize("dtype", ["m8[D]", "M8[s]"])
3814
+ @pytest.mark.parametrize("pos", [0, 23, 10])
3815
+ def test_nat_basic(self, dtype, pos):
3816
+ # TODO: Note that times have dubious rounding as of fixing NaTs!
3817
+ # NaT and NaN should behave the same, do basic tests for NaT:
3818
+ a = np.arange(0, 24, dtype=dtype)
3819
+ a[pos] = "NaT"
3820
+ res = np.percentile(a, 30)
3821
+ assert res.dtype == dtype
3822
+ assert np.isnat(res)
3823
+ res = np.percentile(a, [30, 60])
3824
+ assert res.dtype == dtype
3825
+ assert np.isnat(res).all()
3826
+
3827
+ a = np.arange(0, 24 * 3, dtype=dtype).reshape(-1, 3)
3828
+ a[pos, 1] = "NaT"
3829
+ res = np.percentile(a, 30, axis=0)
3830
+ assert_array_equal(np.isnat(res), [False, True, False])
3831
+
3832
+
3833
+ quantile_methods = [
3834
+ 'inverted_cdf', 'averaged_inverted_cdf', 'closest_observation',
3835
+ 'interpolated_inverted_cdf', 'hazen', 'weibull', 'linear',
3836
+ 'median_unbiased', 'normal_unbiased', 'nearest', 'lower', 'higher',
3837
+ 'midpoint']
3838
+
3839
+
3840
+ methods_supporting_weights = ["inverted_cdf"]
3841
+
3842
+
3843
+ class TestQuantile:
3844
+ # most of this is already tested by TestPercentile
3845
+
3846
+ def V(self, x, y, alpha):
3847
+ # Identification function used in several tests.
3848
+ return (x >= y) - alpha
3849
+
3850
+ def test_max_ulp(self):
3851
+ x = [0.0, 0.2, 0.4]
3852
+ a = np.quantile(x, 0.45)
3853
+ # The default linear method would result in 0 + 0.2 * (0.45/2) = 0.18.
3854
+ # 0.18 is not exactly representable and the formula leads to a 1 ULP
3855
+ # different result. Ensure it is this exact within 1 ULP, see gh-20331.
3856
+ np.testing.assert_array_max_ulp(a, 0.18, maxulp=1)
3857
+
3858
+ def test_basic(self):
3859
+ x = np.arange(8) * 0.5
3860
+ assert_equal(np.quantile(x, 0), 0.)
3861
+ assert_equal(np.quantile(x, 1), 3.5)
3862
+ assert_equal(np.quantile(x, 0.5), 1.75)
3863
+
3864
+ def test_correct_quantile_value(self):
3865
+ a = np.array([True])
3866
+ tf_quant = np.quantile(True, False)
3867
+ assert_equal(tf_quant, a[0])
3868
+ assert_equal(type(tf_quant), a.dtype)
3869
+ a = np.array([False, True, True])
3870
+ quant_res = np.quantile(a, a)
3871
+ assert_array_equal(quant_res, a)
3872
+ assert_equal(quant_res.dtype, a.dtype)
3873
+
3874
+ def test_fraction(self):
3875
+ # fractional input, integral quantile
3876
+ x = [Fraction(i, 2) for i in range(8)]
3877
+ q = np.quantile(x, 0)
3878
+ assert_equal(q, 0)
3879
+ assert_equal(type(q), Fraction)
3880
+
3881
+ q = np.quantile(x, 1)
3882
+ assert_equal(q, Fraction(7, 2))
3883
+ assert_equal(type(q), Fraction)
3884
+
3885
+ q = np.quantile(x, .5)
3886
+ assert_equal(q, 1.75)
3887
+ assert_equal(type(q), np.float64)
3888
+
3889
+ q = np.quantile(x, Fraction(1, 2))
3890
+ assert_equal(q, Fraction(7, 4))
3891
+ assert_equal(type(q), Fraction)
3892
+
3893
+ q = np.quantile(x, [Fraction(1, 2)])
3894
+ assert_equal(q, np.array([Fraction(7, 4)]))
3895
+ assert_equal(type(q), np.ndarray)
3896
+
3897
+ q = np.quantile(x, [[Fraction(1, 2)]])
3898
+ assert_equal(q, np.array([[Fraction(7, 4)]]))
3899
+ assert_equal(type(q), np.ndarray)
3900
+
3901
+ # repeat with integral input but fractional quantile
3902
+ x = np.arange(8)
3903
+ assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))
3904
+
3905
+ def test_complex(self):
3906
+ # gh-22652
3907
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G')
3908
+ assert_raises(TypeError, np.quantile, arr_c, 0.5)
3909
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D')
3910
+ assert_raises(TypeError, np.quantile, arr_c, 0.5)
3911
+ arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='F')
3912
+ assert_raises(TypeError, np.quantile, arr_c, 0.5)
3913
+
3914
+ def test_no_p_overwrite(self):
3915
+ # this is worth retesting, because quantile does not make a copy
3916
+ p0 = np.array([0, 0.75, 0.25, 0.5, 1.0])
3917
+ p = p0.copy()
3918
+ np.quantile(np.arange(100.), p, method="midpoint")
3919
+ assert_array_equal(p, p0)
3920
+
3921
+ p0 = p0.tolist()
3922
+ p = p.tolist()
3923
+ np.quantile(np.arange(100.), p, method="midpoint")
3924
+ assert_array_equal(p, p0)
3925
+
3926
+ @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
3927
+ def test_quantile_preserve_int_type(self, dtype):
3928
+ res = np.quantile(np.array([1, 2], dtype=dtype), [0.5],
3929
+ method="nearest")
3930
+ assert res.dtype == dtype
3931
+
3932
+ @pytest.mark.parametrize("method", quantile_methods)
3933
+ def test_q_zero_one(self, method):
3934
+ # gh-24710
3935
+ arr = [10, 11, 12]
3936
+ quantile = np.quantile(arr, q=[0, 1], method=method)
3937
+ assert_equal(quantile, np.array([10, 12]))
3938
+
3939
+ @pytest.mark.parametrize("method", quantile_methods)
3940
+ def test_quantile_monotonic(self, method):
3941
+ # GH 14685
3942
+ # test that the return value of quantile is monotonic if p0 is ordered
3943
+ # Also tests that the boundary values are not mishandled.
3944
+ p0 = np.linspace(0, 1, 101)
3945
+ quantile = np.quantile(np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9,
3946
+ 8, 8, 7]) * 0.1, p0, method=method)
3947
+ assert_equal(np.sort(quantile), quantile)
3948
+
3949
+ # Also test one where the number of data points is clearly divisible:
3950
+ quantile = np.quantile([0., 1., 2., 3.], p0, method=method)
3951
+ assert_equal(np.sort(quantile), quantile)
3952
+
3953
+ @hypothesis.given(
3954
+ arr=arrays(dtype=np.float64,
3955
+ shape=st.integers(min_value=3, max_value=1000),
3956
+ elements=st.floats(allow_infinity=False, allow_nan=False,
3957
+ min_value=-1e300, max_value=1e300)))
3958
+ def test_quantile_monotonic_hypo(self, arr):
3959
+ p0 = np.arange(0, 1, 0.01)
3960
+ quantile = np.quantile(arr, p0)
3961
+ assert_equal(np.sort(quantile), quantile)
3962
+
3963
+ def test_quantile_scalar_nan(self):
3964
+ a = np.array([[10., 7., 4.], [3., 2., 1.]])
3965
+ a[0][1] = np.nan
3966
+ actual = np.quantile(a, 0.5)
3967
+ assert np.isscalar(actual)
3968
+ assert_equal(np.quantile(a, 0.5), np.nan)
3969
+
3970
+ @pytest.mark.parametrize("weights", [False, True])
3971
+ @pytest.mark.parametrize("method", quantile_methods)
3972
+ @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
3973
+ def test_quantile_identification_equation(self, weights, method, alpha):
3974
+ # Test that the identification equation holds for the empirical
3975
+ # CDF:
3976
+ # E[V(x, Y)] = 0 <=> x is quantile
3977
+ # with Y the random variable for which we have observed values and
3978
+ # V(x, y) the canonical identification function for the quantile (at
3979
+ # level alpha), see
3980
+ # https://doi.org/10.48550/arXiv.0912.0902
3981
+ if weights and method not in methods_supporting_weights:
3982
+ pytest.skip("Weights not supported by method.")
3983
+ rng = np.random.default_rng(4321)
3984
+ # We choose n and alpha such that we cover 3 cases:
3985
+ # - n * alpha is an integer
3986
+ # - n * alpha is a float that gets rounded down
3987
+ # - n * alpha is a float that gest rounded up
3988
+ n = 102 # n * alpha = 20.4, 51. , 91.8
3989
+ y = rng.random(n)
3990
+ w = rng.integers(low=0, high=10, size=n) if weights else None
3991
+ x = np.quantile(y, alpha, method=method, weights=w)
3992
+
3993
+ if method in ("higher",):
3994
+ # These methods do not fulfill the identification equation.
3995
+ assert np.abs(np.mean(self.V(x, y, alpha))) > 0.1 / n
3996
+ elif int(n * alpha) == n * alpha and not weights:
3997
+ # We can expect exact results, up to machine precision.
3998
+ assert_allclose(
3999
+ np.average(self.V(x, y, alpha), weights=w), 0, atol=1e-14,
4000
+ )
4001
+ else:
4002
+ # V = (x >= y) - alpha cannot sum to zero exactly but within
4003
+ # "sample precision".
4004
+ assert_allclose(np.average(self.V(x, y, alpha), weights=w), 0,
4005
+ atol=1 / n / np.amin([alpha, 1 - alpha]))
4006
+
4007
+ @pytest.mark.parametrize("weights", [False, True])
4008
+ @pytest.mark.parametrize("method", quantile_methods)
4009
+ @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
4010
+ def test_quantile_add_and_multiply_constant(self, weights, method, alpha):
4011
+ # Test that
4012
+ # 1. quantile(c + x) = c + quantile(x)
4013
+ # 2. quantile(c * x) = c * quantile(x)
4014
+ # 3. quantile(-x) = -quantile(x, 1 - alpha)
4015
+ # On empirical quantiles, this equation does not hold exactly.
4016
+ # Koenker (2005) "Quantile Regression" Chapter 2.2.3 calls these
4017
+ # properties equivariance.
4018
+ if weights and method not in methods_supporting_weights:
4019
+ pytest.skip("Weights not supported by method.")
4020
+ rng = np.random.default_rng(4321)
4021
+ # We choose n and alpha such that we have cases for
4022
+ # - n * alpha is an integer
4023
+ # - n * alpha is a float that gets rounded down
4024
+ # - n * alpha is a float that gest rounded up
4025
+ n = 102 # n * alpha = 20.4, 51. , 91.8
4026
+ y = rng.random(n)
4027
+ w = rng.integers(low=0, high=10, size=n) if weights else None
4028
+ q = np.quantile(y, alpha, method=method, weights=w)
4029
+ c = 13.5
4030
+
4031
+ # 1
4032
+ assert_allclose(np.quantile(c + y, alpha, method=method, weights=w),
4033
+ c + q)
4034
+ # 2
4035
+ assert_allclose(np.quantile(c * y, alpha, method=method, weights=w),
4036
+ c * q)
4037
+ # 3
4038
+ if weights:
4039
+ # From here on, we would need more methods to support weights.
4040
+ return
4041
+ q = -np.quantile(-y, 1 - alpha, method=method)
4042
+ if method == "inverted_cdf":
4043
+ if (
4044
+ n * alpha == int(n * alpha)
4045
+ or np.round(n * alpha) == int(n * alpha) + 1
4046
+ ):
4047
+ assert_allclose(q, np.quantile(y, alpha, method="higher"))
4048
+ else:
4049
+ assert_allclose(q, np.quantile(y, alpha, method="lower"))
4050
+ elif method == "closest_observation":
4051
+ if n * alpha == int(n * alpha):
4052
+ assert_allclose(q, np.quantile(y, alpha, method="higher"))
4053
+ elif np.round(n * alpha) == int(n * alpha) + 1:
4054
+ assert_allclose(
4055
+ q, np.quantile(y, alpha + 1 / n, method="higher"))
4056
+ else:
4057
+ assert_allclose(q, np.quantile(y, alpha, method="lower"))
4058
+ elif method == "interpolated_inverted_cdf":
4059
+ assert_allclose(q, np.quantile(y, alpha + 1 / n, method=method))
4060
+ elif method == "nearest":
4061
+ if n * alpha == int(n * alpha):
4062
+ assert_allclose(q, np.quantile(y, alpha + 1 / n, method=method))
4063
+ else:
4064
+ assert_allclose(q, np.quantile(y, alpha, method=method))
4065
+ elif method == "lower":
4066
+ assert_allclose(q, np.quantile(y, alpha, method="higher"))
4067
+ elif method == "higher":
4068
+ assert_allclose(q, np.quantile(y, alpha, method="lower"))
4069
+ else:
4070
+ # "averaged_inverted_cdf", "hazen", "weibull", "linear",
4071
+ # "median_unbiased", "normal_unbiased", "midpoint"
4072
+ assert_allclose(q, np.quantile(y, alpha, method=method))
4073
+
4074
+ @pytest.mark.parametrize("method", methods_supporting_weights)
4075
+ @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
4076
+ def test_quantile_constant_weights(self, method, alpha):
4077
+ rng = np.random.default_rng(4321)
4078
+ # We choose n and alpha such that we have cases for
4079
+ # - n * alpha is an integer
4080
+ # - n * alpha is a float that gets rounded down
4081
+ # - n * alpha is a float that gest rounded up
4082
+ n = 102 # n * alpha = 20.4, 51. , 91.8
4083
+ y = rng.random(n)
4084
+ q = np.quantile(y, alpha, method=method)
4085
+
4086
+ w = np.ones_like(y)
4087
+ qw = np.quantile(y, alpha, method=method, weights=w)
4088
+ assert_allclose(qw, q)
4089
+
4090
+ w = 8.125 * np.ones_like(y)
4091
+ qw = np.quantile(y, alpha, method=method, weights=w)
4092
+ assert_allclose(qw, q)
4093
+
4094
+ @pytest.mark.parametrize("method", methods_supporting_weights)
4095
+ @pytest.mark.parametrize("alpha", [0, 0.2, 0.5, 0.9, 1])
4096
+ def test_quantile_with_integer_weights(self, method, alpha):
4097
+ # Integer weights can be interpreted as repeated observations.
4098
+ rng = np.random.default_rng(4321)
4099
+ # We choose n and alpha such that we have cases for
4100
+ # - n * alpha is an integer
4101
+ # - n * alpha is a float that gets rounded down
4102
+ # - n * alpha is a float that gest rounded up
4103
+ n = 102 # n * alpha = 20.4, 51. , 91.8
4104
+ y = rng.random(n)
4105
+ w = rng.integers(low=0, high=10, size=n, dtype=np.int32)
4106
+
4107
+ qw = np.quantile(y, alpha, method=method, weights=w)
4108
+ q = np.quantile(np.repeat(y, w), alpha, method=method)
4109
+ assert_allclose(qw, q)
4110
+
4111
+ @pytest.mark.parametrize("method", methods_supporting_weights)
4112
+ def test_quantile_with_weights_and_axis(self, method):
4113
+ rng = np.random.default_rng(4321)
4114
+
4115
+ # 1d weight and single alpha
4116
+ y = rng.random((2, 10, 3))
4117
+ w = np.abs(rng.random(10))
4118
+ alpha = 0.5
4119
+ q = np.quantile(y, alpha, weights=w, method=method, axis=1)
4120
+ q_res = np.zeros(shape=(2, 3))
4121
+ for i in range(2):
4122
+ for j in range(3):
4123
+ q_res[i, j] = np.quantile(
4124
+ y[i, :, j], alpha, method=method, weights=w
4125
+ )
4126
+ assert_allclose(q, q_res)
4127
+
4128
+ # 1d weight and 1d alpha
4129
+ alpha = [0, 0.2, 0.4, 0.6, 0.8, 1] # shape (6,)
4130
+ q = np.quantile(y, alpha, weights=w, method=method, axis=1)
4131
+ q_res = np.zeros(shape=(6, 2, 3))
4132
+ for i in range(2):
4133
+ for j in range(3):
4134
+ q_res[:, i, j] = np.quantile(
4135
+ y[i, :, j], alpha, method=method, weights=w
4136
+ )
4137
+ assert_allclose(q, q_res)
4138
+
4139
+ # 1d weight and 2d alpha
4140
+ alpha = [[0, 0.2], [0.4, 0.6], [0.8, 1]] # shape (3, 2)
4141
+ q = np.quantile(y, alpha, weights=w, method=method, axis=1)
4142
+ q_res = q_res.reshape((3, 2, 2, 3))
4143
+ assert_allclose(q, q_res)
4144
+
4145
+ # shape of weights equals shape of y
4146
+ w = np.abs(rng.random((2, 10, 3)))
4147
+ alpha = 0.5
4148
+ q = np.quantile(y, alpha, weights=w, method=method, axis=1)
4149
+ q_res = np.zeros(shape=(2, 3))
4150
+ for i in range(2):
4151
+ for j in range(3):
4152
+ q_res[i, j] = np.quantile(
4153
+ y[i, :, j], alpha, method=method, weights=w[i, :, j]
4154
+ )
4155
+ assert_allclose(q, q_res)
4156
+
4157
+ @pytest.mark.parametrize("method", methods_supporting_weights)
4158
+ def test_quantile_weights_min_max(self, method):
4159
+ # Test weighted quantile at 0 and 1 with leading and trailing zero
4160
+ # weights.
4161
+ w = [0, 0, 1, 2, 3, 0]
4162
+ y = np.arange(6)
4163
+ y_min = np.quantile(y, 0, weights=w, method="inverted_cdf")
4164
+ y_max = np.quantile(y, 1, weights=w, method="inverted_cdf")
4165
+ assert y_min == y[2] # == 2
4166
+ assert y_max == y[4] # == 4
4167
+
4168
+ def test_quantile_weights_raises_negative_weights(self):
4169
+ y = [1, 2]
4170
+ w = [-0.5, 1]
4171
+ with pytest.raises(ValueError, match="Weights must be non-negative"):
4172
+ np.quantile(y, 0.5, weights=w, method="inverted_cdf")
4173
+
4174
+ @pytest.mark.parametrize(
4175
+ "method",
4176
+ sorted(set(quantile_methods) - set(methods_supporting_weights)),
4177
+ )
4178
+ def test_quantile_weights_raises_unsupported_methods(self, method):
4179
+ y = [1, 2]
4180
+ w = [0.5, 1]
4181
+ msg = "Only method 'inverted_cdf' supports weights"
4182
+ with pytest.raises(ValueError, match=msg):
4183
+ np.quantile(y, 0.5, weights=w, method=method)
4184
+
4185
+ def test_weibull_fraction(self):
4186
+ arr = [Fraction(0, 1), Fraction(1, 10)]
4187
+ quantile = np.quantile(arr, [0, ], method='weibull')
4188
+ assert_equal(quantile, np.array(Fraction(0, 1)))
4189
+ quantile = np.quantile(arr, [Fraction(1, 2)], method='weibull')
4190
+ assert_equal(quantile, np.array(Fraction(1, 20)))
4191
+
4192
+ def test_closest_observation(self):
4193
+ # Round ties to nearest even order statistic (see #26656)
4194
+ m = 'closest_observation'
4195
+ q = 0.5
4196
+ arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4197
+ assert_equal(2, np.quantile(arr[0:3], q, method=m))
4198
+ assert_equal(2, np.quantile(arr[0:4], q, method=m))
4199
+ assert_equal(2, np.quantile(arr[0:5], q, method=m))
4200
+ assert_equal(3, np.quantile(arr[0:6], q, method=m))
4201
+ assert_equal(4, np.quantile(arr[0:7], q, method=m))
4202
+ assert_equal(4, np.quantile(arr[0:8], q, method=m))
4203
+ assert_equal(4, np.quantile(arr[0:9], q, method=m))
4204
+ assert_equal(5, np.quantile(arr, q, method=m))
4205
+
4206
+
4207
+ class TestLerp:
4208
+ @hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,
4209
+ min_value=0, max_value=1),
4210
+ t1=st.floats(allow_nan=False, allow_infinity=False,
4211
+ min_value=0, max_value=1),
4212
+ a=st.floats(allow_nan=False, allow_infinity=False,
4213
+ min_value=-1e300, max_value=1e300),
4214
+ b=st.floats(allow_nan=False, allow_infinity=False,
4215
+ min_value=-1e300, max_value=1e300))
4216
+ def test_linear_interpolation_formula_monotonic(self, t0, t1, a, b):
4217
+ l0 = nfb._lerp(a, b, t0)
4218
+ l1 = nfb._lerp(a, b, t1)
4219
+ if t0 == t1 or a == b:
4220
+ assert l0 == l1 # uninteresting
4221
+ elif (t0 < t1) == (a < b):
4222
+ assert l0 <= l1
4223
+ else:
4224
+ assert l0 >= l1
4225
+
4226
+ @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
4227
+ min_value=0, max_value=1),
4228
+ a=st.floats(allow_nan=False, allow_infinity=False,
4229
+ min_value=-1e300, max_value=1e300),
4230
+ b=st.floats(allow_nan=False, allow_infinity=False,
4231
+ min_value=-1e300, max_value=1e300))
4232
+ def test_linear_interpolation_formula_bounded(self, t, a, b):
4233
+ if a <= b:
4234
+ assert a <= nfb._lerp(a, b, t) <= b
4235
+ else:
4236
+ assert b <= nfb._lerp(a, b, t) <= a
4237
+
4238
+ @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
4239
+ min_value=0, max_value=1),
4240
+ a=st.floats(allow_nan=False, allow_infinity=False,
4241
+ min_value=-1e300, max_value=1e300),
4242
+ b=st.floats(allow_nan=False, allow_infinity=False,
4243
+ min_value=-1e300, max_value=1e300))
4244
+ def test_linear_interpolation_formula_symmetric(self, t, a, b):
4245
+ # double subtraction is needed to remove the extra precision of t < 0.5
4246
+ left = nfb._lerp(a, b, 1 - (1 - t))
4247
+ right = nfb._lerp(b, a, 1 - t)
4248
+ assert_allclose(left, right)
4249
+
4250
+ def test_linear_interpolation_formula_0d_inputs(self):
4251
+ a = np.array(2)
4252
+ b = np.array(5)
4253
+ t = np.array(0.2)
4254
+ assert nfb._lerp(a, b, t) == 2.6
4255
+
4256
+
4257
+ class TestMedian:
4258
+
4259
+ def test_basic(self):
4260
+ a0 = np.array(1)
4261
+ a1 = np.arange(2)
4262
+ a2 = np.arange(6).reshape(2, 3)
4263
+ assert_equal(np.median(a0), 1)
4264
+ assert_allclose(np.median(a1), 0.5)
4265
+ assert_allclose(np.median(a2), 2.5)
4266
+ assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5])
4267
+ assert_equal(np.median(a2, axis=1), [1, 4])
4268
+ assert_allclose(np.median(a2, axis=None), 2.5)
4269
+
4270
+ a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775])
4271
+ assert_almost_equal((a[1] + a[3]) / 2., np.median(a))
4272
+ a = np.array([0.0463301, 0.0444502, 0.141249])
4273
+ assert_equal(a[0], np.median(a))
4274
+ a = np.array([0.0444502, 0.141249, 0.0463301])
4275
+ assert_equal(a[-1], np.median(a))
4276
+ # check array scalar result
4277
+ assert_equal(np.median(a).ndim, 0)
4278
+ a[1] = np.nan
4279
+ assert_equal(np.median(a).ndim, 0)
4280
+
4281
+ def test_axis_keyword(self):
4282
+ a3 = np.array([[2, 3],
4283
+ [0, 1],
4284
+ [6, 7],
4285
+ [4, 5]])
4286
+ for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:
4287
+ orig = a.copy()
4288
+ np.median(a, axis=None)
4289
+ for ax in range(a.ndim):
4290
+ np.median(a, axis=ax)
4291
+ assert_array_equal(a, orig)
4292
+
4293
+ assert_allclose(np.median(a3, axis=0), [3, 4])
4294
+ assert_allclose(np.median(a3.T, axis=1), [3, 4])
4295
+ assert_allclose(np.median(a3), 3.5)
4296
+ assert_allclose(np.median(a3, axis=None), 3.5)
4297
+ assert_allclose(np.median(a3.T), 3.5)
4298
+
4299
+ def test_overwrite_keyword(self):
4300
+ a3 = np.array([[2, 3],
4301
+ [0, 1],
4302
+ [6, 7],
4303
+ [4, 5]])
4304
+ a0 = np.array(1)
4305
+ a1 = np.arange(2)
4306
+ a2 = np.arange(6).reshape(2, 3)
4307
+ assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)
4308
+ assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)
4309
+ assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)
4310
+ assert_allclose(
4311
+ np.median(a2.copy(), overwrite_input=True, axis=0), [1.5, 2.5, 3.5])
4312
+ assert_allclose(
4313
+ np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])
4314
+ assert_allclose(
4315
+ np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)
4316
+ assert_allclose(
4317
+ np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4])
4318
+ assert_allclose(
4319
+ np.median(a3.T.copy(), overwrite_input=True, axis=1), [3, 4])
4320
+
4321
+ a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
4322
+ np.random.shuffle(a4.ravel())
4323
+ assert_allclose(np.median(a4, axis=None),
4324
+ np.median(a4.copy(), axis=None, overwrite_input=True))
4325
+ assert_allclose(np.median(a4, axis=0),
4326
+ np.median(a4.copy(), axis=0, overwrite_input=True))
4327
+ assert_allclose(np.median(a4, axis=1),
4328
+ np.median(a4.copy(), axis=1, overwrite_input=True))
4329
+ assert_allclose(np.median(a4, axis=2),
4330
+ np.median(a4.copy(), axis=2, overwrite_input=True))
4331
+
4332
+ def test_array_like(self):
4333
+ x = [1, 2, 3]
4334
+ assert_almost_equal(np.median(x), 2)
4335
+ x2 = [x]
4336
+ assert_almost_equal(np.median(x2), 2)
4337
+ assert_allclose(np.median(x2, axis=0), x)
4338
+
4339
+ def test_subclass(self):
4340
+ # gh-3846
4341
+ class MySubClass(np.ndarray):
4342
+
4343
+ def __new__(cls, input_array, info=None):
4344
+ obj = np.asarray(input_array).view(cls)
4345
+ obj.info = info
4346
+ return obj
4347
+
4348
+ def mean(self, axis=None, dtype=None, out=None):
4349
+ return -7
4350
+
4351
+ a = MySubClass([1, 2, 3])
4352
+ assert_equal(np.median(a), -7)
4353
+
4354
+ @pytest.mark.parametrize('arr',
4355
+ ([1., 2., 3.], [1., np.nan, 3.], np.nan, 0.))
4356
+ def test_subclass2(self, arr):
4357
+ """Check that we return subclasses, even if a NaN scalar."""
4358
+ class MySubclass(np.ndarray):
4359
+ pass
4360
+
4361
+ m = np.median(np.array(arr).view(MySubclass))
4362
+ assert isinstance(m, MySubclass)
4363
+
4364
+ def test_out(self):
4365
+ o = np.zeros((4,))
4366
+ d = np.ones((3, 4))
4367
+ assert_equal(np.median(d, 0, out=o), o)
4368
+ o = np.zeros((3,))
4369
+ assert_equal(np.median(d, 1, out=o), o)
4370
+ o = np.zeros(())
4371
+ assert_equal(np.median(d, out=o), o)
4372
+
4373
+ def test_out_nan(self):
4374
+ with warnings.catch_warnings(record=True):
4375
+ warnings.filterwarnings('always', '', RuntimeWarning)
4376
+ o = np.zeros((4,))
4377
+ d = np.ones((3, 4))
4378
+ d[2, 1] = np.nan
4379
+ assert_equal(np.median(d, 0, out=o), o)
4380
+ o = np.zeros((3,))
4381
+ assert_equal(np.median(d, 1, out=o), o)
4382
+ o = np.zeros(())
4383
+ assert_equal(np.median(d, out=o), o)
4384
+
4385
+ def test_nan_behavior(self):
4386
+ a = np.arange(24, dtype=float)
4387
+ a[2] = np.nan
4388
+ assert_equal(np.median(a), np.nan)
4389
+ assert_equal(np.median(a, axis=0), np.nan)
4390
+
4391
+ a = np.arange(24, dtype=float).reshape(2, 3, 4)
4392
+ a[1, 2, 3] = np.nan
4393
+ a[1, 1, 2] = np.nan
4394
+
4395
+ # no axis
4396
+ assert_equal(np.median(a), np.nan)
4397
+ assert_equal(np.median(a).ndim, 0)
4398
+
4399
+ # axis0
4400
+ b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 0)
4401
+ b[2, 3] = np.nan
4402
+ b[1, 2] = np.nan
4403
+ assert_equal(np.median(a, 0), b)
4404
+
4405
+ # axis1
4406
+ b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 1)
4407
+ b[1, 3] = np.nan
4408
+ b[1, 2] = np.nan
4409
+ assert_equal(np.median(a, 1), b)
4410
+
4411
+ # axis02
4412
+ b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), (0, 2))
4413
+ b[1] = np.nan
4414
+ b[2] = np.nan
4415
+ assert_equal(np.median(a, (0, 2)), b)
4416
+
4417
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work correctly")
4418
+ def test_empty(self):
4419
+ # mean(empty array) emits two warnings: empty slice and divide by 0
4420
+ a = np.array([], dtype=float)
4421
+ with warnings.catch_warnings(record=True) as w:
4422
+ warnings.filterwarnings('always', '', RuntimeWarning)
4423
+ assert_equal(np.median(a), np.nan)
4424
+ assert_(w[0].category is RuntimeWarning)
4425
+ assert_equal(len(w), 2)
4426
+
4427
+ # multiple dimensions
4428
+ a = np.array([], dtype=float, ndmin=3)
4429
+ # no axis
4430
+ with warnings.catch_warnings(record=True) as w:
4431
+ warnings.filterwarnings('always', '', RuntimeWarning)
4432
+ assert_equal(np.median(a), np.nan)
4433
+ assert_(w[0].category is RuntimeWarning)
4434
+
4435
+ # axis 0 and 1
4436
+ b = np.array([], dtype=float, ndmin=2)
4437
+ assert_equal(np.median(a, axis=0), b)
4438
+ assert_equal(np.median(a, axis=1), b)
4439
+
4440
+ # axis 2
4441
+ b = np.array(np.nan, dtype=float, ndmin=2)
4442
+ with warnings.catch_warnings(record=True) as w:
4443
+ warnings.filterwarnings('always', '', RuntimeWarning)
4444
+ assert_equal(np.median(a, axis=2), b)
4445
+ assert_(w[0].category is RuntimeWarning)
4446
+
4447
+ def test_object(self):
4448
+ o = np.arange(7.)
4449
+ assert_(type(np.median(o.astype(object))), float)
4450
+ o[2] = np.nan
4451
+ assert_(type(np.median(o.astype(object))), float)
4452
+
4453
+ def test_extended_axis(self):
4454
+ o = np.random.normal(size=(71, 23))
4455
+ x = np.dstack([o] * 10)
4456
+ assert_equal(np.median(x, axis=(0, 1)), np.median(o))
4457
+ x = np.moveaxis(x, -1, 0)
4458
+ assert_equal(np.median(x, axis=(-2, -1)), np.median(o))
4459
+ x = x.swapaxes(0, 1).copy()
4460
+ assert_equal(np.median(x, axis=(0, -1)), np.median(o))
4461
+
4462
+ assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))
4463
+ assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))
4464
+ assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))
4465
+
4466
+ d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
4467
+ np.random.shuffle(d.ravel())
4468
+ assert_equal(np.median(d, axis=(0, 1, 2))[0],
4469
+ np.median(d[:, :, :, 0].flatten()))
4470
+ assert_equal(np.median(d, axis=(0, 1, 3))[1],
4471
+ np.median(d[:, :, 1, :].flatten()))
4472
+ assert_equal(np.median(d, axis=(3, 1, -4))[2],
4473
+ np.median(d[:, :, 2, :].flatten()))
4474
+ assert_equal(np.median(d, axis=(3, 1, 2))[2],
4475
+ np.median(d[2, :, :, :].flatten()))
4476
+ assert_equal(np.median(d, axis=(3, 2))[2, 1],
4477
+ np.median(d[2, 1, :, :].flatten()))
4478
+ assert_equal(np.median(d, axis=(1, -2))[2, 1],
4479
+ np.median(d[2, :, :, 1].flatten()))
4480
+ assert_equal(np.median(d, axis=(1, 3))[2, 2],
4481
+ np.median(d[2, :, 2, :].flatten()))
4482
+
4483
+ def test_extended_axis_invalid(self):
4484
+ d = np.ones((3, 5, 7, 11))
4485
+ assert_raises(AxisError, np.median, d, axis=-5)
4486
+ assert_raises(AxisError, np.median, d, axis=(0, -5))
4487
+ assert_raises(AxisError, np.median, d, axis=4)
4488
+ assert_raises(AxisError, np.median, d, axis=(0, 4))
4489
+ assert_raises(ValueError, np.median, d, axis=(1, 1))
4490
+
4491
+ def test_keepdims(self):
4492
+ d = np.ones((3, 5, 7, 11))
4493
+ assert_equal(np.median(d, axis=None, keepdims=True).shape,
4494
+ (1, 1, 1, 1))
4495
+ assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape,
4496
+ (1, 1, 7, 11))
4497
+ assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape,
4498
+ (1, 5, 7, 1))
4499
+ assert_equal(np.median(d, axis=(1,), keepdims=True).shape,
4500
+ (3, 1, 7, 11))
4501
+ assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape,
4502
+ (1, 1, 1, 1))
4503
+ assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape,
4504
+ (1, 1, 7, 1))
4505
+
4506
+ @pytest.mark.parametrize(
4507
+ argnames='axis',
4508
+ argvalues=[
4509
+ None,
4510
+ 1,
4511
+ (1, ),
4512
+ (0, 1),
4513
+ (-3, -1),
4514
+ ]
4515
+ )
4516
+ def test_keepdims_out(self, axis):
4517
+ d = np.ones((3, 5, 7, 11))
4518
+ if axis is None:
4519
+ shape_out = (1,) * d.ndim
4520
+ else:
4521
+ axis_norm = normalize_axis_tuple(axis, d.ndim)
4522
+ shape_out = tuple(
4523
+ 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
4524
+ out = np.empty(shape_out)
4525
+ result = np.median(d, axis=axis, keepdims=True, out=out)
4526
+ assert result is out
4527
+ assert_equal(result.shape, shape_out)
4528
+
4529
+ @pytest.mark.parametrize("dtype", ["m8[s]"])
4530
+ @pytest.mark.parametrize("pos", [0, 23, 10])
4531
+ def test_nat_behavior(self, dtype, pos):
4532
+ # TODO: Median does not support Datetime, due to `mean`.
4533
+ # NaT and NaN should behave the same, do basic tests for NaT.
4534
+ a = np.arange(0, 24, dtype=dtype)
4535
+ a[pos] = "NaT"
4536
+ res = np.median(a)
4537
+ assert res.dtype == dtype
4538
+ assert np.isnat(res)
4539
+ res = np.percentile(a, [30, 60])
4540
+ assert res.dtype == dtype
4541
+ assert np.isnat(res).all()
4542
+
4543
+ a = np.arange(0, 24 * 3, dtype=dtype).reshape(-1, 3)
4544
+ a[pos, 1] = "NaT"
4545
+ res = np.median(a, axis=0)
4546
+ assert_array_equal(np.isnat(res), [False, True, False])
4547
+
4548
+
4549
+ class TestSortComplex:
4550
+
4551
+ @pytest.mark.parametrize("type_in, type_out", [
4552
+ ('l', 'D'),
4553
+ ('h', 'F'),
4554
+ ('H', 'F'),
4555
+ ('b', 'F'),
4556
+ ('B', 'F'),
4557
+ ('g', 'G'),
4558
+ ])
4559
+ def test_sort_real(self, type_in, type_out):
4560
+ # sort_complex() type casting for real input types
4561
+ a = np.array([5, 3, 6, 2, 1], dtype=type_in)
4562
+ actual = np.sort_complex(a)
4563
+ expected = np.sort(a).astype(type_out)
4564
+ assert_equal(actual, expected)
4565
+ assert_equal(actual.dtype, expected.dtype)
4566
+
4567
+ def test_sort_complex(self):
4568
+ # sort_complex() handling of complex input
4569
+ a = np.array([2 + 3j, 1 - 2j, 1 - 3j, 2 + 1j], dtype='D')
4570
+ expected = np.array([1 - 3j, 1 - 2j, 2 + 1j, 2 + 3j], dtype='D')
4571
+ actual = np.sort_complex(a)
4572
+ assert_equal(actual, expected)
4573
+ assert_equal(actual.dtype, expected.dtype)