numpy 2.4.0__cp314-cp314-macosx_14_0_x86_64.whl

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