numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,4269 @@
1
+ """Module containing non-deprecated functions borrowed from Numeric.
2
+
3
+ """
4
+ import functools
5
+ import types
6
+ import warnings
7
+
8
+ import numpy as np
9
+ from numpy._utils import set_module
10
+
11
+ from . import _methods, overrides
12
+ from . import multiarray as mu
13
+ from . import numerictypes as nt
14
+ from . import umath as um
15
+ from ._multiarray_umath import _array_converter
16
+ from .multiarray import asanyarray, asarray, concatenate
17
+
18
+ _dt_ = nt.sctype2char
19
+
20
+ # functions that are methods
21
+ __all__ = [
22
+ 'all', 'amax', 'amin', 'any', 'argmax',
23
+ 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
24
+ 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
25
+ 'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
26
+ 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
27
+ 'ravel', 'repeat', 'reshape', 'resize', 'round',
28
+ 'searchsorted', 'shape', 'size', 'sort', 'squeeze',
29
+ 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
30
+ ]
31
+
32
+ _gentype = types.GeneratorType
33
+ # save away Python sum
34
+ _sum_ = sum
35
+
36
+ array_function_dispatch = functools.partial(
37
+ overrides.array_function_dispatch, module='numpy')
38
+
39
+
40
+ # functions that are now methods
41
+ def _wrapit(obj, method, *args, **kwds):
42
+ conv = _array_converter(obj)
43
+ # As this already tried the method, subok is maybe quite reasonable here
44
+ # but this follows what was done before. TODO: revisit this.
45
+ arr, = conv.as_arrays(subok=False)
46
+ result = getattr(arr, method)(*args, **kwds)
47
+
48
+ return conv.wrap(result, to_scalar=False)
49
+
50
+
51
+ def _wrapfunc(obj, method, *args, **kwds):
52
+ bound = getattr(obj, method, None)
53
+ if bound is None:
54
+ return _wrapit(obj, method, *args, **kwds)
55
+
56
+ try:
57
+ return bound(*args, **kwds)
58
+ except TypeError:
59
+ # A TypeError occurs if the object does have such a method in its
60
+ # class, but its signature is not identical to that of NumPy's. This
61
+ # situation has occurred in the case of a downstream library like
62
+ # 'pandas'.
63
+ #
64
+ # Call _wrapit from within the except clause to ensure a potential
65
+ # exception has a traceback chain.
66
+ return _wrapit(obj, method, *args, **kwds)
67
+
68
+
69
+ def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
70
+ passkwargs = {k: v for k, v in kwargs.items()
71
+ if v is not np._NoValue}
72
+
73
+ if type(obj) is not mu.ndarray:
74
+ try:
75
+ reduction = getattr(obj, method)
76
+ except AttributeError:
77
+ pass
78
+ else:
79
+ # This branch is needed for reductions like any which don't
80
+ # support a dtype.
81
+ if dtype is not None:
82
+ return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
83
+ else:
84
+ return reduction(axis=axis, out=out, **passkwargs)
85
+
86
+ return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
87
+
88
+
89
+ def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs):
90
+ # Same as above function, but dtype is always bool (but never passed on)
91
+ passkwargs = {k: v for k, v in kwargs.items()
92
+ if v is not np._NoValue}
93
+
94
+ if type(obj) is not mu.ndarray:
95
+ try:
96
+ reduction = getattr(obj, method)
97
+ except AttributeError:
98
+ pass
99
+ else:
100
+ return reduction(axis=axis, out=out, **passkwargs)
101
+
102
+ return ufunc.reduce(obj, axis, bool, out, **passkwargs)
103
+
104
+
105
+ def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
106
+ return (a, out)
107
+
108
+
109
+ @array_function_dispatch(_take_dispatcher)
110
+ def take(a, indices, axis=None, out=None, mode='raise'):
111
+ """
112
+ Take elements from an array along an axis.
113
+
114
+ When axis is not None, this function does the same thing as "fancy"
115
+ indexing (indexing arrays using arrays); however, it can be easier to use
116
+ if you need elements along a given axis. A call such as
117
+ ``np.take(arr, indices, axis=3)`` is equivalent to
118
+ ``arr[:,:,:,indices,...]``.
119
+
120
+ Explained without fancy indexing, this is equivalent to the following use
121
+ of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
122
+ indices::
123
+
124
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
125
+ Nj = indices.shape
126
+ for ii in ndindex(Ni):
127
+ for jj in ndindex(Nj):
128
+ for kk in ndindex(Nk):
129
+ out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
130
+
131
+ Parameters
132
+ ----------
133
+ a : array_like (Ni..., M, Nk...)
134
+ The source array.
135
+ indices : array_like (Nj...)
136
+ The indices of the values to extract.
137
+ Also allow scalars for indices.
138
+ axis : int, optional
139
+ The axis over which to select values. By default, the flattened
140
+ input array is used.
141
+ out : ndarray, optional (Ni..., Nj..., Nk...)
142
+ If provided, the result will be placed in this array. It should
143
+ be of the appropriate shape and dtype. Note that `out` is always
144
+ buffered if `mode='raise'`; use other modes for better performance.
145
+ mode : {'raise', 'wrap', 'clip'}, optional
146
+ Specifies how out-of-bounds indices will behave.
147
+
148
+ * 'raise' -- raise an error (default)
149
+ * 'wrap' -- wrap around
150
+ * 'clip' -- clip to the range
151
+
152
+ 'clip' mode means that all indices that are too large are replaced
153
+ by the index that addresses the last element along that axis. Note
154
+ that this disables indexing with negative numbers.
155
+
156
+ Returns
157
+ -------
158
+ out : ndarray (Ni..., Nj..., Nk...)
159
+ The returned array has the same type as `a`.
160
+
161
+ See Also
162
+ --------
163
+ compress : Take elements using a boolean mask
164
+ ndarray.take : equivalent method
165
+ take_along_axis : Take elements by matching the array and the index arrays
166
+
167
+ Notes
168
+ -----
169
+ By eliminating the inner loop in the description above, and using `s_` to
170
+ build simple slice objects, `take` can be expressed in terms of applying
171
+ fancy indexing to each 1-d slice::
172
+
173
+ Ni, Nk = a.shape[:axis], a.shape[axis+1:]
174
+ for ii in ndindex(Ni):
175
+ for kk in ndindex(Nj):
176
+ out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
177
+
178
+ For this reason, it is equivalent to (but faster than) the following use
179
+ of `apply_along_axis`::
180
+
181
+ out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
182
+
183
+ Examples
184
+ --------
185
+ >>> import numpy as np
186
+ >>> a = [4, 3, 5, 7, 6, 8]
187
+ >>> indices = [0, 1, 4]
188
+ >>> np.take(a, indices)
189
+ array([4, 3, 6])
190
+
191
+ In this example if `a` is an ndarray, "fancy" indexing can be used.
192
+
193
+ >>> a = np.array(a)
194
+ >>> a[indices]
195
+ array([4, 3, 6])
196
+
197
+ If `indices` is not one dimensional, the output also has these dimensions.
198
+
199
+ >>> np.take(a, [[0, 1], [2, 3]])
200
+ array([[4, 3],
201
+ [5, 7]])
202
+ """
203
+ return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
204
+
205
+
206
+ def _reshape_dispatcher(a, /, shape=None, order=None, *, newshape=None,
207
+ copy=None):
208
+ return (a,)
209
+
210
+
211
+ @array_function_dispatch(_reshape_dispatcher)
212
+ def reshape(a, /, shape=None, order='C', *, newshape=None, copy=None):
213
+ """
214
+ Gives a new shape to an array without changing its data.
215
+
216
+ Parameters
217
+ ----------
218
+ a : array_like
219
+ Array to be reshaped.
220
+ shape : int or tuple of ints
221
+ The new shape should be compatible with the original shape. If
222
+ an integer, then the result will be a 1-D array of that length.
223
+ One shape dimension can be -1. In this case, the value is
224
+ inferred from the length of the array and remaining dimensions.
225
+ order : {'C', 'F', 'A'}, optional
226
+ Read the elements of ``a`` using this index order, and place the
227
+ elements into the reshaped array using this index order. 'C'
228
+ means to read / write the elements using C-like index order,
229
+ with the last axis index changing fastest, back to the first
230
+ axis index changing slowest. 'F' means to read / write the
231
+ elements using Fortran-like index order, with the first index
232
+ changing fastest, and the last index changing slowest. Note that
233
+ the 'C' and 'F' options take no account of the memory layout of
234
+ the underlying array, and only refer to the order of indexing.
235
+ 'A' means to read / write the elements in Fortran-like index
236
+ order if ``a`` is Fortran *contiguous* in memory, C-like order
237
+ otherwise.
238
+ newshape : int or tuple of ints
239
+ .. deprecated:: 2.1
240
+ Replaced by ``shape`` argument. Retained for backward
241
+ compatibility.
242
+ copy : bool, optional
243
+ If ``True``, then the array data is copied. If ``None``, a copy will
244
+ only be made if it's required by ``order``. For ``False`` it raises
245
+ a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
246
+
247
+ Returns
248
+ -------
249
+ reshaped_array : ndarray
250
+ This will be a new view object if possible; otherwise, it will
251
+ be a copy. Note there is no guarantee of the *memory layout* (C- or
252
+ Fortran- contiguous) of the returned array.
253
+
254
+ See Also
255
+ --------
256
+ ndarray.reshape : Equivalent method.
257
+
258
+ Notes
259
+ -----
260
+ It is not always possible to change the shape of an array without copying
261
+ the data.
262
+
263
+ The ``order`` keyword gives the index ordering both for *fetching*
264
+ the values from ``a``, and then *placing* the values into the output
265
+ array. For example, let's say you have an array:
266
+
267
+ >>> a = np.arange(6).reshape((3, 2))
268
+ >>> a
269
+ array([[0, 1],
270
+ [2, 3],
271
+ [4, 5]])
272
+
273
+ You can think of reshaping as first raveling the array (using the given
274
+ index order), then inserting the elements from the raveled array into the
275
+ new array using the same kind of index ordering as was used for the
276
+ raveling.
277
+
278
+ >>> np.reshape(a, (2, 3)) # C-like index ordering
279
+ array([[0, 1, 2],
280
+ [3, 4, 5]])
281
+ >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
282
+ array([[0, 1, 2],
283
+ [3, 4, 5]])
284
+ >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
285
+ array([[0, 4, 3],
286
+ [2, 1, 5]])
287
+ >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
288
+ array([[0, 4, 3],
289
+ [2, 1, 5]])
290
+
291
+ Examples
292
+ --------
293
+ >>> import numpy as np
294
+ >>> a = np.array([[1,2,3], [4,5,6]])
295
+ >>> np.reshape(a, 6)
296
+ array([1, 2, 3, 4, 5, 6])
297
+ >>> np.reshape(a, 6, order='F')
298
+ array([1, 4, 2, 5, 3, 6])
299
+
300
+ >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
301
+ array([[1, 2],
302
+ [3, 4],
303
+ [5, 6]])
304
+ """
305
+ if newshape is None and shape is None:
306
+ raise TypeError(
307
+ "reshape() missing 1 required positional argument: 'shape'")
308
+ if newshape is not None:
309
+ if shape is not None:
310
+ raise TypeError(
311
+ "You cannot specify 'newshape' and 'shape' arguments "
312
+ "at the same time.")
313
+ # Deprecated in NumPy 2.1, 2024-04-18
314
+ warnings.warn(
315
+ "`newshape` keyword argument is deprecated, "
316
+ "use `shape=...` or pass shape positionally instead. "
317
+ "(deprecated in NumPy 2.1)",
318
+ DeprecationWarning,
319
+ stacklevel=2,
320
+ )
321
+ shape = newshape
322
+ if copy is not None:
323
+ return _wrapfunc(a, 'reshape', shape, order=order, copy=copy)
324
+ return _wrapfunc(a, 'reshape', shape, order=order)
325
+
326
+
327
+ def _choose_dispatcher(a, choices, out=None, mode=None):
328
+ yield a
329
+ yield from choices
330
+ yield out
331
+
332
+
333
+ @array_function_dispatch(_choose_dispatcher)
334
+ def choose(a, choices, out=None, mode='raise'):
335
+ """
336
+ Construct an array from an index array and a list of arrays to choose from.
337
+
338
+ First of all, if confused or uncertain, definitely look at the Examples -
339
+ in its full generality, this function is less simple than it might
340
+ seem from the following code description::
341
+
342
+ np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])
343
+
344
+ But this omits some subtleties. Here is a fully general summary:
345
+
346
+ Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
347
+ (`choices`), `a` and each choice array are first broadcast, as necessary,
348
+ to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
349
+ 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
350
+ for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
351
+ follows:
352
+
353
+ * if ``mode='raise'`` (the default), then, first of all, each element of
354
+ ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
355
+ that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
356
+ position in ``Ba`` - then the value at the same position in the new array
357
+ is the value in ``Bchoices[i]`` at that same position;
358
+
359
+ * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
360
+ integer; modular arithmetic is used to map integers outside the range
361
+ `[0, n-1]` back into that range; and then the new array is constructed
362
+ as above;
363
+
364
+ * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
365
+ integer; negative integers are mapped to 0; values greater than ``n-1``
366
+ are mapped to ``n-1``; and then the new array is constructed as above.
367
+
368
+ Parameters
369
+ ----------
370
+ a : int array
371
+ This array must contain integers in ``[0, n-1]``, where ``n`` is the
372
+ number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
373
+ cases any integers are permissible.
374
+ choices : sequence of arrays
375
+ Choice arrays. `a` and all of the choices must be broadcastable to the
376
+ same shape. If `choices` is itself an array (not recommended), then
377
+ its outermost dimension (i.e., the one corresponding to
378
+ ``choices.shape[0]``) is taken as defining the "sequence".
379
+ out : array, optional
380
+ If provided, the result will be inserted into this array. It should
381
+ be of the appropriate shape and dtype. Note that `out` is always
382
+ buffered if ``mode='raise'``; use other modes for better performance.
383
+ mode : {'raise' (default), 'wrap', 'clip'}, optional
384
+ Specifies how indices outside ``[0, n-1]`` will be treated:
385
+
386
+ * 'raise' : an exception is raised
387
+ * 'wrap' : value becomes value mod ``n``
388
+ * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
389
+
390
+ Returns
391
+ -------
392
+ merged_array : array
393
+ The merged result.
394
+
395
+ Raises
396
+ ------
397
+ ValueError: shape mismatch
398
+ If `a` and each choice array are not all broadcastable to the same
399
+ shape.
400
+
401
+ See Also
402
+ --------
403
+ ndarray.choose : equivalent method
404
+ numpy.take_along_axis : Preferable if `choices` is an array
405
+
406
+ Notes
407
+ -----
408
+ To reduce the chance of misinterpretation, even though the following
409
+ "abuse" is nominally supported, `choices` should neither be, nor be
410
+ thought of as, a single array, i.e., the outermost sequence-like container
411
+ should be either a list or a tuple.
412
+
413
+ Examples
414
+ --------
415
+
416
+ >>> import numpy as np
417
+ >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
418
+ ... [20, 21, 22, 23], [30, 31, 32, 33]]
419
+ >>> np.choose([2, 3, 1, 0], choices
420
+ ... # the first element of the result will be the first element of the
421
+ ... # third (2+1) "array" in choices, namely, 20; the second element
422
+ ... # will be the second element of the fourth (3+1) choice array, i.e.,
423
+ ... # 31, etc.
424
+ ... )
425
+ array([20, 31, 12, 3])
426
+ >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
427
+ array([20, 31, 12, 3])
428
+ >>> # because there are 4 choice arrays
429
+ >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
430
+ array([20, 1, 12, 3])
431
+ >>> # i.e., 0
432
+
433
+ A couple examples illustrating how choose broadcasts:
434
+
435
+ >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
436
+ >>> choices = [-10, 10]
437
+ >>> np.choose(a, choices)
438
+ array([[ 10, -10, 10],
439
+ [-10, 10, -10],
440
+ [ 10, -10, 10]])
441
+
442
+ >>> # With thanks to Anne Archibald
443
+ >>> a = np.array([0, 1]).reshape((2,1,1))
444
+ >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
445
+ >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
446
+ >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
447
+ array([[[ 1, 1, 1, 1, 1],
448
+ [ 2, 2, 2, 2, 2],
449
+ [ 3, 3, 3, 3, 3]],
450
+ [[-1, -2, -3, -4, -5],
451
+ [-1, -2, -3, -4, -5],
452
+ [-1, -2, -3, -4, -5]]])
453
+
454
+ """
455
+ return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
456
+
457
+
458
+ def _repeat_dispatcher(a, repeats, axis=None):
459
+ return (a,)
460
+
461
+
462
+ @array_function_dispatch(_repeat_dispatcher)
463
+ def repeat(a, repeats, axis=None):
464
+ """
465
+ Repeat each element of an array after themselves
466
+
467
+ Parameters
468
+ ----------
469
+ a : array_like
470
+ Input array.
471
+ repeats : int or array of ints
472
+ The number of repetitions for each element. `repeats` is broadcasted
473
+ to fit the shape of the given axis.
474
+ axis : int, optional
475
+ The axis along which to repeat values. By default, use the
476
+ flattened input array, and return a flat output array.
477
+
478
+ Returns
479
+ -------
480
+ repeated_array : ndarray
481
+ Output array which has the same shape as `a`, except along
482
+ the given axis.
483
+
484
+ See Also
485
+ --------
486
+ tile : Tile an array.
487
+ unique : Find the unique elements of an array.
488
+
489
+ Examples
490
+ --------
491
+ >>> import numpy as np
492
+ >>> np.repeat(3, 4)
493
+ array([3, 3, 3, 3])
494
+ >>> x = np.array([[1,2],[3,4]])
495
+ >>> np.repeat(x, 2)
496
+ array([1, 1, 2, 2, 3, 3, 4, 4])
497
+ >>> np.repeat(x, 3, axis=1)
498
+ array([[1, 1, 1, 2, 2, 2],
499
+ [3, 3, 3, 4, 4, 4]])
500
+ >>> np.repeat(x, [1, 2], axis=0)
501
+ array([[1, 2],
502
+ [3, 4],
503
+ [3, 4]])
504
+
505
+ """
506
+ return _wrapfunc(a, 'repeat', repeats, axis=axis)
507
+
508
+
509
+ def _put_dispatcher(a, ind, v, mode=None):
510
+ return (a, ind, v)
511
+
512
+
513
+ @array_function_dispatch(_put_dispatcher)
514
+ def put(a, ind, v, mode='raise'):
515
+ """
516
+ Replaces specified elements of an array with given values.
517
+
518
+ The indexing works on the flattened target array. `put` is roughly
519
+ equivalent to:
520
+
521
+ ::
522
+
523
+ a.flat[ind] = v
524
+
525
+ Parameters
526
+ ----------
527
+ a : ndarray
528
+ Target array.
529
+ ind : array_like
530
+ Target indices, interpreted as integers.
531
+ v : array_like
532
+ Values to place in `a` at target indices. If `v` is shorter than
533
+ `ind` it will be repeated as necessary.
534
+ mode : {'raise', 'wrap', 'clip'}, optional
535
+ Specifies how out-of-bounds indices will behave.
536
+
537
+ * 'raise' -- raise an error (default)
538
+ * 'wrap' -- wrap around
539
+ * 'clip' -- clip to the range
540
+
541
+ 'clip' mode means that all indices that are too large are replaced
542
+ by the index that addresses the last element along that axis. Note
543
+ that this disables indexing with negative numbers. In 'raise' mode,
544
+ if an exception occurs the target array may still be modified.
545
+
546
+ See Also
547
+ --------
548
+ putmask, place
549
+ put_along_axis : Put elements by matching the array and the index arrays
550
+
551
+ Examples
552
+ --------
553
+ >>> import numpy as np
554
+ >>> a = np.arange(5)
555
+ >>> np.put(a, [0, 2], [-44, -55])
556
+ >>> a
557
+ array([-44, 1, -55, 3, 4])
558
+
559
+ >>> a = np.arange(5)
560
+ >>> np.put(a, 22, -5, mode='clip')
561
+ >>> a
562
+ array([ 0, 1, 2, 3, -5])
563
+
564
+ """
565
+ try:
566
+ put = a.put
567
+ except AttributeError as e:
568
+ raise TypeError(f"argument 1 must be numpy.ndarray, not {type(a)}") from e
569
+
570
+ return put(ind, v, mode=mode)
571
+
572
+
573
+ def _swapaxes_dispatcher(a, axis1, axis2):
574
+ return (a,)
575
+
576
+
577
+ @array_function_dispatch(_swapaxes_dispatcher)
578
+ def swapaxes(a, axis1, axis2):
579
+ """
580
+ Interchange two axes of an array.
581
+
582
+ Parameters
583
+ ----------
584
+ a : array_like
585
+ Input array.
586
+ axis1 : int
587
+ First axis.
588
+ axis2 : int
589
+ Second axis.
590
+
591
+ Returns
592
+ -------
593
+ a_swapped : ndarray
594
+ For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
595
+ returned; otherwise a new array is created. For earlier NumPy
596
+ versions a view of `a` is returned only if the order of the
597
+ axes is changed, otherwise the input array is returned.
598
+
599
+ Examples
600
+ --------
601
+ >>> import numpy as np
602
+ >>> x = np.array([[1,2,3]])
603
+ >>> np.swapaxes(x,0,1)
604
+ array([[1],
605
+ [2],
606
+ [3]])
607
+
608
+ >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
609
+ >>> x
610
+ array([[[0, 1],
611
+ [2, 3]],
612
+ [[4, 5],
613
+ [6, 7]]])
614
+
615
+ >>> np.swapaxes(x,0,2)
616
+ array([[[0, 4],
617
+ [2, 6]],
618
+ [[1, 5],
619
+ [3, 7]]])
620
+
621
+ """
622
+ return _wrapfunc(a, 'swapaxes', axis1, axis2)
623
+
624
+
625
+ def _transpose_dispatcher(a, axes=None):
626
+ return (a,)
627
+
628
+
629
+ @array_function_dispatch(_transpose_dispatcher)
630
+ def transpose(a, axes=None):
631
+ """
632
+ Returns an array with axes transposed.
633
+
634
+ For a 1-D array, this returns an unchanged view of the original array, as a
635
+ transposed vector is simply the same vector.
636
+ To convert a 1-D array into a 2-D column vector, an additional dimension
637
+ must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
638
+ ``a[:, np.newaxis]``.
639
+ For a 2-D array, this is the standard matrix transpose.
640
+ For an n-D array, if axes are given, their order indicates how the
641
+ axes are permuted (see Examples). If axes are not provided, then
642
+ ``transpose(a).shape == a.shape[::-1]``.
643
+
644
+ Parameters
645
+ ----------
646
+ a : array_like
647
+ Input array.
648
+ axes : tuple or list of ints, optional
649
+ If specified, it must be a tuple or list which contains a permutation
650
+ of [0, 1, ..., N-1] where N is the number of axes of `a`. Negative
651
+ indices can also be used to specify axes. The i-th axis of the returned
652
+ array will correspond to the axis numbered ``axes[i]`` of the input.
653
+ If not specified, defaults to ``range(a.ndim)[::-1]``, which reverses
654
+ the order of the axes.
655
+
656
+ Returns
657
+ -------
658
+ p : ndarray
659
+ `a` with its axes permuted. A view is returned whenever possible.
660
+
661
+ See Also
662
+ --------
663
+ ndarray.transpose : Equivalent method.
664
+ moveaxis : Move axes of an array to new positions.
665
+ argsort : Return the indices that would sort an array.
666
+
667
+ Notes
668
+ -----
669
+ Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
670
+ when using the `axes` keyword argument.
671
+
672
+ Examples
673
+ --------
674
+ >>> import numpy as np
675
+ >>> a = np.array([[1, 2], [3, 4]])
676
+ >>> a
677
+ array([[1, 2],
678
+ [3, 4]])
679
+ >>> np.transpose(a)
680
+ array([[1, 3],
681
+ [2, 4]])
682
+
683
+ >>> a = np.array([1, 2, 3, 4])
684
+ >>> a
685
+ array([1, 2, 3, 4])
686
+ >>> np.transpose(a)
687
+ array([1, 2, 3, 4])
688
+
689
+ >>> a = np.ones((1, 2, 3))
690
+ >>> np.transpose(a, (1, 0, 2)).shape
691
+ (2, 1, 3)
692
+
693
+ >>> a = np.ones((2, 3, 4, 5))
694
+ >>> np.transpose(a).shape
695
+ (5, 4, 3, 2)
696
+
697
+ >>> a = np.arange(3*4*5).reshape((3, 4, 5))
698
+ >>> np.transpose(a, (-1, 0, -2)).shape
699
+ (5, 3, 4)
700
+
701
+ """
702
+ return _wrapfunc(a, 'transpose', axes)
703
+
704
+
705
+ def _matrix_transpose_dispatcher(x):
706
+ return (x,)
707
+
708
+ @array_function_dispatch(_matrix_transpose_dispatcher)
709
+ def matrix_transpose(x, /):
710
+ """
711
+ Transposes a matrix (or a stack of matrices) ``x``.
712
+
713
+ This function is Array API compatible.
714
+
715
+ Parameters
716
+ ----------
717
+ x : array_like
718
+ Input array having shape (..., M, N) and whose two innermost
719
+ dimensions form ``MxN`` matrices.
720
+
721
+ Returns
722
+ -------
723
+ out : ndarray
724
+ An array containing the transpose for each matrix and having shape
725
+ (..., N, M).
726
+
727
+ See Also
728
+ --------
729
+ transpose : Generic transpose method.
730
+
731
+ Examples
732
+ --------
733
+ >>> import numpy as np
734
+ >>> np.matrix_transpose([[1, 2], [3, 4]])
735
+ array([[1, 3],
736
+ [2, 4]])
737
+
738
+ >>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
739
+ array([[[1, 3],
740
+ [2, 4]],
741
+ [[5, 7],
742
+ [6, 8]]])
743
+
744
+ """
745
+ x = asanyarray(x)
746
+ if x.ndim < 2:
747
+ raise ValueError(
748
+ f"Input array must be at least 2-dimensional, but it is {x.ndim}"
749
+ )
750
+ return swapaxes(x, -1, -2)
751
+
752
+
753
+ def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
754
+ return (a,)
755
+
756
+
757
+ @array_function_dispatch(_partition_dispatcher)
758
+ def partition(a, kth, axis=-1, kind='introselect', order=None):
759
+ """
760
+ Return a partitioned copy of an array.
761
+
762
+ Creates a copy of the array and partially sorts it in such a way that
763
+ the value of the element in k-th position is in the position it would be
764
+ in a sorted array. In the output array, all elements smaller than the k-th
765
+ element are located to the left of this element and all equal or greater
766
+ are located to its right. The ordering of the elements in the two
767
+ partitions on the either side of the k-th element in the output array is
768
+ undefined.
769
+
770
+ Parameters
771
+ ----------
772
+ a : array_like
773
+ Array to be sorted.
774
+ kth : int or sequence of ints
775
+ Element index to partition by. The k-th value of the element
776
+ will be in its final sorted position and all smaller elements
777
+ will be moved before it and all equal or greater elements behind
778
+ it. The order of all elements in the partitions is undefined. If
779
+ provided with a sequence of k-th it will partition all elements
780
+ indexed by k-th of them into their sorted position at once.
781
+
782
+ .. deprecated:: 1.22.0
783
+ Passing booleans as index is deprecated.
784
+ axis : int or None, optional
785
+ Axis along which to sort. If None, the array is flattened before
786
+ sorting. The default is -1, which sorts along the last axis.
787
+ kind : {'introselect'}, optional
788
+ Selection algorithm. Default is 'introselect'.
789
+ order : str or list of str, optional
790
+ When `a` is an array with fields defined, this argument
791
+ specifies which fields to compare first, second, etc. A single
792
+ field can be specified as a string. Not all fields need be
793
+ specified, but unspecified fields will still be used, in the
794
+ order in which they come up in the dtype, to break ties.
795
+
796
+ Returns
797
+ -------
798
+ partitioned_array : ndarray
799
+ Array of the same type and shape as `a`.
800
+
801
+ See Also
802
+ --------
803
+ ndarray.partition : Method to sort an array in-place.
804
+ argpartition : Indirect partition.
805
+ sort : Full sorting
806
+
807
+ Notes
808
+ -----
809
+ The various selection algorithms are characterized by their average
810
+ speed, worst case performance, work space size, and whether they are
811
+ stable. A stable sort keeps items with the same key in the same
812
+ relative order. The available algorithms have the following
813
+ properties:
814
+
815
+ ================= ======= ============= ============ =======
816
+ kind speed worst case work space stable
817
+ ================= ======= ============= ============ =======
818
+ 'introselect' 1 O(n) 0 no
819
+ ================= ======= ============= ============ =======
820
+
821
+ All the partition algorithms make temporary copies of the data when
822
+ partitioning along any but the last axis. Consequently,
823
+ partitioning along the last axis is faster and uses less space than
824
+ partitioning along any other axis.
825
+
826
+ The sort order for complex numbers is lexicographic. If both the
827
+ real and imaginary parts are non-nan then the order is determined by
828
+ the real parts except when they are equal, in which case the order
829
+ is determined by the imaginary parts.
830
+
831
+ The sort order of ``np.nan`` is bigger than ``np.inf``.
832
+
833
+ Examples
834
+ --------
835
+ >>> import numpy as np
836
+ >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
837
+ >>> p = np.partition(a, 4)
838
+ >>> p
839
+ array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
840
+
841
+ ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
842
+ to ``p[4]``, and all elements in ``p[5:]`` are greater than or
843
+ equal to ``p[4]``. The partition is::
844
+
845
+ [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
846
+
847
+ The next example shows the use of multiple values passed to `kth`.
848
+
849
+ >>> p2 = np.partition(a, (4, 8))
850
+ >>> p2
851
+ array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
852
+
853
+ ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
854
+ are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
855
+ are greater than or equal to ``p2[4]`` and less than or equal to
856
+ ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
857
+ equal to ``p2[8]``. The partition is::
858
+
859
+ [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
860
+ """
861
+ if axis is None:
862
+ # flatten returns (1, N) for np.matrix, so always use the last axis
863
+ a = asanyarray(a).flatten()
864
+ axis = -1
865
+ else:
866
+ a = asanyarray(a).copy(order="K")
867
+ a.partition(kth, axis=axis, kind=kind, order=order)
868
+ return a
869
+
870
+
871
+ def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
872
+ return (a,)
873
+
874
+
875
+ @array_function_dispatch(_argpartition_dispatcher)
876
+ def argpartition(a, kth, axis=-1, kind='introselect', order=None):
877
+ """
878
+ Perform an indirect partition along the given axis using the
879
+ algorithm specified by the `kind` keyword. It returns an array of
880
+ indices of the same shape as `a` that index data along the given
881
+ axis in partitioned order.
882
+
883
+ Parameters
884
+ ----------
885
+ a : array_like
886
+ Array to sort.
887
+ kth : int or sequence of ints
888
+ Element index to partition by. The k-th element will be in its
889
+ final sorted position and all smaller elements will be moved
890
+ before it and all larger elements behind it. The order of all
891
+ elements in the partitions is undefined. If provided with a
892
+ sequence of k-th it will partition all of them into their sorted
893
+ position at once.
894
+
895
+ .. deprecated:: 1.22.0
896
+ Passing booleans as index is deprecated.
897
+ axis : int or None, optional
898
+ Axis along which to sort. The default is -1 (the last axis). If
899
+ None, the flattened array is used.
900
+ kind : {'introselect'}, optional
901
+ Selection algorithm. Default is 'introselect'
902
+ order : str or list of str, optional
903
+ When `a` is an array with fields defined, this argument
904
+ specifies which fields to compare first, second, etc. A single
905
+ field can be specified as a string, and not all fields need be
906
+ specified, but unspecified fields will still be used, in the
907
+ order in which they come up in the dtype, to break ties.
908
+
909
+ Returns
910
+ -------
911
+ index_array : ndarray, int
912
+ Array of indices that partition `a` along the specified axis.
913
+ If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
914
+ More generally, ``np.take_along_axis(a, index_array, axis=axis)``
915
+ always yields the partitioned `a`, irrespective of dimensionality.
916
+
917
+ See Also
918
+ --------
919
+ partition : Describes partition algorithms used.
920
+ ndarray.partition : Inplace partition.
921
+ argsort : Full indirect sort.
922
+ take_along_axis : Apply ``index_array`` from argpartition
923
+ to an array as if by calling partition.
924
+
925
+ Notes
926
+ -----
927
+ The returned indices are not guaranteed to be sorted according to
928
+ the values. Furthermore, the default selection algorithm ``introselect``
929
+ is unstable, and hence the returned indices are not guaranteed
930
+ to be the earliest/latest occurrence of the element.
931
+
932
+ `argpartition` works for real/complex inputs with nan values,
933
+ see `partition` for notes on the enhanced sort order and
934
+ different selection algorithms.
935
+
936
+ Examples
937
+ --------
938
+ One dimensional array:
939
+
940
+ >>> import numpy as np
941
+ >>> x = np.array([3, 4, 2, 1])
942
+ >>> x[np.argpartition(x, 3)]
943
+ array([2, 1, 3, 4]) # may vary
944
+ >>> x[np.argpartition(x, (1, 3))]
945
+ array([1, 2, 3, 4]) # may vary
946
+
947
+ >>> x = [3, 4, 2, 1]
948
+ >>> np.array(x)[np.argpartition(x, 3)]
949
+ array([2, 1, 3, 4]) # may vary
950
+
951
+ Multi-dimensional array:
952
+
953
+ >>> x = np.array([[3, 4, 2], [1, 3, 1]])
954
+ >>> index_array = np.argpartition(x, kth=1, axis=-1)
955
+ >>> # below is the same as np.partition(x, kth=1)
956
+ >>> np.take_along_axis(x, index_array, axis=-1)
957
+ array([[2, 3, 4],
958
+ [1, 1, 3]])
959
+
960
+ """
961
+ return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
962
+
963
+
964
+ def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
965
+ return (a,)
966
+
967
+
968
+ @array_function_dispatch(_sort_dispatcher)
969
+ def sort(a, axis=-1, kind=None, order=None, *, stable=None):
970
+ """
971
+ Return a sorted copy of an array.
972
+
973
+ Parameters
974
+ ----------
975
+ a : array_like
976
+ Array to be sorted.
977
+ axis : int or None, optional
978
+ Axis along which to sort. If None, the array is flattened before
979
+ sorting. The default is -1, which sorts along the last axis.
980
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
981
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
982
+ and 'mergesort' use timsort or radix sort under the covers and,
983
+ in general, the actual implementation will vary with data type.
984
+ The 'mergesort' option is retained for backwards compatibility.
985
+ order : str or list of str, optional
986
+ When `a` is an array with fields defined, this argument specifies
987
+ which fields to compare first, second, etc. A single field can
988
+ be specified as a string, and not all fields need be specified,
989
+ but unspecified fields will still be used, in the order in which
990
+ they come up in the dtype, to break ties.
991
+ stable : bool, optional
992
+ Sort stability. If ``True``, the returned array will maintain
993
+ the relative order of ``a`` values which compare as equal.
994
+ If ``False`` or ``None``, this is not guaranteed. Internally,
995
+ this option selects ``kind='stable'``. Default: ``None``.
996
+
997
+ .. versionadded:: 2.0.0
998
+
999
+ Returns
1000
+ -------
1001
+ sorted_array : ndarray
1002
+ Array of the same type and shape as `a`.
1003
+
1004
+ See Also
1005
+ --------
1006
+ ndarray.sort : Method to sort an array in-place.
1007
+ argsort : Indirect sort.
1008
+ lexsort : Indirect stable sort on multiple keys.
1009
+ searchsorted : Find elements in a sorted array.
1010
+ partition : Partial sort.
1011
+
1012
+ Notes
1013
+ -----
1014
+ The various sorting algorithms are characterized by their average speed,
1015
+ worst case performance, work space size, and whether they are stable. A
1016
+ stable sort keeps items with the same key in the same relative
1017
+ order. The four algorithms implemented in NumPy have the following
1018
+ properties:
1019
+
1020
+ =========== ======= ============= ============ ========
1021
+ kind speed worst case work space stable
1022
+ =========== ======= ============= ============ ========
1023
+ 'quicksort' 1 O(n^2) 0 no
1024
+ 'heapsort' 3 O(n*log(n)) 0 no
1025
+ 'mergesort' 2 O(n*log(n)) ~n/2 yes
1026
+ 'timsort' 2 O(n*log(n)) ~n/2 yes
1027
+ =========== ======= ============= ============ ========
1028
+
1029
+ .. note:: The datatype determines which of 'mergesort' or 'timsort'
1030
+ is actually used, even if 'mergesort' is specified. User selection
1031
+ at a finer scale is not currently available.
1032
+
1033
+ For performance, ``sort`` makes a temporary copy if needed to make the data
1034
+ `contiguous <https://numpy.org/doc/stable/glossary.html#term-contiguous>`_
1035
+ in memory along the sort axis. For even better performance and reduced
1036
+ memory consumption, ensure that the array is already contiguous along the
1037
+ sort axis.
1038
+
1039
+ The sort order for complex numbers is lexicographic. If both the real
1040
+ and imaginary parts are non-nan then the order is determined by the
1041
+ real parts except when they are equal, in which case the order is
1042
+ determined by the imaginary parts.
1043
+
1044
+ Previous to numpy 1.4.0 sorting real and complex arrays containing nan
1045
+ values led to undefined behaviour. In numpy versions >= 1.4.0 nan
1046
+ values are sorted to the end. The extended sort order is:
1047
+
1048
+ * Real: [R, nan]
1049
+ * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
1050
+
1051
+ where R is a non-nan real value. Complex values with the same nan
1052
+ placements are sorted according to the non-nan part if it exists.
1053
+ Non-nan values are sorted as before.
1054
+
1055
+ quicksort has been changed to:
1056
+ `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
1057
+ When sorting does not make enough progress it switches to
1058
+ `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
1059
+ This implementation makes quicksort O(n*log(n)) in the worst case.
1060
+
1061
+ 'stable' automatically chooses the best stable sorting algorithm
1062
+ for the data type being sorted.
1063
+ It, along with 'mergesort' is currently mapped to
1064
+ `timsort <https://en.wikipedia.org/wiki/Timsort>`_
1065
+ or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
1066
+ depending on the data type.
1067
+ API forward compatibility currently limits the
1068
+ ability to select the implementation and it is hardwired for the different
1069
+ data types.
1070
+
1071
+ Timsort is added for better performance on already or nearly
1072
+ sorted data. On random data timsort is almost identical to
1073
+ mergesort. It is now used for stable sort while quicksort is still the
1074
+ default sort if none is chosen. For timsort details, refer to
1075
+ `CPython listsort.txt
1076
+ <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_
1077
+ 'mergesort' and 'stable' are mapped to radix sort for integer data types.
1078
+ Radix sort is an O(n) sort instead of O(n log n).
1079
+
1080
+ NaT now sorts to the end of arrays for consistency with NaN.
1081
+
1082
+ Examples
1083
+ --------
1084
+ >>> import numpy as np
1085
+ >>> a = np.array([[1,4],[3,1]])
1086
+ >>> np.sort(a) # sort along the last axis
1087
+ array([[1, 4],
1088
+ [1, 3]])
1089
+ >>> np.sort(a, axis=None) # sort the flattened array
1090
+ array([1, 1, 3, 4])
1091
+ >>> np.sort(a, axis=0) # sort along the first axis
1092
+ array([[1, 1],
1093
+ [3, 4]])
1094
+
1095
+ Use the `order` keyword to specify a field to use when sorting a
1096
+ structured array:
1097
+
1098
+ >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
1099
+ >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
1100
+ ... ('Galahad', 1.7, 38)]
1101
+ >>> a = np.array(values, dtype=dtype) # create a structured array
1102
+ >>> np.sort(a, order='height') # doctest: +SKIP
1103
+ array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
1104
+ ('Lancelot', 1.8999999999999999, 38)],
1105
+ dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1106
+
1107
+ Sort by age, then height if ages are equal:
1108
+
1109
+ >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
1110
+ array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
1111
+ ('Arthur', 1.8, 41)],
1112
+ dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1113
+
1114
+ """
1115
+ if axis is None:
1116
+ # flatten returns (1, N) for np.matrix, so always use the last axis
1117
+ a = asanyarray(a).flatten()
1118
+ axis = -1
1119
+ else:
1120
+ a = asanyarray(a).copy(order="K")
1121
+ a.sort(axis=axis, kind=kind, order=order, stable=stable)
1122
+ return a
1123
+
1124
+
1125
+ def _argsort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
1126
+ return (a,)
1127
+
1128
+
1129
+ @array_function_dispatch(_argsort_dispatcher)
1130
+ def argsort(a, axis=-1, kind=None, order=None, *, stable=None):
1131
+ """
1132
+ Returns the indices that would sort an array.
1133
+
1134
+ Perform an indirect sort along the given axis using the algorithm specified
1135
+ by the `kind` keyword. It returns an array of indices of the same shape as
1136
+ `a` that index data along the given axis in sorted order.
1137
+
1138
+ Parameters
1139
+ ----------
1140
+ a : array_like
1141
+ Array to sort.
1142
+ axis : int or None, optional
1143
+ Axis along which to sort. The default is -1 (the last axis). If None,
1144
+ the flattened array is used.
1145
+ kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
1146
+ Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
1147
+ and 'mergesort' use timsort under the covers and, in general, the
1148
+ actual implementation will vary with data type. The 'mergesort' option
1149
+ is retained for backwards compatibility.
1150
+ order : str or list of str, optional
1151
+ When `a` is an array with fields defined, this argument specifies
1152
+ which fields to compare first, second, etc. A single field can
1153
+ be specified as a string, and not all fields need be specified,
1154
+ but unspecified fields will still be used, in the order in which
1155
+ they come up in the dtype, to break ties.
1156
+ stable : bool, optional
1157
+ Sort stability. If ``True``, the returned array will maintain
1158
+ the relative order of ``a`` values which compare as equal.
1159
+ If ``False`` or ``None``, this is not guaranteed. Internally,
1160
+ this option selects ``kind='stable'``. Default: ``None``.
1161
+
1162
+ .. versionadded:: 2.0.0
1163
+
1164
+ Returns
1165
+ -------
1166
+ index_array : ndarray, int
1167
+ Array of indices that sort `a` along the specified `axis`.
1168
+ If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
1169
+ More generally, ``np.take_along_axis(a, index_array, axis=axis)``
1170
+ always yields the sorted `a`, irrespective of dimensionality.
1171
+
1172
+ See Also
1173
+ --------
1174
+ sort : Describes sorting algorithms used.
1175
+ lexsort : Indirect stable sort with multiple keys.
1176
+ ndarray.sort : Inplace sort.
1177
+ argpartition : Indirect partial sort.
1178
+ take_along_axis : Apply ``index_array`` from argsort
1179
+ to an array as if by calling sort.
1180
+
1181
+ Notes
1182
+ -----
1183
+ See `sort` for notes on the different sorting algorithms.
1184
+
1185
+ As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
1186
+ nan values. The enhanced sort order is documented in `sort`.
1187
+
1188
+ Examples
1189
+ --------
1190
+ One dimensional array:
1191
+
1192
+ >>> import numpy as np
1193
+ >>> x = np.array([3, 1, 2])
1194
+ >>> np.argsort(x)
1195
+ array([1, 2, 0])
1196
+
1197
+ Two-dimensional array:
1198
+
1199
+ >>> x = np.array([[0, 3], [2, 2]])
1200
+ >>> x
1201
+ array([[0, 3],
1202
+ [2, 2]])
1203
+
1204
+ >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
1205
+ >>> ind
1206
+ array([[0, 1],
1207
+ [1, 0]])
1208
+ >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
1209
+ array([[0, 2],
1210
+ [2, 3]])
1211
+
1212
+ >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
1213
+ >>> ind
1214
+ array([[0, 1],
1215
+ [0, 1]])
1216
+ >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
1217
+ array([[0, 3],
1218
+ [2, 2]])
1219
+
1220
+ Indices of the sorted elements of a N-dimensional array:
1221
+
1222
+ >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
1223
+ >>> ind
1224
+ (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
1225
+ >>> x[ind] # same as np.sort(x, axis=None)
1226
+ array([0, 2, 2, 3])
1227
+
1228
+ Sorting with keys:
1229
+
1230
+ >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
1231
+ >>> x
1232
+ array([(1, 0), (0, 1)],
1233
+ dtype=[('x', '<i4'), ('y', '<i4')])
1234
+
1235
+ >>> np.argsort(x, order=('x','y'))
1236
+ array([1, 0])
1237
+
1238
+ >>> np.argsort(x, order=('y','x'))
1239
+ array([0, 1])
1240
+
1241
+ """
1242
+ return _wrapfunc(
1243
+ a, 'argsort', axis=axis, kind=kind, order=order, stable=stable
1244
+ )
1245
+
1246
+ def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1247
+ return (a, out)
1248
+
1249
+
1250
+ @array_function_dispatch(_argmax_dispatcher)
1251
+ def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
1252
+ """
1253
+ Returns the indices of the maximum values along an axis.
1254
+
1255
+ Parameters
1256
+ ----------
1257
+ a : array_like
1258
+ Input array.
1259
+ axis : int, optional
1260
+ By default, the index is into the flattened array, otherwise
1261
+ along the specified axis.
1262
+ out : array, optional
1263
+ If provided, the result will be inserted into this array. It should
1264
+ be of the appropriate shape and dtype.
1265
+ keepdims : bool, optional
1266
+ If this is set to True, the axes which are reduced are left
1267
+ in the result as dimensions with size one. With this option,
1268
+ the result will broadcast correctly against the array.
1269
+
1270
+ .. versionadded:: 1.22.0
1271
+
1272
+ Returns
1273
+ -------
1274
+ index_array : ndarray of ints
1275
+ Array of indices into the array. It has the same shape as ``a.shape``
1276
+ with the dimension along `axis` removed. If `keepdims` is set to True,
1277
+ then the size of `axis` will be 1 with the resulting array having same
1278
+ shape as ``a.shape``.
1279
+
1280
+ See Also
1281
+ --------
1282
+ ndarray.argmax, argmin
1283
+ amax : The maximum value along a given axis.
1284
+ unravel_index : Convert a flat index into an index tuple.
1285
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1286
+ from argmax to an array as if by calling max.
1287
+
1288
+ Notes
1289
+ -----
1290
+ In case of multiple occurrences of the maximum values, the indices
1291
+ corresponding to the first occurrence are returned.
1292
+
1293
+ Examples
1294
+ --------
1295
+ >>> import numpy as np
1296
+ >>> a = np.arange(6).reshape(2,3) + 10
1297
+ >>> a
1298
+ array([[10, 11, 12],
1299
+ [13, 14, 15]])
1300
+ >>> np.argmax(a)
1301
+ 5
1302
+ >>> np.argmax(a, axis=0)
1303
+ array([1, 1, 1])
1304
+ >>> np.argmax(a, axis=1)
1305
+ array([2, 2])
1306
+
1307
+ Indexes of the maximal elements of a N-dimensional array:
1308
+
1309
+ >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
1310
+ >>> ind
1311
+ (1, 2)
1312
+ >>> a[ind]
1313
+ 15
1314
+
1315
+ >>> b = np.arange(6)
1316
+ >>> b[1] = 5
1317
+ >>> b
1318
+ array([0, 5, 2, 3, 4, 5])
1319
+ >>> np.argmax(b) # Only the first occurrence is returned.
1320
+ 1
1321
+
1322
+ >>> x = np.array([[4,2,3], [1,0,3]])
1323
+ >>> index_array = np.argmax(x, axis=-1)
1324
+ >>> # Same as np.amax(x, axis=-1, keepdims=True)
1325
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1326
+ array([[4],
1327
+ [3]])
1328
+ >>> # Same as np.amax(x, axis=-1)
1329
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
1330
+ ... axis=-1).squeeze(axis=-1)
1331
+ array([4, 3])
1332
+
1333
+ Setting `keepdims` to `True`,
1334
+
1335
+ >>> x = np.arange(24).reshape((2, 3, 4))
1336
+ >>> res = np.argmax(x, axis=1, keepdims=True)
1337
+ >>> res.shape
1338
+ (2, 1, 4)
1339
+ """
1340
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1341
+ return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
1342
+
1343
+
1344
+ def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1345
+ return (a, out)
1346
+
1347
+
1348
+ @array_function_dispatch(_argmin_dispatcher)
1349
+ def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
1350
+ """
1351
+ Returns the indices of the minimum values along an axis.
1352
+
1353
+ Parameters
1354
+ ----------
1355
+ a : array_like
1356
+ Input array.
1357
+ axis : int, optional
1358
+ By default, the index is into the flattened array, otherwise
1359
+ along the specified axis.
1360
+ out : array, optional
1361
+ If provided, the result will be inserted into this array. It should
1362
+ be of the appropriate shape and dtype.
1363
+ keepdims : bool, optional
1364
+ If this is set to True, the axes which are reduced are left
1365
+ in the result as dimensions with size one. With this option,
1366
+ the result will broadcast correctly against the array.
1367
+
1368
+ .. versionadded:: 1.22.0
1369
+
1370
+ Returns
1371
+ -------
1372
+ index_array : ndarray of ints
1373
+ Array of indices into the array. It has the same shape as `a.shape`
1374
+ with the dimension along `axis` removed. If `keepdims` is set to True,
1375
+ then the size of `axis` will be 1 with the resulting array having same
1376
+ shape as `a.shape`.
1377
+
1378
+ See Also
1379
+ --------
1380
+ ndarray.argmin, argmax
1381
+ amin : The minimum value along a given axis.
1382
+ unravel_index : Convert a flat index into an index tuple.
1383
+ take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1384
+ from argmin to an array as if by calling min.
1385
+
1386
+ Notes
1387
+ -----
1388
+ In case of multiple occurrences of the minimum values, the indices
1389
+ corresponding to the first occurrence are returned.
1390
+
1391
+ Examples
1392
+ --------
1393
+ >>> import numpy as np
1394
+ >>> a = np.arange(6).reshape(2,3) + 10
1395
+ >>> a
1396
+ array([[10, 11, 12],
1397
+ [13, 14, 15]])
1398
+ >>> np.argmin(a)
1399
+ 0
1400
+ >>> np.argmin(a, axis=0)
1401
+ array([0, 0, 0])
1402
+ >>> np.argmin(a, axis=1)
1403
+ array([0, 0])
1404
+
1405
+ Indices of the minimum elements of a N-dimensional array:
1406
+
1407
+ >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
1408
+ >>> ind
1409
+ (0, 0)
1410
+ >>> a[ind]
1411
+ 10
1412
+
1413
+ >>> b = np.arange(6) + 10
1414
+ >>> b[4] = 10
1415
+ >>> b
1416
+ array([10, 11, 12, 13, 10, 15])
1417
+ >>> np.argmin(b) # Only the first occurrence is returned.
1418
+ 0
1419
+
1420
+ >>> x = np.array([[4,2,3], [1,0,3]])
1421
+ >>> index_array = np.argmin(x, axis=-1)
1422
+ >>> # Same as np.amin(x, axis=-1, keepdims=True)
1423
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1424
+ array([[2],
1425
+ [0]])
1426
+ >>> # Same as np.amax(x, axis=-1)
1427
+ >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
1428
+ ... axis=-1).squeeze(axis=-1)
1429
+ array([2, 0])
1430
+
1431
+ Setting `keepdims` to `True`,
1432
+
1433
+ >>> x = np.arange(24).reshape((2, 3, 4))
1434
+ >>> res = np.argmin(x, axis=1, keepdims=True)
1435
+ >>> res.shape
1436
+ (2, 1, 4)
1437
+ """
1438
+ kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1439
+ return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
1440
+
1441
+
1442
+ def _searchsorted_dispatcher(a, v, side=None, sorter=None):
1443
+ return (a, v, sorter)
1444
+
1445
+
1446
+ @array_function_dispatch(_searchsorted_dispatcher)
1447
+ def searchsorted(a, v, side='left', sorter=None):
1448
+ """
1449
+ Find indices where elements should be inserted to maintain order.
1450
+
1451
+ Find the indices into a sorted array `a` such that, if the
1452
+ corresponding elements in `v` were inserted before the indices, the
1453
+ order of `a` would be preserved.
1454
+
1455
+ Assuming that `a` is sorted:
1456
+
1457
+ ====== ============================
1458
+ `side` returned index `i` satisfies
1459
+ ====== ============================
1460
+ left ``a[i-1] < v <= a[i]``
1461
+ right ``a[i-1] <= v < a[i]``
1462
+ ====== ============================
1463
+
1464
+ Parameters
1465
+ ----------
1466
+ a : 1-D array_like
1467
+ Input array. If `sorter` is None, then it must be sorted in
1468
+ ascending order, otherwise `sorter` must be an array of indices
1469
+ that sort it.
1470
+ v : array_like
1471
+ Values to insert into `a`.
1472
+ side : {'left', 'right'}, optional
1473
+ If 'left', the index of the first suitable location found is given.
1474
+ If 'right', return the last such index. If there is no suitable
1475
+ index, return either 0 or N (where N is the length of `a`).
1476
+ sorter : 1-D array_like, optional
1477
+ Optional array of integer indices that sort array a into ascending
1478
+ order. They are typically the result of argsort.
1479
+
1480
+ Returns
1481
+ -------
1482
+ indices : int or array of ints
1483
+ Array of insertion points with the same shape as `v`,
1484
+ or an integer if `v` is a scalar.
1485
+
1486
+ See Also
1487
+ --------
1488
+ sort : Return a sorted copy of an array.
1489
+ histogram : Produce histogram from 1-D data.
1490
+
1491
+ Notes
1492
+ -----
1493
+ Binary search is used to find the required insertion points.
1494
+
1495
+ As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
1496
+ `nan` values. The enhanced sort order is documented in `sort`.
1497
+
1498
+ This function uses the same algorithm as the builtin python
1499
+ `bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
1500
+ (``side='right'``) functions, which is also vectorized
1501
+ in the `v` argument.
1502
+
1503
+ Examples
1504
+ --------
1505
+ >>> import numpy as np
1506
+ >>> np.searchsorted([11,12,13,14,15], 13)
1507
+ 2
1508
+ >>> np.searchsorted([11,12,13,14,15], 13, side='right')
1509
+ 3
1510
+ >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
1511
+ array([0, 5, 1, 2])
1512
+
1513
+ When `sorter` is used, the returned indices refer to the sorted
1514
+ array of `a` and not `a` itself:
1515
+
1516
+ >>> a = np.array([40, 10, 20, 30])
1517
+ >>> sorter = np.argsort(a)
1518
+ >>> sorter
1519
+ array([1, 2, 3, 0]) # Indices that would sort the array 'a'
1520
+ >>> result = np.searchsorted(a, 25, sorter=sorter)
1521
+ >>> result
1522
+ 2
1523
+ >>> a[sorter[result]]
1524
+ 30 # The element at index 2 of the sorted array is 30.
1525
+ """
1526
+ return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1527
+
1528
+
1529
+ def _resize_dispatcher(a, new_shape):
1530
+ return (a,)
1531
+
1532
+
1533
+ @array_function_dispatch(_resize_dispatcher)
1534
+ def resize(a, new_shape):
1535
+ """
1536
+ Return a new array with the specified shape.
1537
+
1538
+ If the new array is larger than the original array, then the new
1539
+ array is filled with repeated copies of `a`. Note that this behavior
1540
+ is different from a.resize(new_shape) which fills with zeros instead
1541
+ of repeated copies of `a`.
1542
+
1543
+ Parameters
1544
+ ----------
1545
+ a : array_like
1546
+ Array to be resized.
1547
+
1548
+ new_shape : int or tuple of int
1549
+ Shape of resized array.
1550
+
1551
+ Returns
1552
+ -------
1553
+ reshaped_array : ndarray
1554
+ The new array is formed from the data in the old array, repeated
1555
+ if necessary to fill out the required number of elements. The
1556
+ data are repeated iterating over the array in C-order.
1557
+
1558
+ See Also
1559
+ --------
1560
+ numpy.reshape : Reshape an array without changing the total size.
1561
+ numpy.pad : Enlarge and pad an array.
1562
+ numpy.repeat : Repeat elements of an array.
1563
+ ndarray.resize : resize an array in-place.
1564
+
1565
+ Notes
1566
+ -----
1567
+ When the total size of the array does not change `~numpy.reshape` should
1568
+ be used. In most other cases either indexing (to reduce the size)
1569
+ or padding (to increase the size) may be a more appropriate solution.
1570
+
1571
+ Warning: This functionality does **not** consider axes separately,
1572
+ i.e. it does not apply interpolation/extrapolation.
1573
+ It fills the return array with the required number of elements, iterating
1574
+ over `a` in C-order, disregarding axes (and cycling back from the start if
1575
+ the new shape is larger). This functionality is therefore not suitable to
1576
+ resize images, or data where each axis represents a separate and distinct
1577
+ entity.
1578
+
1579
+ Examples
1580
+ --------
1581
+ >>> import numpy as np
1582
+ >>> a = np.array([[0,1],[2,3]])
1583
+ >>> np.resize(a,(2,3))
1584
+ array([[0, 1, 2],
1585
+ [3, 0, 1]])
1586
+ >>> np.resize(a,(1,4))
1587
+ array([[0, 1, 2, 3]])
1588
+ >>> np.resize(a,(2,4))
1589
+ array([[0, 1, 2, 3],
1590
+ [0, 1, 2, 3]])
1591
+
1592
+ """
1593
+ if isinstance(new_shape, (int, nt.integer)):
1594
+ new_shape = (new_shape,)
1595
+
1596
+ a = ravel(a)
1597
+
1598
+ new_size = 1
1599
+ for dim_length in new_shape:
1600
+ new_size *= dim_length
1601
+ if dim_length < 0:
1602
+ raise ValueError(
1603
+ 'all elements of `new_shape` must be non-negative'
1604
+ )
1605
+
1606
+ if a.size == 0 or new_size == 0:
1607
+ # First case must zero fill. The second would have repeats == 0.
1608
+ return np.zeros_like(a, shape=new_shape)
1609
+
1610
+ # ceiling division without negating new_size
1611
+ repeats = (new_size + a.size - 1) // a.size
1612
+ a = concatenate((a,) * repeats)[:new_size]
1613
+
1614
+ return reshape(a, new_shape)
1615
+
1616
+
1617
+ def _squeeze_dispatcher(a, axis=None):
1618
+ return (a,)
1619
+
1620
+
1621
+ @array_function_dispatch(_squeeze_dispatcher)
1622
+ def squeeze(a, axis=None):
1623
+ """
1624
+ Remove axes of length one from `a`.
1625
+
1626
+ Parameters
1627
+ ----------
1628
+ a : array_like
1629
+ Input data.
1630
+ axis : None or int or tuple of ints, optional
1631
+ Selects a subset of the entries of length one in the
1632
+ shape. If an axis is selected with shape entry greater than
1633
+ one, an error is raised.
1634
+
1635
+ Returns
1636
+ -------
1637
+ squeezed : ndarray
1638
+ The input array, but with all or a subset of the
1639
+ dimensions of length 1 removed. This is always `a` itself
1640
+ or a view into `a`. Note that if all axes are squeezed,
1641
+ the result is a 0d array and not a scalar.
1642
+
1643
+ Raises
1644
+ ------
1645
+ ValueError
1646
+ If `axis` is not None, and an axis being squeezed is not of length 1
1647
+
1648
+ See Also
1649
+ --------
1650
+ expand_dims : The inverse operation, adding entries of length one
1651
+ reshape : Insert, remove, and combine dimensions, and resize existing ones
1652
+
1653
+ Examples
1654
+ --------
1655
+ >>> import numpy as np
1656
+ >>> x = np.array([[[0], [1], [2]]])
1657
+ >>> x.shape
1658
+ (1, 3, 1)
1659
+ >>> np.squeeze(x).shape
1660
+ (3,)
1661
+ >>> np.squeeze(x, axis=0).shape
1662
+ (3, 1)
1663
+ >>> np.squeeze(x, axis=1).shape
1664
+ Traceback (most recent call last):
1665
+ ...
1666
+ ValueError: cannot select an axis to squeeze out which has size
1667
+ not equal to one
1668
+ >>> np.squeeze(x, axis=2).shape
1669
+ (1, 3)
1670
+ >>> x = np.array([[1234]])
1671
+ >>> x.shape
1672
+ (1, 1)
1673
+ >>> np.squeeze(x)
1674
+ array(1234) # 0d array
1675
+ >>> np.squeeze(x).shape
1676
+ ()
1677
+ >>> np.squeeze(x)[()]
1678
+ 1234
1679
+
1680
+ """
1681
+ try:
1682
+ squeeze = a.squeeze
1683
+ except AttributeError:
1684
+ return _wrapit(a, 'squeeze', axis=axis)
1685
+ if axis is None:
1686
+ return squeeze()
1687
+ else:
1688
+ return squeeze(axis=axis)
1689
+
1690
+
1691
+ def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
1692
+ return (a,)
1693
+
1694
+
1695
+ @array_function_dispatch(_diagonal_dispatcher)
1696
+ def diagonal(a, offset=0, axis1=0, axis2=1):
1697
+ """
1698
+ Return specified diagonals.
1699
+
1700
+ If `a` is 2-D, returns the diagonal of `a` with the given offset,
1701
+ i.e., the collection of elements of the form ``a[i, i+offset]``. If
1702
+ `a` has more than two dimensions, then the axes specified by `axis1`
1703
+ and `axis2` are used to determine the 2-D sub-array whose diagonal is
1704
+ returned. The shape of the resulting array can be determined by
1705
+ removing `axis1` and `axis2` and appending an index to the right equal
1706
+ to the size of the resulting diagonals.
1707
+
1708
+ In versions of NumPy prior to 1.7, this function always returned a new,
1709
+ independent array containing a copy of the values in the diagonal.
1710
+
1711
+ In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
1712
+ but depending on this fact is deprecated. Writing to the resulting
1713
+ array continues to work as it used to, but a FutureWarning is issued.
1714
+
1715
+ Starting in NumPy 1.9 it returns a read-only view on the original array.
1716
+ Attempting to write to the resulting array will produce an error.
1717
+
1718
+ In some future release, it will return a read/write view and writing to
1719
+ the returned array will alter your original array. The returned array
1720
+ will have the same type as the input array.
1721
+
1722
+ If you don't write to the array returned by this function, then you can
1723
+ just ignore all of the above.
1724
+
1725
+ If you depend on the current behavior, then we suggest copying the
1726
+ returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
1727
+ of just ``np.diagonal(a)``. This will work with both past and future
1728
+ versions of NumPy.
1729
+
1730
+ Parameters
1731
+ ----------
1732
+ a : array_like
1733
+ Array from which the diagonals are taken.
1734
+ offset : int, optional
1735
+ Offset of the diagonal from the main diagonal. Can be positive or
1736
+ negative. Defaults to main diagonal (0).
1737
+ axis1 : int, optional
1738
+ Axis to be used as the first axis of the 2-D sub-arrays from which
1739
+ the diagonals should be taken. Defaults to first axis (0).
1740
+ axis2 : int, optional
1741
+ Axis to be used as the second axis of the 2-D sub-arrays from
1742
+ which the diagonals should be taken. Defaults to second axis (1).
1743
+
1744
+ Returns
1745
+ -------
1746
+ array_of_diagonals : ndarray
1747
+ If `a` is 2-D, then a 1-D array containing the diagonal and of the
1748
+ same type as `a` is returned unless `a` is a `matrix`, in which case
1749
+ a 1-D array rather than a (2-D) `matrix` is returned in order to
1750
+ maintain backward compatibility.
1751
+
1752
+ If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
1753
+ are removed, and a new axis inserted at the end corresponding to the
1754
+ diagonal.
1755
+
1756
+ Raises
1757
+ ------
1758
+ ValueError
1759
+ If the dimension of `a` is less than 2.
1760
+
1761
+ See Also
1762
+ --------
1763
+ diag : MATLAB work-a-like for 1-D and 2-D arrays.
1764
+ diagflat : Create diagonal arrays.
1765
+ trace : Sum along diagonals.
1766
+
1767
+ Examples
1768
+ --------
1769
+ >>> import numpy as np
1770
+ >>> a = np.arange(4).reshape(2,2)
1771
+ >>> a
1772
+ array([[0, 1],
1773
+ [2, 3]])
1774
+ >>> a.diagonal()
1775
+ array([0, 3])
1776
+ >>> a.diagonal(1)
1777
+ array([1])
1778
+
1779
+ A 3-D example:
1780
+
1781
+ >>> a = np.arange(8).reshape(2,2,2); a
1782
+ array([[[0, 1],
1783
+ [2, 3]],
1784
+ [[4, 5],
1785
+ [6, 7]]])
1786
+ >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
1787
+ ... 0, # across the outer(left)-most axis last and
1788
+ ... 1) # the "middle" (row) axis first.
1789
+ array([[0, 6],
1790
+ [1, 7]])
1791
+
1792
+ The sub-arrays whose main diagonals we just obtained; note that each
1793
+ corresponds to fixing the right-most (column) axis, and that the
1794
+ diagonals are "packed" in rows.
1795
+
1796
+ >>> a[:,:,0] # main diagonal is [0 6]
1797
+ array([[0, 2],
1798
+ [4, 6]])
1799
+ >>> a[:,:,1] # main diagonal is [1 7]
1800
+ array([[1, 3],
1801
+ [5, 7]])
1802
+
1803
+ The anti-diagonal can be obtained by reversing the order of elements
1804
+ using either `numpy.flipud` or `numpy.fliplr`.
1805
+
1806
+ >>> a = np.arange(9).reshape(3, 3)
1807
+ >>> a
1808
+ array([[0, 1, 2],
1809
+ [3, 4, 5],
1810
+ [6, 7, 8]])
1811
+ >>> np.fliplr(a).diagonal() # Horizontal flip
1812
+ array([2, 4, 6])
1813
+ >>> np.flipud(a).diagonal() # Vertical flip
1814
+ array([6, 4, 2])
1815
+
1816
+ Note that the order in which the diagonal is retrieved varies depending
1817
+ on the flip function.
1818
+ """
1819
+ if isinstance(a, np.matrix):
1820
+ # Make diagonal of matrix 1-D to preserve backward compatibility.
1821
+ return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1822
+ else:
1823
+ return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1824
+
1825
+
1826
+ def _trace_dispatcher(
1827
+ a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
1828
+ return (a, out)
1829
+
1830
+
1831
+ @array_function_dispatch(_trace_dispatcher)
1832
+ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1833
+ """
1834
+ Return the sum along diagonals of the array.
1835
+
1836
+ If `a` is 2-D, the sum along its diagonal with the given offset
1837
+ is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1838
+
1839
+ If `a` has more than two dimensions, then the axes specified by axis1 and
1840
+ axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1841
+ The shape of the resulting array is the same as that of `a` with `axis1`
1842
+ and `axis2` removed.
1843
+
1844
+ Parameters
1845
+ ----------
1846
+ a : array_like
1847
+ Input array, from which the diagonals are taken.
1848
+ offset : int, optional
1849
+ Offset of the diagonal from the main diagonal. Can be both positive
1850
+ and negative. Defaults to 0.
1851
+ axis1, axis2 : int, optional
1852
+ Axes to be used as the first and second axis of the 2-D sub-arrays
1853
+ from which the diagonals should be taken. Defaults are the first two
1854
+ axes of `a`.
1855
+ dtype : dtype, optional
1856
+ Determines the data-type of the returned array and of the accumulator
1857
+ where the elements are summed. If dtype has the value None and `a` is
1858
+ of integer type of precision less than the default integer
1859
+ precision, then the default integer precision is used. Otherwise,
1860
+ the precision is the same as that of `a`.
1861
+ out : ndarray, optional
1862
+ Array into which the output is placed. Its type is preserved and
1863
+ it must be of the right shape to hold the output.
1864
+
1865
+ Returns
1866
+ -------
1867
+ sum_along_diagonals : ndarray
1868
+ If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1869
+ larger dimensions, then an array of sums along diagonals is returned.
1870
+
1871
+ See Also
1872
+ --------
1873
+ diag, diagonal, diagflat
1874
+
1875
+ Examples
1876
+ --------
1877
+ >>> import numpy as np
1878
+ >>> np.trace(np.eye(3))
1879
+ 3.0
1880
+ >>> a = np.arange(8).reshape((2,2,2))
1881
+ >>> np.trace(a)
1882
+ array([6, 8])
1883
+
1884
+ >>> a = np.arange(24).reshape((2,2,2,3))
1885
+ >>> np.trace(a).shape
1886
+ (2, 3)
1887
+
1888
+ """
1889
+ if isinstance(a, np.matrix):
1890
+ # Get trace of matrix via an array to preserve backward compatibility.
1891
+ return asarray(a).trace(
1892
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
1893
+ )
1894
+ else:
1895
+ return asanyarray(a).trace(
1896
+ offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
1897
+ )
1898
+
1899
+
1900
+ def _ravel_dispatcher(a, order=None):
1901
+ return (a,)
1902
+
1903
+
1904
+ @array_function_dispatch(_ravel_dispatcher)
1905
+ def ravel(a, order='C'):
1906
+ """Return a contiguous flattened array.
1907
+
1908
+ A 1-D array, containing the elements of the input, is returned. A copy is
1909
+ made only if needed.
1910
+
1911
+ As of NumPy 1.10, the returned array will have the same type as the input
1912
+ array. (for example, a masked array will be returned for a masked array
1913
+ input)
1914
+
1915
+ Parameters
1916
+ ----------
1917
+ a : array_like
1918
+ Input array. The elements in `a` are read in the order specified by
1919
+ `order`, and packed as a 1-D array.
1920
+ order : {'C','F', 'A', 'K'}, optional
1921
+
1922
+ The elements of `a` are read using this index order. 'C' means
1923
+ to index the elements in row-major, C-style order,
1924
+ with the last axis index changing fastest, back to the first
1925
+ axis index changing slowest. 'F' means to index the elements
1926
+ in column-major, Fortran-style order, with the
1927
+ first index changing fastest, and the last index changing
1928
+ slowest. Note that the 'C' and 'F' options take no account of
1929
+ the memory layout of the underlying array, and only refer to
1930
+ the order of axis indexing. 'A' means to read the elements in
1931
+ Fortran-like index order if `a` is Fortran *contiguous* in
1932
+ memory, C-like order otherwise. 'K' means to read the
1933
+ elements in the order they occur in memory, except for
1934
+ reversing the data when strides are negative. By default, 'C'
1935
+ index order is used.
1936
+
1937
+ Returns
1938
+ -------
1939
+ y : array_like
1940
+ y is a contiguous 1-D array of the same subtype as `a`,
1941
+ with shape ``(a.size,)``.
1942
+ Note that matrices are special cased for backward compatibility,
1943
+ if `a` is a matrix, then y is a 1-D ndarray.
1944
+
1945
+ See Also
1946
+ --------
1947
+ ndarray.flat : 1-D iterator over an array.
1948
+ ndarray.flatten : 1-D array copy of the elements of an array
1949
+ in row-major order.
1950
+ ndarray.reshape : Change the shape of an array without changing its data.
1951
+
1952
+ Notes
1953
+ -----
1954
+ In row-major, C-style order, in two dimensions, the row index
1955
+ varies the slowest, and the column index the quickest. This can
1956
+ be generalized to multiple dimensions, where row-major order
1957
+ implies that the index along the first axis varies slowest, and
1958
+ the index along the last quickest. The opposite holds for
1959
+ column-major, Fortran-style index ordering.
1960
+
1961
+ When a view is desired in as many cases as possible, ``arr.reshape(-1)``
1962
+ may be preferable. However, ``ravel`` supports ``K`` in the optional
1963
+ ``order`` argument while ``reshape`` does not.
1964
+
1965
+ Examples
1966
+ --------
1967
+ It is equivalent to ``reshape(-1, order=order)``.
1968
+
1969
+ >>> import numpy as np
1970
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]])
1971
+ >>> np.ravel(x)
1972
+ array([1, 2, 3, 4, 5, 6])
1973
+
1974
+ >>> x.reshape(-1)
1975
+ array([1, 2, 3, 4, 5, 6])
1976
+
1977
+ >>> np.ravel(x, order='F')
1978
+ array([1, 4, 2, 5, 3, 6])
1979
+
1980
+ When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
1981
+
1982
+ >>> np.ravel(x.T)
1983
+ array([1, 4, 2, 5, 3, 6])
1984
+ >>> np.ravel(x.T, order='A')
1985
+ array([1, 2, 3, 4, 5, 6])
1986
+
1987
+ When ``order`` is 'K', it will preserve orderings that are neither 'C'
1988
+ nor 'F', but won't reverse axes:
1989
+
1990
+ >>> a = np.arange(3)[::-1]; a
1991
+ array([2, 1, 0])
1992
+ >>> a.ravel(order='C')
1993
+ array([2, 1, 0])
1994
+ >>> a.ravel(order='K')
1995
+ array([2, 1, 0])
1996
+
1997
+ >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
1998
+ array([[[ 0, 2, 4],
1999
+ [ 1, 3, 5]],
2000
+ [[ 6, 8, 10],
2001
+ [ 7, 9, 11]]])
2002
+ >>> a.ravel(order='C')
2003
+ array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
2004
+ >>> a.ravel(order='K')
2005
+ array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
2006
+
2007
+ """
2008
+ if isinstance(a, np.matrix):
2009
+ return asarray(a).ravel(order=order)
2010
+ else:
2011
+ return asanyarray(a).ravel(order=order)
2012
+
2013
+
2014
+ def _nonzero_dispatcher(a):
2015
+ return (a,)
2016
+
2017
+
2018
+ @array_function_dispatch(_nonzero_dispatcher)
2019
+ def nonzero(a):
2020
+ """
2021
+ Return the indices of the elements that are non-zero.
2022
+
2023
+ Returns a tuple of arrays, one for each dimension of `a`,
2024
+ containing the indices of the non-zero elements in that
2025
+ dimension. The values in `a` are always tested and returned in
2026
+ row-major, C-style order.
2027
+
2028
+ To group the indices by element, rather than dimension, use `argwhere`,
2029
+ which returns a row for each non-zero element.
2030
+
2031
+ .. note::
2032
+
2033
+ When called on a zero-d array or scalar, ``nonzero(a)`` is treated
2034
+ as ``nonzero(atleast_1d(a))``.
2035
+
2036
+ .. deprecated:: 1.17.0
2037
+
2038
+ Use `atleast_1d` explicitly if this behavior is deliberate.
2039
+
2040
+ Parameters
2041
+ ----------
2042
+ a : array_like
2043
+ Input array.
2044
+
2045
+ Returns
2046
+ -------
2047
+ tuple_of_arrays : tuple
2048
+ Indices of elements that are non-zero.
2049
+
2050
+ See Also
2051
+ --------
2052
+ flatnonzero :
2053
+ Return indices that are non-zero in the flattened version of the input
2054
+ array.
2055
+ ndarray.nonzero :
2056
+ Equivalent ndarray method.
2057
+ count_nonzero :
2058
+ Counts the number of non-zero elements in the input array.
2059
+
2060
+ Notes
2061
+ -----
2062
+ While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
2063
+ recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
2064
+ will correctly handle 0-d arrays.
2065
+
2066
+ Examples
2067
+ --------
2068
+ >>> import numpy as np
2069
+ >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
2070
+ >>> x
2071
+ array([[3, 0, 0],
2072
+ [0, 4, 0],
2073
+ [5, 6, 0]])
2074
+ >>> np.nonzero(x)
2075
+ (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
2076
+
2077
+ >>> x[np.nonzero(x)]
2078
+ array([3, 4, 5, 6])
2079
+ >>> np.transpose(np.nonzero(x))
2080
+ array([[0, 0],
2081
+ [1, 1],
2082
+ [2, 0],
2083
+ [2, 1]])
2084
+
2085
+ A common use for ``nonzero`` is to find the indices of an array, where
2086
+ a condition is True. Given an array `a`, the condition `a` > 3 is a
2087
+ boolean array and since False is interpreted as 0, np.nonzero(a > 3)
2088
+ yields the indices of the `a` where the condition is true.
2089
+
2090
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2091
+ >>> a > 3
2092
+ array([[False, False, False],
2093
+ [ True, True, True],
2094
+ [ True, True, True]])
2095
+ >>> np.nonzero(a > 3)
2096
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
2097
+
2098
+ Using this result to index `a` is equivalent to using the mask directly:
2099
+
2100
+ >>> a[np.nonzero(a > 3)]
2101
+ array([4, 5, 6, 7, 8, 9])
2102
+ >>> a[a > 3] # prefer this spelling
2103
+ array([4, 5, 6, 7, 8, 9])
2104
+
2105
+ ``nonzero`` can also be called as a method of the array.
2106
+
2107
+ >>> (a > 3).nonzero()
2108
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
2109
+
2110
+ """
2111
+ return _wrapfunc(a, 'nonzero')
2112
+
2113
+
2114
+ def _shape_dispatcher(a):
2115
+ return (a,)
2116
+
2117
+
2118
+ @array_function_dispatch(_shape_dispatcher)
2119
+ def shape(a):
2120
+ """
2121
+ Return the shape of an array.
2122
+
2123
+ Parameters
2124
+ ----------
2125
+ a : array_like
2126
+ Input array.
2127
+
2128
+ Returns
2129
+ -------
2130
+ shape : tuple of ints
2131
+ The elements of the shape tuple give the lengths of the
2132
+ corresponding array dimensions.
2133
+
2134
+ See Also
2135
+ --------
2136
+ len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
2137
+ ``N>=1``.
2138
+ ndarray.shape : Equivalent array method.
2139
+
2140
+ Examples
2141
+ --------
2142
+ >>> import numpy as np
2143
+ >>> np.shape(np.eye(3))
2144
+ (3, 3)
2145
+ >>> np.shape([[1, 3]])
2146
+ (1, 2)
2147
+ >>> np.shape([0])
2148
+ (1,)
2149
+ >>> np.shape(0)
2150
+ ()
2151
+
2152
+ >>> a = np.array([(1, 2), (3, 4), (5, 6)],
2153
+ ... dtype=[('x', 'i4'), ('y', 'i4')])
2154
+ >>> np.shape(a)
2155
+ (3,)
2156
+ >>> a.shape
2157
+ (3,)
2158
+
2159
+ """
2160
+ try:
2161
+ result = a.shape
2162
+ except AttributeError:
2163
+ result = asarray(a).shape
2164
+ return result
2165
+
2166
+
2167
+ def _compress_dispatcher(condition, a, axis=None, out=None):
2168
+ return (condition, a, out)
2169
+
2170
+
2171
+ @array_function_dispatch(_compress_dispatcher)
2172
+ def compress(condition, a, axis=None, out=None):
2173
+ """
2174
+ Return selected slices of an array along given axis.
2175
+
2176
+ When working along a given axis, a slice along that axis is returned in
2177
+ `output` for each index where `condition` evaluates to True. When
2178
+ working on a 1-D array, `compress` is equivalent to `extract`.
2179
+
2180
+ Parameters
2181
+ ----------
2182
+ condition : 1-D array of bools
2183
+ Array that selects which entries to return. If len(condition)
2184
+ is less than the size of `a` along the given axis, then output is
2185
+ truncated to the length of the condition array.
2186
+ a : array_like
2187
+ Array from which to extract a part.
2188
+ axis : int, optional
2189
+ Axis along which to take slices. If None (default), work on the
2190
+ flattened array.
2191
+ out : ndarray, optional
2192
+ Output array. Its type is preserved and it must be of the right
2193
+ shape to hold the output.
2194
+
2195
+ Returns
2196
+ -------
2197
+ compressed_array : ndarray
2198
+ A copy of `a` without the slices along axis for which `condition`
2199
+ is false.
2200
+
2201
+ See Also
2202
+ --------
2203
+ take, choose, diag, diagonal, select
2204
+ ndarray.compress : Equivalent method in ndarray
2205
+ extract : Equivalent method when working on 1-D arrays
2206
+ :ref:`ufuncs-output-type`
2207
+
2208
+ Examples
2209
+ --------
2210
+ >>> import numpy as np
2211
+ >>> a = np.array([[1, 2], [3, 4], [5, 6]])
2212
+ >>> a
2213
+ array([[1, 2],
2214
+ [3, 4],
2215
+ [5, 6]])
2216
+ >>> np.compress([0, 1], a, axis=0)
2217
+ array([[3, 4]])
2218
+ >>> np.compress([False, True, True], a, axis=0)
2219
+ array([[3, 4],
2220
+ [5, 6]])
2221
+ >>> np.compress([False, True], a, axis=1)
2222
+ array([[2],
2223
+ [4],
2224
+ [6]])
2225
+
2226
+ Working on the flattened array does not return slices along an axis but
2227
+ selects elements.
2228
+
2229
+ >>> np.compress([False, True], a)
2230
+ array([2])
2231
+
2232
+ """
2233
+ return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
2234
+
2235
+
2236
+ def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None,
2237
+ max=None, **kwargs):
2238
+ return (a, a_min, a_max, out, min, max)
2239
+
2240
+
2241
+ @array_function_dispatch(_clip_dispatcher)
2242
+ def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *,
2243
+ min=np._NoValue, max=np._NoValue, **kwargs):
2244
+ """
2245
+ Clip (limit) the values in an array.
2246
+
2247
+ Given an interval, values outside the interval are clipped to
2248
+ the interval edges. For example, if an interval of ``[0, 1]``
2249
+ is specified, values smaller than 0 become 0, and values larger
2250
+ than 1 become 1.
2251
+
2252
+ Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
2253
+
2254
+ No check is performed to ensure ``a_min < a_max``.
2255
+
2256
+ Parameters
2257
+ ----------
2258
+ a : array_like
2259
+ Array containing elements to clip.
2260
+ a_min, a_max : array_like or None
2261
+ Minimum and maximum value. If ``None``, clipping is not performed on
2262
+ the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
2263
+ the elements of the returned array stay the same. Both are broadcasted
2264
+ against ``a``.
2265
+ out : ndarray, optional
2266
+ The results will be placed in this array. It may be the input
2267
+ array for in-place clipping. `out` must be of the right shape
2268
+ to hold the output. Its type is preserved.
2269
+ min, max : array_like or None
2270
+ Array API compatible alternatives for ``a_min`` and ``a_max``
2271
+ arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
2272
+ can be passed at the same time. Default: ``None``.
2273
+
2274
+ .. versionadded:: 2.1.0
2275
+ **kwargs
2276
+ For other keyword-only arguments, see the
2277
+ :ref:`ufunc docs <ufuncs.kwargs>`.
2278
+
2279
+ Returns
2280
+ -------
2281
+ clipped_array : ndarray
2282
+ An array with the elements of `a`, but where values
2283
+ < `a_min` are replaced with `a_min`, and those > `a_max`
2284
+ with `a_max`.
2285
+
2286
+ See Also
2287
+ --------
2288
+ :ref:`ufuncs-output-type`
2289
+
2290
+ Notes
2291
+ -----
2292
+ When `a_min` is greater than `a_max`, `clip` returns an
2293
+ array in which all values are equal to `a_max`,
2294
+ as shown in the second example.
2295
+
2296
+ Examples
2297
+ --------
2298
+ >>> import numpy as np
2299
+ >>> a = np.arange(10)
2300
+ >>> a
2301
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2302
+ >>> np.clip(a, 1, 8)
2303
+ array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
2304
+ >>> np.clip(a, 8, 1)
2305
+ array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
2306
+ >>> np.clip(a, 3, 6, out=a)
2307
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2308
+ >>> a
2309
+ array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2310
+ >>> a = np.arange(10)
2311
+ >>> a
2312
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2313
+ >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
2314
+ array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
2315
+
2316
+ """
2317
+ if a_min is np._NoValue and a_max is np._NoValue:
2318
+ a_min = None if min is np._NoValue else min
2319
+ a_max = None if max is np._NoValue else max
2320
+ elif a_min is np._NoValue:
2321
+ raise TypeError("clip() missing 1 required positional "
2322
+ "argument: 'a_min'")
2323
+ elif a_max is np._NoValue:
2324
+ raise TypeError("clip() missing 1 required positional "
2325
+ "argument: 'a_max'")
2326
+ elif min is not np._NoValue or max is not np._NoValue:
2327
+ raise ValueError("Passing `min` or `max` keyword argument when "
2328
+ "`a_min` and `a_max` are provided is forbidden.")
2329
+
2330
+ return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
2331
+
2332
+
2333
+ def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2334
+ initial=None, where=None):
2335
+ return (a, out)
2336
+
2337
+
2338
+ @array_function_dispatch(_sum_dispatcher)
2339
+ def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2340
+ initial=np._NoValue, where=np._NoValue):
2341
+ """
2342
+ Sum of array elements over a given axis.
2343
+
2344
+ Parameters
2345
+ ----------
2346
+ a : array_like
2347
+ Elements to sum.
2348
+ axis : None or int or tuple of ints, optional
2349
+ Axis or axes along which a sum is performed. The default,
2350
+ axis=None, will sum all of the elements of the input array. If
2351
+ axis is negative it counts from the last to the first axis. If
2352
+ axis is a tuple of ints, a sum is performed on all of the axes
2353
+ specified in the tuple instead of a single axis or all the axes as
2354
+ before.
2355
+ dtype : dtype, optional
2356
+ The type of the returned array and of the accumulator in which the
2357
+ elements are summed. The dtype of `a` is used by default unless `a`
2358
+ has an integer dtype of less precision than the default platform
2359
+ integer. In that case, if `a` is signed then the platform integer
2360
+ is used while if `a` is unsigned then an unsigned integer of the
2361
+ same precision as the platform integer is used.
2362
+ out : ndarray, optional
2363
+ Alternative output array in which to place the result. It must have
2364
+ the same shape as the expected output, but the type of the output
2365
+ values will be cast if necessary.
2366
+ keepdims : bool, optional
2367
+ If this is set to True, the axes which are reduced are left
2368
+ in the result as dimensions with size one. With this option,
2369
+ the result will broadcast correctly against the input array.
2370
+
2371
+ If the default value is passed, then `keepdims` will not be
2372
+ passed through to the `sum` method of sub-classes of
2373
+ `ndarray`, however any non-default value will be. If the
2374
+ sub-class' method does not implement `keepdims` any
2375
+ exceptions will be raised.
2376
+ initial : scalar, optional
2377
+ Starting value for the sum. See `~numpy.ufunc.reduce` for details.
2378
+ where : array_like of bool, optional
2379
+ Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
2380
+
2381
+ Returns
2382
+ -------
2383
+ sum_along_axis : ndarray
2384
+ An array with the same shape as `a`, with the specified
2385
+ axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
2386
+ is returned. If an output array is specified, a reference to
2387
+ `out` is returned.
2388
+
2389
+ See Also
2390
+ --------
2391
+ ndarray.sum : Equivalent method.
2392
+ add: ``numpy.add.reduce`` equivalent function.
2393
+ cumsum : Cumulative sum of array elements.
2394
+ trapezoid : Integration of array values using composite trapezoidal rule.
2395
+
2396
+ mean, average
2397
+
2398
+ Notes
2399
+ -----
2400
+ Arithmetic is modular when using integer types, and no error is
2401
+ raised on overflow.
2402
+
2403
+ The sum of an empty array is the neutral element 0:
2404
+
2405
+ >>> np.sum([])
2406
+ 0.0
2407
+
2408
+ For floating point numbers the numerical precision of sum (and
2409
+ ``np.add.reduce``) is in general limited by directly adding each number
2410
+ individually to the result causing rounding errors in every step.
2411
+ However, often numpy will use a numerically better approach (partial
2412
+ pairwise summation) leading to improved precision in many use-cases.
2413
+ This improved precision is always provided when no ``axis`` is given.
2414
+ When ``axis`` is given, it will depend on which axis is summed.
2415
+ Technically, to provide the best speed possible, the improved precision
2416
+ is only used when the summation is along the fast axis in memory.
2417
+ Note that the exact precision may vary depending on other parameters.
2418
+ In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2419
+ more precise approach to summation.
2420
+ Especially when summing a large number of lower precision floating point
2421
+ numbers, such as ``float32``, numerical errors can become significant.
2422
+ In such cases it can be advisable to use `dtype="float64"` to use a higher
2423
+ precision for the output.
2424
+
2425
+ Examples
2426
+ --------
2427
+ >>> import numpy as np
2428
+ >>> np.sum([0.5, 1.5])
2429
+ 2.0
2430
+ >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
2431
+ np.int32(1)
2432
+ >>> np.sum([[0, 1], [0, 5]])
2433
+ 6
2434
+ >>> np.sum([[0, 1], [0, 5]], axis=0)
2435
+ array([0, 6])
2436
+ >>> np.sum([[0, 1], [0, 5]], axis=1)
2437
+ array([1, 5])
2438
+ >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
2439
+ array([1., 5.])
2440
+
2441
+ If the accumulator is too small, overflow occurs:
2442
+
2443
+ >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
2444
+ np.int8(-128)
2445
+
2446
+ You can also start the sum with a value other than zero:
2447
+
2448
+ >>> np.sum([10], initial=5)
2449
+ 15
2450
+ """
2451
+ if isinstance(a, _gentype):
2452
+ # 2018-02-25, 1.15.0
2453
+ warnings.warn(
2454
+ "Calling np.sum(generator) is deprecated, and in the future will "
2455
+ "give a different result. Use np.sum(np.fromiter(generator)) or "
2456
+ "the python sum builtin instead.",
2457
+ DeprecationWarning, stacklevel=2
2458
+ )
2459
+
2460
+ res = _sum_(a)
2461
+ if out is not None:
2462
+ out[...] = res
2463
+ return out
2464
+ return res
2465
+
2466
+ return _wrapreduction(
2467
+ a, np.add, 'sum', axis, dtype, out,
2468
+ keepdims=keepdims, initial=initial, where=where
2469
+ )
2470
+
2471
+
2472
+ def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
2473
+ where=np._NoValue):
2474
+ return (a, where, out)
2475
+
2476
+
2477
+ @array_function_dispatch(_any_dispatcher)
2478
+ def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2479
+ """
2480
+ Test whether any array element along a given axis evaluates to True.
2481
+
2482
+ Returns single boolean if `axis` is ``None``
2483
+
2484
+ Parameters
2485
+ ----------
2486
+ a : array_like
2487
+ Input array or object that can be converted to an array.
2488
+ axis : None or int or tuple of ints, optional
2489
+ Axis or axes along which a logical OR reduction is performed.
2490
+ The default (``axis=None``) is to perform a logical OR over all
2491
+ the dimensions of the input array. `axis` may be negative, in
2492
+ which case it counts from the last to the first axis. If this
2493
+ is a tuple of ints, a reduction is performed on multiple
2494
+ axes, instead of a single axis or all the axes as before.
2495
+ out : ndarray, optional
2496
+ Alternate output array in which to place the result. It must have
2497
+ the same shape as the expected output and its type is preserved
2498
+ (e.g., if it is of type float, then it will remain so, returning
2499
+ 1.0 for True and 0.0 for False, regardless of the type of `a`).
2500
+ See :ref:`ufuncs-output-type` for more details.
2501
+
2502
+ keepdims : bool, optional
2503
+ If this is set to True, the axes which are reduced are left
2504
+ in the result as dimensions with size one. With this option,
2505
+ the result will broadcast correctly against the input array.
2506
+
2507
+ If the default value is passed, then `keepdims` will not be
2508
+ passed through to the `any` method of sub-classes of
2509
+ `ndarray`, however any non-default value will be. If the
2510
+ sub-class' method does not implement `keepdims` any
2511
+ exceptions will be raised.
2512
+
2513
+ where : array_like of bool, optional
2514
+ Elements to include in checking for any `True` values.
2515
+ See `~numpy.ufunc.reduce` for details.
2516
+
2517
+ .. versionadded:: 1.20.0
2518
+
2519
+ Returns
2520
+ -------
2521
+ any : bool or ndarray
2522
+ A new boolean or `ndarray` is returned unless `out` is specified,
2523
+ in which case a reference to `out` is returned.
2524
+
2525
+ See Also
2526
+ --------
2527
+ ndarray.any : equivalent method
2528
+
2529
+ all : Test whether all elements along a given axis evaluate to True.
2530
+
2531
+ Notes
2532
+ -----
2533
+ Not a Number (NaN), positive infinity and negative infinity evaluate
2534
+ to `True` because these are not equal to zero.
2535
+
2536
+ .. versionchanged:: 2.0
2537
+ Before NumPy 2.0, ``any`` did not return booleans for object dtype
2538
+ input arrays.
2539
+ This behavior is still available via ``np.logical_or.reduce``.
2540
+
2541
+ Examples
2542
+ --------
2543
+ >>> import numpy as np
2544
+ >>> np.any([[True, False], [True, True]])
2545
+ True
2546
+
2547
+ >>> np.any([[True, False, True ],
2548
+ ... [False, False, False]], axis=0)
2549
+ array([ True, False, True])
2550
+
2551
+ >>> np.any([-1, 0, 5])
2552
+ True
2553
+
2554
+ >>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
2555
+ array([[ True],
2556
+ [ True]])
2557
+
2558
+ >>> np.any([[True, False], [False, False]], where=[[False], [True]])
2559
+ False
2560
+
2561
+ >>> a = np.array([[1, 0, 0],
2562
+ ... [0, 0, 1],
2563
+ ... [0, 0, 0]])
2564
+ >>> np.any(a, axis=0)
2565
+ array([ True, False, True])
2566
+ >>> np.any(a, axis=1)
2567
+ array([ True, True, False])
2568
+
2569
+ >>> o=np.array(False)
2570
+ >>> z=np.any([-1, 4, 5], out=o)
2571
+ >>> z, o
2572
+ (array(True), array(True))
2573
+ >>> # Check now that z is a reference to o
2574
+ >>> z is o
2575
+ True
2576
+ >>> id(z), id(o) # identity of z and o # doctest: +SKIP
2577
+ (191614240, 191614240)
2578
+
2579
+ """
2580
+ return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out,
2581
+ keepdims=keepdims, where=where)
2582
+
2583
+
2584
+ def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
2585
+ where=None):
2586
+ return (a, where, out)
2587
+
2588
+
2589
+ @array_function_dispatch(_all_dispatcher)
2590
+ def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2591
+ """
2592
+ Test whether all array elements along a given axis evaluate to True.
2593
+
2594
+ Parameters
2595
+ ----------
2596
+ a : array_like
2597
+ Input array or object that can be converted to an array.
2598
+ axis : None or int or tuple of ints, optional
2599
+ Axis or axes along which a logical AND reduction is performed.
2600
+ The default (``axis=None``) is to perform a logical AND over all
2601
+ the dimensions of the input array. `axis` may be negative, in
2602
+ which case it counts from the last to the first axis. If this
2603
+ is a tuple of ints, a reduction is performed on multiple
2604
+ axes, instead of a single axis or all the axes as before.
2605
+ out : ndarray, optional
2606
+ Alternate output array in which to place the result.
2607
+ It must have the same shape as the expected output and its
2608
+ type is preserved (e.g., if ``dtype(out)`` is float, the result
2609
+ will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
2610
+ for more details.
2611
+
2612
+ keepdims : bool, optional
2613
+ If this is set to True, the axes which are reduced are left
2614
+ in the result as dimensions with size one. With this option,
2615
+ the result will broadcast correctly against the input array.
2616
+
2617
+ If the default value is passed, then `keepdims` will not be
2618
+ passed through to the `all` method of sub-classes of
2619
+ `ndarray`, however any non-default value will be. If the
2620
+ sub-class' method does not implement `keepdims` any
2621
+ exceptions will be raised.
2622
+
2623
+ where : array_like of bool, optional
2624
+ Elements to include in checking for all `True` values.
2625
+ See `~numpy.ufunc.reduce` for details.
2626
+
2627
+ .. versionadded:: 1.20.0
2628
+
2629
+ Returns
2630
+ -------
2631
+ all : ndarray, bool
2632
+ A new boolean or array is returned unless `out` is specified,
2633
+ in which case a reference to `out` is returned.
2634
+
2635
+ See Also
2636
+ --------
2637
+ ndarray.all : equivalent method
2638
+
2639
+ any : Test whether any element along a given axis evaluates to True.
2640
+
2641
+ Notes
2642
+ -----
2643
+ Not a Number (NaN), positive infinity and negative infinity
2644
+ evaluate to `True` because these are not equal to zero.
2645
+
2646
+ .. versionchanged:: 2.0
2647
+ Before NumPy 2.0, ``all`` did not return booleans for object dtype
2648
+ input arrays.
2649
+ This behavior is still available via ``np.logical_and.reduce``.
2650
+
2651
+ Examples
2652
+ --------
2653
+ >>> import numpy as np
2654
+ >>> np.all([[True,False],[True,True]])
2655
+ False
2656
+
2657
+ >>> np.all([[True,False],[True,True]], axis=0)
2658
+ array([ True, False])
2659
+
2660
+ >>> np.all([-1, 4, 5])
2661
+ True
2662
+
2663
+ >>> np.all([1.0, np.nan])
2664
+ True
2665
+
2666
+ >>> np.all([[True, True], [False, True]], where=[[True], [False]])
2667
+ True
2668
+
2669
+ >>> o=np.array(False)
2670
+ >>> z=np.all([-1, 4, 5], out=o)
2671
+ >>> id(z), id(o), z
2672
+ (28293632, 28293632, array(True)) # may vary
2673
+
2674
+ """
2675
+ return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out,
2676
+ keepdims=keepdims, where=where)
2677
+
2678
+
2679
+ def _cumulative_func(x, func, axis, dtype, out, include_initial):
2680
+ x = np.atleast_1d(x)
2681
+ x_ndim = x.ndim
2682
+ if axis is None:
2683
+ if x_ndim >= 2:
2684
+ raise ValueError("For arrays which have more than one dimension "
2685
+ "``axis`` argument is required.")
2686
+ axis = 0
2687
+
2688
+ if out is not None and include_initial:
2689
+ item = [slice(None)] * x_ndim
2690
+ item[axis] = slice(1, None)
2691
+ func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)])
2692
+ item[axis] = 0
2693
+ out[tuple(item)] = func.identity
2694
+ return out
2695
+
2696
+ res = func.accumulate(x, axis=axis, dtype=dtype, out=out)
2697
+ if include_initial:
2698
+ initial_shape = list(x.shape)
2699
+ initial_shape[axis] = 1
2700
+ res = np.concat(
2701
+ [np.full_like(res, func.identity, shape=initial_shape), res],
2702
+ axis=axis,
2703
+ )
2704
+
2705
+ return res
2706
+
2707
+
2708
+ def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None,
2709
+ include_initial=None):
2710
+ return (x, out)
2711
+
2712
+
2713
+ @array_function_dispatch(_cumulative_prod_dispatcher)
2714
+ def cumulative_prod(x, /, *, axis=None, dtype=None, out=None,
2715
+ include_initial=False):
2716
+ """
2717
+ Return the cumulative product of elements along a given axis.
2718
+
2719
+ This function is an Array API compatible alternative to `numpy.cumprod`.
2720
+
2721
+ Parameters
2722
+ ----------
2723
+ x : array_like
2724
+ Input array.
2725
+ axis : int, optional
2726
+ Axis along which the cumulative product is computed. The default
2727
+ (None) is only allowed for one-dimensional arrays. For arrays
2728
+ with more than one dimension ``axis`` is required.
2729
+ dtype : dtype, optional
2730
+ Type of the returned array, as well as of the accumulator in which
2731
+ the elements are multiplied. If ``dtype`` is not specified, it
2732
+ defaults to the dtype of ``x``, unless ``x`` has an integer dtype
2733
+ with a precision less than that of the default platform integer.
2734
+ In that case, the default platform integer is used instead.
2735
+ out : ndarray, optional
2736
+ Alternative output array in which to place the result. It must
2737
+ have the same shape and buffer length as the expected output
2738
+ but the type of the resulting values will be cast if necessary.
2739
+ See :ref:`ufuncs-output-type` for more details.
2740
+ include_initial : bool, optional
2741
+ Boolean indicating whether to include the initial value (ones) as
2742
+ the first value in the output. With ``include_initial=True``
2743
+ the shape of the output is different than the shape of the input.
2744
+ Default: ``False``.
2745
+
2746
+ Returns
2747
+ -------
2748
+ cumulative_prod_along_axis : ndarray
2749
+ A new array holding the result is returned unless ``out`` is
2750
+ specified, in which case a reference to ``out`` is returned. The
2751
+ result has the same shape as ``x`` if ``include_initial=False``.
2752
+
2753
+ Notes
2754
+ -----
2755
+ Arithmetic is modular when using integer types, and no error is
2756
+ raised on overflow.
2757
+
2758
+ Examples
2759
+ --------
2760
+ >>> a = np.array([1, 2, 3])
2761
+ >>> np.cumulative_prod(a) # intermediate results 1, 1*2
2762
+ ... # total product 1*2*3 = 6
2763
+ array([1, 2, 6])
2764
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
2765
+ >>> np.cumulative_prod(a, dtype=float) # specify type of output
2766
+ array([ 1., 2., 6., 24., 120., 720.])
2767
+
2768
+ The cumulative product for each column (i.e., over the rows) of ``b``:
2769
+
2770
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
2771
+ >>> np.cumulative_prod(b, axis=0)
2772
+ array([[ 1, 2, 3],
2773
+ [ 4, 10, 18]])
2774
+
2775
+ The cumulative product for each row (i.e. over the columns) of ``b``:
2776
+
2777
+ >>> np.cumulative_prod(b, axis=1)
2778
+ array([[ 1, 2, 6],
2779
+ [ 4, 20, 120]])
2780
+
2781
+ """
2782
+ return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial)
2783
+
2784
+
2785
+ def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None,
2786
+ include_initial=None):
2787
+ return (x, out)
2788
+
2789
+
2790
+ @array_function_dispatch(_cumulative_sum_dispatcher)
2791
+ def cumulative_sum(x, /, *, axis=None, dtype=None, out=None,
2792
+ include_initial=False):
2793
+ """
2794
+ Return the cumulative sum of the elements along a given axis.
2795
+
2796
+ This function is an Array API compatible alternative to `numpy.cumsum`.
2797
+
2798
+ Parameters
2799
+ ----------
2800
+ x : array_like
2801
+ Input array.
2802
+ axis : int, optional
2803
+ Axis along which the cumulative sum is computed. The default
2804
+ (None) is only allowed for one-dimensional arrays. For arrays
2805
+ with more than one dimension ``axis`` is required.
2806
+ dtype : dtype, optional
2807
+ Type of the returned array and of the accumulator in which the
2808
+ elements are summed. If ``dtype`` is not specified, it defaults
2809
+ to the dtype of ``x``, unless ``x`` has an integer dtype with
2810
+ a precision less than that of the default platform integer.
2811
+ In that case, the default platform integer is used.
2812
+ out : ndarray, optional
2813
+ Alternative output array in which to place the result. It must
2814
+ have the same shape and buffer length as the expected output
2815
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
2816
+ for more details.
2817
+ include_initial : bool, optional
2818
+ Boolean indicating whether to include the initial value (zeros) as
2819
+ the first value in the output. With ``include_initial=True``
2820
+ the shape of the output is different than the shape of the input.
2821
+ Default: ``False``.
2822
+
2823
+ Returns
2824
+ -------
2825
+ cumulative_sum_along_axis : ndarray
2826
+ A new array holding the result is returned unless ``out`` is
2827
+ specified, in which case a reference to ``out`` is returned. The
2828
+ result has the same shape as ``x`` if ``include_initial=False``.
2829
+
2830
+ See Also
2831
+ --------
2832
+ sum : Sum array elements.
2833
+ trapezoid : Integration of array values using composite trapezoidal rule.
2834
+ diff : Calculate the n-th discrete difference along given axis.
2835
+
2836
+ Notes
2837
+ -----
2838
+ Arithmetic is modular when using integer types, and no error is
2839
+ raised on overflow.
2840
+
2841
+ ``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
2842
+ floating-point values since ``sum`` may use a pairwise summation routine,
2843
+ reducing the roundoff-error. See `sum` for more information.
2844
+
2845
+ Examples
2846
+ --------
2847
+ >>> a = np.array([1, 2, 3, 4, 5, 6])
2848
+ >>> a
2849
+ array([1, 2, 3, 4, 5, 6])
2850
+ >>> np.cumulative_sum(a)
2851
+ array([ 1, 3, 6, 10, 15, 21])
2852
+ >>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
2853
+ array([ 1., 3., 6., 10., 15., 21.])
2854
+
2855
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]])
2856
+ >>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
2857
+ array([[1, 2, 3],
2858
+ [5, 7, 9]])
2859
+ >>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
2860
+ array([[ 1, 3, 6],
2861
+ [ 4, 9, 15]])
2862
+
2863
+ ``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
2864
+
2865
+ >>> c = np.array([1, 2e-9, 3e-9] * 1000000)
2866
+ >>> np.cumulative_sum(c)[-1]
2867
+ 1000000.0050045159
2868
+ >>> c.sum()
2869
+ 1000000.0050000029
2870
+
2871
+ """
2872
+ return _cumulative_func(x, um.add, axis, dtype, out, include_initial)
2873
+
2874
+
2875
+ def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
2876
+ return (a, out)
2877
+
2878
+
2879
+ @array_function_dispatch(_cumsum_dispatcher)
2880
+ def cumsum(a, axis=None, dtype=None, out=None):
2881
+ """
2882
+ Return the cumulative sum of the elements along a given axis.
2883
+
2884
+ Parameters
2885
+ ----------
2886
+ a : array_like
2887
+ Input array.
2888
+ axis : int, optional
2889
+ Axis along which the cumulative sum is computed. The default
2890
+ (None) is to compute the cumsum over the flattened array.
2891
+ dtype : dtype, optional
2892
+ Type of the returned array and of the accumulator in which the
2893
+ elements are summed. If `dtype` is not specified, it defaults
2894
+ to the dtype of `a`, unless `a` has an integer dtype with a
2895
+ precision less than that of the default platform integer. In
2896
+ that case, the default platform integer is used.
2897
+ out : ndarray, optional
2898
+ Alternative output array in which to place the result. It must
2899
+ have the same shape and buffer length as the expected output
2900
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type`
2901
+ for more details.
2902
+
2903
+ Returns
2904
+ -------
2905
+ cumsum_along_axis : ndarray.
2906
+ A new array holding the result is returned unless `out` is
2907
+ specified, in which case a reference to `out` is returned. The
2908
+ result has the same size as `a`, and the same shape as `a` if
2909
+ `axis` is not None or `a` is a 1-d array.
2910
+
2911
+ See Also
2912
+ --------
2913
+ cumulative_sum : Array API compatible alternative for ``cumsum``.
2914
+ sum : Sum array elements.
2915
+ trapezoid : Integration of array values using composite trapezoidal rule.
2916
+ diff : Calculate the n-th discrete difference along given axis.
2917
+
2918
+ Notes
2919
+ -----
2920
+ Arithmetic is modular when using integer types, and no error is
2921
+ raised on overflow.
2922
+
2923
+ ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
2924
+ values since ``sum`` may use a pairwise summation routine, reducing
2925
+ the roundoff-error. See `sum` for more information.
2926
+
2927
+ Examples
2928
+ --------
2929
+ >>> import numpy as np
2930
+ >>> a = np.array([[1,2,3], [4,5,6]])
2931
+ >>> a
2932
+ array([[1, 2, 3],
2933
+ [4, 5, 6]])
2934
+ >>> np.cumsum(a)
2935
+ array([ 1, 3, 6, 10, 15, 21])
2936
+ >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
2937
+ array([ 1., 3., 6., 10., 15., 21.])
2938
+
2939
+ >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
2940
+ array([[1, 2, 3],
2941
+ [5, 7, 9]])
2942
+ >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
2943
+ array([[ 1, 3, 6],
2944
+ [ 4, 9, 15]])
2945
+
2946
+ ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
2947
+
2948
+ >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
2949
+ >>> b.cumsum()[-1]
2950
+ 1000000.0050045159
2951
+ >>> b.sum()
2952
+ 1000000.0050000029
2953
+
2954
+ """
2955
+ return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
2956
+
2957
+
2958
+ def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
2959
+ return (a, out)
2960
+
2961
+
2962
+ @array_function_dispatch(_ptp_dispatcher)
2963
+ def ptp(a, axis=None, out=None, keepdims=np._NoValue):
2964
+ """
2965
+ Range of values (maximum - minimum) along an axis.
2966
+
2967
+ The name of the function comes from the acronym for 'peak to peak'.
2968
+
2969
+ .. warning::
2970
+ `ptp` preserves the data type of the array. This means the
2971
+ return value for an input of signed integers with n bits
2972
+ (e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
2973
+ with n bits. In that case, peak-to-peak values greater than
2974
+ ``2**(n-1)-1`` will be returned as negative values. An example
2975
+ with a work-around is shown below.
2976
+
2977
+ Parameters
2978
+ ----------
2979
+ a : array_like
2980
+ Input values.
2981
+ axis : None or int or tuple of ints, optional
2982
+ Axis along which to find the peaks. By default, flatten the
2983
+ array. `axis` may be negative, in
2984
+ which case it counts from the last to the first axis.
2985
+ If this is a tuple of ints, a reduction is performed on multiple
2986
+ axes, instead of a single axis or all the axes as before.
2987
+ out : array_like
2988
+ Alternative output array in which to place the result. It must
2989
+ have the same shape and buffer length as the expected output,
2990
+ but the type of the output values will be cast if necessary.
2991
+
2992
+ keepdims : bool, optional
2993
+ If this is set to True, the axes which are reduced are left
2994
+ in the result as dimensions with size one. With this option,
2995
+ the result will broadcast correctly against the input array.
2996
+
2997
+ If the default value is passed, then `keepdims` will not be
2998
+ passed through to the `ptp` method of sub-classes of
2999
+ `ndarray`, however any non-default value will be. If the
3000
+ sub-class' method does not implement `keepdims` any
3001
+ exceptions will be raised.
3002
+
3003
+ Returns
3004
+ -------
3005
+ ptp : ndarray or scalar
3006
+ The range of a given array - `scalar` if array is one-dimensional
3007
+ or a new array holding the result along the given axis
3008
+
3009
+ Examples
3010
+ --------
3011
+ >>> import numpy as np
3012
+ >>> x = np.array([[4, 9, 2, 10],
3013
+ ... [6, 9, 7, 12]])
3014
+
3015
+ >>> np.ptp(x, axis=1)
3016
+ array([8, 6])
3017
+
3018
+ >>> np.ptp(x, axis=0)
3019
+ array([2, 0, 5, 2])
3020
+
3021
+ >>> np.ptp(x)
3022
+ 10
3023
+
3024
+ This example shows that a negative value can be returned when
3025
+ the input is an array of signed integers.
3026
+
3027
+ >>> y = np.array([[1, 127],
3028
+ ... [0, 127],
3029
+ ... [-1, 127],
3030
+ ... [-2, 127]], dtype=np.int8)
3031
+ >>> np.ptp(y, axis=1)
3032
+ array([ 126, 127, -128, -127], dtype=int8)
3033
+
3034
+ A work-around is to use the `view()` method to view the result as
3035
+ unsigned integers with the same bit width:
3036
+
3037
+ >>> np.ptp(y, axis=1).view(np.uint8)
3038
+ array([126, 127, 128, 129], dtype=uint8)
3039
+
3040
+ """
3041
+ kwargs = {}
3042
+ if keepdims is not np._NoValue:
3043
+ kwargs['keepdims'] = keepdims
3044
+ return _methods._ptp(a, axis=axis, out=out, **kwargs)
3045
+
3046
+
3047
+ def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
3048
+ where=None):
3049
+ return (a, out)
3050
+
3051
+
3052
+ @array_function_dispatch(_max_dispatcher)
3053
+ @set_module('numpy')
3054
+ def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3055
+ where=np._NoValue):
3056
+ """
3057
+ Return the maximum of an array or maximum along an axis.
3058
+
3059
+ Parameters
3060
+ ----------
3061
+ a : array_like
3062
+ Input data.
3063
+ axis : None or int or tuple of ints, optional
3064
+ Axis or axes along which to operate. By default, flattened input is
3065
+ used. If this is a tuple of ints, the maximum is selected over
3066
+ multiple axes, instead of a single axis or all the axes as before.
3067
+
3068
+ out : ndarray, optional
3069
+ Alternative output array in which to place the result. Must
3070
+ be of the same shape and buffer length as the expected output.
3071
+ See :ref:`ufuncs-output-type` for more details.
3072
+
3073
+ keepdims : bool, optional
3074
+ If this is set to True, the axes which are reduced are left
3075
+ in the result as dimensions with size one. With this option,
3076
+ the result will broadcast correctly against the input array.
3077
+
3078
+ If the default value is passed, then `keepdims` will not be
3079
+ passed through to the ``max`` method of sub-classes of
3080
+ `ndarray`, however any non-default value will be. If the
3081
+ sub-class' method does not implement `keepdims` any
3082
+ exceptions will be raised.
3083
+
3084
+ initial : scalar, optional
3085
+ The minimum value of an output element. Must be present to allow
3086
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
3087
+
3088
+ where : array_like of bool, optional
3089
+ Elements to compare for the maximum. See `~numpy.ufunc.reduce`
3090
+ for details.
3091
+
3092
+ Returns
3093
+ -------
3094
+ max : ndarray or scalar
3095
+ Maximum of `a`. If `axis` is None, the result is a scalar value.
3096
+ If `axis` is an int, the result is an array of dimension
3097
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
3098
+ dimension ``a.ndim - len(axis)``.
3099
+
3100
+ See Also
3101
+ --------
3102
+ amin :
3103
+ The minimum value of an array along a given axis, propagating any NaNs.
3104
+ nanmax :
3105
+ The maximum value of an array along a given axis, ignoring any NaNs.
3106
+ maximum :
3107
+ Element-wise maximum of two arrays, propagating any NaNs.
3108
+ fmax :
3109
+ Element-wise maximum of two arrays, ignoring any NaNs.
3110
+ argmax :
3111
+ Return the indices of the maximum values.
3112
+
3113
+ nanmin, minimum, fmin
3114
+
3115
+ Notes
3116
+ -----
3117
+ NaN values are propagated, that is if at least one item is NaN, the
3118
+ corresponding max value will be NaN as well. To ignore NaN values
3119
+ (MATLAB behavior), please use nanmax.
3120
+
3121
+ Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
3122
+ ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
3123
+ ``max(a, axis=0)``.
3124
+
3125
+ Examples
3126
+ --------
3127
+ >>> import numpy as np
3128
+ >>> a = np.arange(4).reshape((2,2))
3129
+ >>> a
3130
+ array([[0, 1],
3131
+ [2, 3]])
3132
+ >>> np.max(a) # Maximum of the flattened array
3133
+ 3
3134
+ >>> np.max(a, axis=0) # Maxima along the first axis
3135
+ array([2, 3])
3136
+ >>> np.max(a, axis=1) # Maxima along the second axis
3137
+ array([1, 3])
3138
+ >>> np.max(a, where=[False, True], initial=-1, axis=0)
3139
+ array([-1, 3])
3140
+ >>> b = np.arange(5, dtype=float)
3141
+ >>> b[2] = np.nan
3142
+ >>> np.max(b)
3143
+ np.float64(nan)
3144
+ >>> np.max(b, where=~np.isnan(b), initial=-1)
3145
+ 4.0
3146
+ >>> np.nanmax(b)
3147
+ 4.0
3148
+
3149
+ You can use an initial value to compute the maximum of an empty slice, or
3150
+ to initialize it to a different value:
3151
+
3152
+ >>> np.max([[-50], [10]], axis=-1, initial=0)
3153
+ array([ 0, 10])
3154
+
3155
+ Notice that the initial value is used as one of the elements for which the
3156
+ maximum is determined, unlike for the default argument Python's max
3157
+ function, which is only used for empty iterables.
3158
+
3159
+ >>> np.max([5], initial=6)
3160
+ 6
3161
+ >>> max([5], default=6)
3162
+ 5
3163
+ """
3164
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
3165
+ keepdims=keepdims, initial=initial, where=where)
3166
+
3167
+
3168
+ @array_function_dispatch(_max_dispatcher)
3169
+ def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3170
+ where=np._NoValue):
3171
+ """
3172
+ Return the maximum of an array or maximum along an axis.
3173
+
3174
+ `amax` is an alias of `~numpy.max`.
3175
+
3176
+ See Also
3177
+ --------
3178
+ max : alias of this function
3179
+ ndarray.max : equivalent method
3180
+ """
3181
+ return _wrapreduction(a, np.maximum, 'max', axis, None, out,
3182
+ keepdims=keepdims, initial=initial, where=where)
3183
+
3184
+
3185
+ def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
3186
+ where=None):
3187
+ return (a, out)
3188
+
3189
+
3190
+ @array_function_dispatch(_min_dispatcher)
3191
+ def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3192
+ where=np._NoValue):
3193
+ """
3194
+ Return the minimum of an array or minimum along an axis.
3195
+
3196
+ Parameters
3197
+ ----------
3198
+ a : array_like
3199
+ Input data.
3200
+ axis : None or int or tuple of ints, optional
3201
+ Axis or axes along which to operate. By default, flattened input is
3202
+ used.
3203
+
3204
+ If this is a tuple of ints, the minimum is selected over multiple axes,
3205
+ instead of a single axis or all the axes as before.
3206
+ out : ndarray, optional
3207
+ Alternative output array in which to place the result. Must
3208
+ be of the same shape and buffer length as the expected output.
3209
+ See :ref:`ufuncs-output-type` for more details.
3210
+
3211
+ keepdims : bool, optional
3212
+ If this is set to True, the axes which are reduced are left
3213
+ in the result as dimensions with size one. With this option,
3214
+ the result will broadcast correctly against the input array.
3215
+
3216
+ If the default value is passed, then `keepdims` will not be
3217
+ passed through to the ``min`` method of sub-classes of
3218
+ `ndarray`, however any non-default value will be. If the
3219
+ sub-class' method does not implement `keepdims` any
3220
+ exceptions will be raised.
3221
+
3222
+ initial : scalar, optional
3223
+ The maximum value of an output element. Must be present to allow
3224
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
3225
+
3226
+ where : array_like of bool, optional
3227
+ Elements to compare for the minimum. See `~numpy.ufunc.reduce`
3228
+ for details.
3229
+
3230
+ Returns
3231
+ -------
3232
+ min : ndarray or scalar
3233
+ Minimum of `a`. If `axis` is None, the result is a scalar value.
3234
+ If `axis` is an int, the result is an array of dimension
3235
+ ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
3236
+ dimension ``a.ndim - len(axis)``.
3237
+
3238
+ See Also
3239
+ --------
3240
+ amax :
3241
+ The maximum value of an array along a given axis, propagating any NaNs.
3242
+ nanmin :
3243
+ The minimum value of an array along a given axis, ignoring any NaNs.
3244
+ minimum :
3245
+ Element-wise minimum of two arrays, propagating any NaNs.
3246
+ fmin :
3247
+ Element-wise minimum of two arrays, ignoring any NaNs.
3248
+ argmin :
3249
+ Return the indices of the minimum values.
3250
+
3251
+ nanmax, maximum, fmax
3252
+
3253
+ Notes
3254
+ -----
3255
+ NaN values are propagated, that is if at least one item is NaN, the
3256
+ corresponding min value will be NaN as well. To ignore NaN values
3257
+ (MATLAB behavior), please use nanmin.
3258
+
3259
+ Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
3260
+ ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
3261
+ ``min(a, axis=0)``.
3262
+
3263
+ Examples
3264
+ --------
3265
+ >>> import numpy as np
3266
+ >>> a = np.arange(4).reshape((2,2))
3267
+ >>> a
3268
+ array([[0, 1],
3269
+ [2, 3]])
3270
+ >>> np.min(a) # Minimum of the flattened array
3271
+ 0
3272
+ >>> np.min(a, axis=0) # Minima along the first axis
3273
+ array([0, 1])
3274
+ >>> np.min(a, axis=1) # Minima along the second axis
3275
+ array([0, 2])
3276
+ >>> np.min(a, where=[False, True], initial=10, axis=0)
3277
+ array([10, 1])
3278
+
3279
+ >>> b = np.arange(5, dtype=float)
3280
+ >>> b[2] = np.nan
3281
+ >>> np.min(b)
3282
+ np.float64(nan)
3283
+ >>> np.min(b, where=~np.isnan(b), initial=10)
3284
+ 0.0
3285
+ >>> np.nanmin(b)
3286
+ 0.0
3287
+
3288
+ >>> np.min([[-50], [10]], axis=-1, initial=0)
3289
+ array([-50, 0])
3290
+
3291
+ Notice that the initial value is used as one of the elements for which the
3292
+ minimum is determined, unlike for the default argument Python's max
3293
+ function, which is only used for empty iterables.
3294
+
3295
+ Notice that this isn't the same as Python's ``default`` argument.
3296
+
3297
+ >>> np.min([6], initial=5)
3298
+ 5
3299
+ >>> min([6], default=5)
3300
+ 6
3301
+ """
3302
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
3303
+ keepdims=keepdims, initial=initial, where=where)
3304
+
3305
+
3306
+ @array_function_dispatch(_min_dispatcher)
3307
+ def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3308
+ where=np._NoValue):
3309
+ """
3310
+ Return the minimum of an array or minimum along an axis.
3311
+
3312
+ `amin` is an alias of `~numpy.min`.
3313
+
3314
+ See Also
3315
+ --------
3316
+ min : alias of this function
3317
+ ndarray.min : equivalent method
3318
+ """
3319
+ return _wrapreduction(a, np.minimum, 'min', axis, None, out,
3320
+ keepdims=keepdims, initial=initial, where=where)
3321
+
3322
+
3323
+ def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
3324
+ initial=None, where=None):
3325
+ return (a, out)
3326
+
3327
+
3328
+ @array_function_dispatch(_prod_dispatcher)
3329
+ def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
3330
+ initial=np._NoValue, where=np._NoValue):
3331
+ """
3332
+ Return the product of array elements over a given axis.
3333
+
3334
+ Parameters
3335
+ ----------
3336
+ a : array_like
3337
+ Input data.
3338
+ axis : None or int or tuple of ints, optional
3339
+ Axis or axes along which a product is performed. The default,
3340
+ axis=None, will calculate the product of all the elements in the
3341
+ input array. If axis is negative it counts from the last to the
3342
+ first axis.
3343
+
3344
+ If axis is a tuple of ints, a product is performed on all of the
3345
+ axes specified in the tuple instead of a single axis or all the
3346
+ axes as before.
3347
+ dtype : dtype, optional
3348
+ The type of the returned array, as well as of the accumulator in
3349
+ which the elements are multiplied. The dtype of `a` is used by
3350
+ default unless `a` has an integer dtype of less precision than the
3351
+ default platform integer. In that case, if `a` is signed then the
3352
+ platform integer is used while if `a` is unsigned then an unsigned
3353
+ integer of the same precision as the platform integer is used.
3354
+ out : ndarray, optional
3355
+ Alternative output array in which to place the result. It must have
3356
+ the same shape as the expected output, but the type of the output
3357
+ values will be cast if necessary.
3358
+ keepdims : bool, optional
3359
+ If this is set to True, the axes which are reduced are left in the
3360
+ result as dimensions with size one. With this option, the result
3361
+ will broadcast correctly against the input array.
3362
+
3363
+ If the default value is passed, then `keepdims` will not be
3364
+ passed through to the `prod` method of sub-classes of
3365
+ `ndarray`, however any non-default value will be. If the
3366
+ sub-class' method does not implement `keepdims` any
3367
+ exceptions will be raised.
3368
+ initial : scalar, optional
3369
+ The starting value for this product. See `~numpy.ufunc.reduce`
3370
+ for details.
3371
+ where : array_like of bool, optional
3372
+ Elements to include in the product. See `~numpy.ufunc.reduce`
3373
+ for details.
3374
+
3375
+ Returns
3376
+ -------
3377
+ product_along_axis : ndarray, see `dtype` parameter above.
3378
+ An array shaped as `a` but with the specified axis removed.
3379
+ Returns a reference to `out` if specified.
3380
+
3381
+ See Also
3382
+ --------
3383
+ ndarray.prod : equivalent method
3384
+ :ref:`ufuncs-output-type`
3385
+
3386
+ Notes
3387
+ -----
3388
+ Arithmetic is modular when using integer types, and no error is
3389
+ raised on overflow. That means that, on a 32-bit platform:
3390
+
3391
+ >>> x = np.array([536870910, 536870910, 536870910, 536870910])
3392
+ >>> np.prod(x)
3393
+ 16 # may vary
3394
+
3395
+ The product of an empty array is the neutral element 1:
3396
+
3397
+ >>> np.prod([])
3398
+ 1.0
3399
+
3400
+ Examples
3401
+ --------
3402
+ By default, calculate the product of all elements:
3403
+
3404
+ >>> import numpy as np
3405
+ >>> np.prod([1.,2.])
3406
+ 2.0
3407
+
3408
+ Even when the input array is two-dimensional:
3409
+
3410
+ >>> a = np.array([[1., 2.], [3., 4.]])
3411
+ >>> np.prod(a)
3412
+ 24.0
3413
+
3414
+ But we can also specify the axis over which to multiply:
3415
+
3416
+ >>> np.prod(a, axis=1)
3417
+ array([ 2., 12.])
3418
+ >>> np.prod(a, axis=0)
3419
+ array([3., 8.])
3420
+
3421
+ Or select specific elements to include:
3422
+
3423
+ >>> np.prod([1., np.nan, 3.], where=[True, False, True])
3424
+ 3.0
3425
+
3426
+ If the type of `x` is unsigned, then the output type is
3427
+ the unsigned platform integer:
3428
+
3429
+ >>> x = np.array([1, 2, 3], dtype=np.uint8)
3430
+ >>> np.prod(x).dtype == np.uint
3431
+ True
3432
+
3433
+ If `x` is of a signed integer type, then the output type
3434
+ is the default platform integer:
3435
+
3436
+ >>> x = np.array([1, 2, 3], dtype=np.int8)
3437
+ >>> np.prod(x).dtype == int
3438
+ True
3439
+
3440
+ You can also start the product with a value other than one:
3441
+
3442
+ >>> np.prod([1, 2], initial=5)
3443
+ 10
3444
+ """
3445
+ return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
3446
+ keepdims=keepdims, initial=initial, where=where)
3447
+
3448
+
3449
+ def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
3450
+ return (a, out)
3451
+
3452
+
3453
+ @array_function_dispatch(_cumprod_dispatcher)
3454
+ def cumprod(a, axis=None, dtype=None, out=None):
3455
+ """
3456
+ Return the cumulative product of elements along a given axis.
3457
+
3458
+ Parameters
3459
+ ----------
3460
+ a : array_like
3461
+ Input array.
3462
+ axis : int, optional
3463
+ Axis along which the cumulative product is computed. By default
3464
+ the input is flattened.
3465
+ dtype : dtype, optional
3466
+ Type of the returned array, as well as of the accumulator in which
3467
+ the elements are multiplied. If *dtype* is not specified, it
3468
+ defaults to the dtype of `a`, unless `a` has an integer dtype with
3469
+ a precision less than that of the default platform integer. In
3470
+ that case, the default platform integer is used instead.
3471
+ out : ndarray, optional
3472
+ Alternative output array in which to place the result. It must
3473
+ have the same shape and buffer length as the expected output
3474
+ but the type of the resulting values will be cast if necessary.
3475
+
3476
+ Returns
3477
+ -------
3478
+ cumprod : ndarray
3479
+ A new array holding the result is returned unless `out` is
3480
+ specified, in which case a reference to out is returned.
3481
+
3482
+ See Also
3483
+ --------
3484
+ cumulative_prod : Array API compatible alternative for ``cumprod``.
3485
+ :ref:`ufuncs-output-type`
3486
+
3487
+ Notes
3488
+ -----
3489
+ Arithmetic is modular when using integer types, and no error is
3490
+ raised on overflow.
3491
+
3492
+ Examples
3493
+ --------
3494
+ >>> import numpy as np
3495
+ >>> a = np.array([1,2,3])
3496
+ >>> np.cumprod(a) # intermediate results 1, 1*2
3497
+ ... # total product 1*2*3 = 6
3498
+ array([1, 2, 6])
3499
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]])
3500
+ >>> np.cumprod(a, dtype=float) # specify type of output
3501
+ array([ 1., 2., 6., 24., 120., 720.])
3502
+
3503
+ The cumulative product for each column (i.e., over the rows) of `a`:
3504
+
3505
+ >>> np.cumprod(a, axis=0)
3506
+ array([[ 1, 2, 3],
3507
+ [ 4, 10, 18]])
3508
+
3509
+ The cumulative product for each row (i.e. over the columns) of `a`:
3510
+
3511
+ >>> np.cumprod(a,axis=1)
3512
+ array([[ 1, 2, 6],
3513
+ [ 4, 20, 120]])
3514
+
3515
+ """
3516
+ return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
3517
+
3518
+
3519
+ def _ndim_dispatcher(a):
3520
+ return (a,)
3521
+
3522
+
3523
+ @array_function_dispatch(_ndim_dispatcher)
3524
+ def ndim(a):
3525
+ """
3526
+ Return the number of dimensions of an array.
3527
+
3528
+ Parameters
3529
+ ----------
3530
+ a : array_like
3531
+ Input array. If it is not already an ndarray, a conversion is
3532
+ attempted.
3533
+
3534
+ Returns
3535
+ -------
3536
+ number_of_dimensions : int
3537
+ The number of dimensions in `a`. Scalars are zero-dimensional.
3538
+
3539
+ See Also
3540
+ --------
3541
+ ndarray.ndim : equivalent method
3542
+ shape : dimensions of array
3543
+ ndarray.shape : dimensions of array
3544
+
3545
+ Examples
3546
+ --------
3547
+ >>> import numpy as np
3548
+ >>> np.ndim([[1,2,3],[4,5,6]])
3549
+ 2
3550
+ >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
3551
+ 2
3552
+ >>> np.ndim(1)
3553
+ 0
3554
+
3555
+ """
3556
+ try:
3557
+ return a.ndim
3558
+ except AttributeError:
3559
+ return asarray(a).ndim
3560
+
3561
+
3562
+ def _size_dispatcher(a, axis=None):
3563
+ return (a,)
3564
+
3565
+
3566
+ @array_function_dispatch(_size_dispatcher)
3567
+ def size(a, axis=None):
3568
+ """
3569
+ Return the number of elements along a given axis.
3570
+
3571
+ Parameters
3572
+ ----------
3573
+ a : array_like
3574
+ Input data.
3575
+ axis : int, optional
3576
+ Axis along which the elements are counted. By default, give
3577
+ the total number of elements.
3578
+
3579
+ Returns
3580
+ -------
3581
+ element_count : int
3582
+ Number of elements along the specified axis.
3583
+
3584
+ See Also
3585
+ --------
3586
+ shape : dimensions of array
3587
+ ndarray.shape : dimensions of array
3588
+ ndarray.size : number of elements in array
3589
+
3590
+ Examples
3591
+ --------
3592
+ >>> import numpy as np
3593
+ >>> a = np.array([[1,2,3],[4,5,6]])
3594
+ >>> np.size(a)
3595
+ 6
3596
+ >>> np.size(a,1)
3597
+ 3
3598
+ >>> np.size(a,0)
3599
+ 2
3600
+
3601
+ """
3602
+ if axis is None:
3603
+ try:
3604
+ return a.size
3605
+ except AttributeError:
3606
+ return asarray(a).size
3607
+ else:
3608
+ try:
3609
+ return a.shape[axis]
3610
+ except AttributeError:
3611
+ return asarray(a).shape[axis]
3612
+
3613
+
3614
+ def _round_dispatcher(a, decimals=None, out=None):
3615
+ return (a, out)
3616
+
3617
+
3618
+ @array_function_dispatch(_round_dispatcher)
3619
+ def round(a, decimals=0, out=None):
3620
+ """
3621
+ Evenly round to the given number of decimals.
3622
+
3623
+ Parameters
3624
+ ----------
3625
+ a : array_like
3626
+ Input data.
3627
+ decimals : int, optional
3628
+ Number of decimal places to round to (default: 0). If
3629
+ decimals is negative, it specifies the number of positions to
3630
+ the left of the decimal point.
3631
+ out : ndarray, optional
3632
+ Alternative output array in which to place the result. It must have
3633
+ the same shape as the expected output, but the type of the output
3634
+ values will be cast if necessary. See :ref:`ufuncs-output-type`
3635
+ for more details.
3636
+
3637
+ Returns
3638
+ -------
3639
+ rounded_array : ndarray
3640
+ An array of the same type as `a`, containing the rounded values.
3641
+ Unless `out` was specified, a new array is created. A reference to
3642
+ the result is returned.
3643
+
3644
+ The real and imaginary parts of complex numbers are rounded
3645
+ separately. The result of rounding a float is a float.
3646
+
3647
+ See Also
3648
+ --------
3649
+ ndarray.round : equivalent method
3650
+ around : an alias for this function
3651
+ ceil, fix, floor, rint, trunc
3652
+
3653
+
3654
+ Notes
3655
+ -----
3656
+ For values exactly halfway between rounded decimal values, NumPy
3657
+ rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
3658
+ -0.5 and 0.5 round to 0.0, etc.
3659
+
3660
+ ``np.round`` uses a fast but sometimes inexact algorithm to round
3661
+ floating-point datatypes. For positive `decimals` it is equivalent to
3662
+ ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
3663
+ error due to the inexact representation of decimal fractions in the IEEE
3664
+ floating point standard [1]_ and errors introduced when scaling by powers
3665
+ of ten. For instance, note the extra "1" in the following:
3666
+
3667
+ >>> np.round(56294995342131.5, 3)
3668
+ 56294995342131.51
3669
+
3670
+ If your goal is to print such values with a fixed number of decimals, it is
3671
+ preferable to use numpy's float printing routines to limit the number of
3672
+ printed decimals:
3673
+
3674
+ >>> np.format_float_positional(56294995342131.5, precision=3)
3675
+ '56294995342131.5'
3676
+
3677
+ The float printing routines use an accurate but much more computationally
3678
+ demanding algorithm to compute the number of digits after the decimal
3679
+ point.
3680
+
3681
+ Alternatively, Python's builtin `round` function uses a more accurate
3682
+ but slower algorithm for 64-bit floating point values:
3683
+
3684
+ >>> round(56294995342131.5, 3)
3685
+ 56294995342131.5
3686
+ >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
3687
+ (16.06, 16.05)
3688
+
3689
+
3690
+ References
3691
+ ----------
3692
+ .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
3693
+ https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
3694
+
3695
+ Examples
3696
+ --------
3697
+ >>> import numpy as np
3698
+ >>> np.round([0.37, 1.64])
3699
+ array([0., 2.])
3700
+ >>> np.round([0.37, 1.64], decimals=1)
3701
+ array([0.4, 1.6])
3702
+ >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
3703
+ array([0., 2., 2., 4., 4.])
3704
+ >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
3705
+ array([ 1, 2, 3, 11])
3706
+ >>> np.round([1,2,3,11], decimals=-1)
3707
+ array([ 0, 0, 0, 10])
3708
+
3709
+ """
3710
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
3711
+
3712
+
3713
+ @array_function_dispatch(_round_dispatcher)
3714
+ def around(a, decimals=0, out=None):
3715
+ """
3716
+ Round an array to the given number of decimals.
3717
+
3718
+ `around` is an alias of `~numpy.round`.
3719
+
3720
+ See Also
3721
+ --------
3722
+ ndarray.round : equivalent method
3723
+ round : alias for this function
3724
+ ceil, fix, floor, rint, trunc
3725
+
3726
+ """
3727
+ return _wrapfunc(a, 'round', decimals=decimals, out=out)
3728
+
3729
+
3730
+ def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
3731
+ where=None):
3732
+ return (a, where, out)
3733
+
3734
+
3735
+ @array_function_dispatch(_mean_dispatcher)
3736
+ def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
3737
+ where=np._NoValue):
3738
+ """
3739
+ Compute the arithmetic mean along the specified axis.
3740
+
3741
+ Returns the average of the array elements. The average is taken over
3742
+ the flattened array by default, otherwise over the specified axis.
3743
+ `float64` intermediate and return values are used for integer inputs.
3744
+
3745
+ Parameters
3746
+ ----------
3747
+ a : array_like
3748
+ Array containing numbers whose mean is desired. If `a` is not an
3749
+ array, a conversion is attempted.
3750
+ axis : None or int or tuple of ints, optional
3751
+ Axis or axes along which the means are computed. The default is to
3752
+ compute the mean of the flattened array.
3753
+
3754
+ If this is a tuple of ints, a mean is performed over multiple axes,
3755
+ instead of a single axis or all the axes as before.
3756
+ dtype : data-type, optional
3757
+ Type to use in computing the mean. For integer inputs, the default
3758
+ is `float64`; for floating point inputs, it is the same as the
3759
+ input dtype.
3760
+ out : ndarray, optional
3761
+ Alternate output array in which to place the result. The default
3762
+ is ``None``; if provided, it must have the same shape as the
3763
+ expected output, but the type will be cast if necessary.
3764
+ See :ref:`ufuncs-output-type` for more details.
3765
+ See :ref:`ufuncs-output-type` for more details.
3766
+
3767
+ keepdims : bool, optional
3768
+ If this is set to True, the axes which are reduced are left
3769
+ in the result as dimensions with size one. With this option,
3770
+ the result will broadcast correctly against the input array.
3771
+
3772
+ If the default value is passed, then `keepdims` will not be
3773
+ passed through to the `mean` method of sub-classes of
3774
+ `ndarray`, however any non-default value will be. If the
3775
+ sub-class' method does not implement `keepdims` any
3776
+ exceptions will be raised.
3777
+
3778
+ where : array_like of bool, optional
3779
+ Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
3780
+
3781
+ .. versionadded:: 1.20.0
3782
+
3783
+ Returns
3784
+ -------
3785
+ m : ndarray, see dtype parameter above
3786
+ If `out=None`, returns a new array containing the mean values,
3787
+ otherwise a reference to the output array is returned.
3788
+
3789
+ See Also
3790
+ --------
3791
+ average : Weighted average
3792
+ std, var, nanmean, nanstd, nanvar
3793
+
3794
+ Notes
3795
+ -----
3796
+ The arithmetic mean is the sum of the elements along the axis divided
3797
+ by the number of elements.
3798
+
3799
+ Note that for floating-point input, the mean is computed using the
3800
+ same precision the input has. Depending on the input data, this can
3801
+ cause the results to be inaccurate, especially for `float32` (see
3802
+ example below). Specifying a higher-precision accumulator using the
3803
+ `dtype` keyword can alleviate this issue.
3804
+
3805
+ By default, `float16` results are computed using `float32` intermediates
3806
+ for extra precision.
3807
+
3808
+ Examples
3809
+ --------
3810
+ >>> import numpy as np
3811
+ >>> a = np.array([[1, 2], [3, 4]])
3812
+ >>> np.mean(a)
3813
+ 2.5
3814
+ >>> np.mean(a, axis=0)
3815
+ array([2., 3.])
3816
+ >>> np.mean(a, axis=1)
3817
+ array([1.5, 3.5])
3818
+
3819
+ In single precision, `mean` can be inaccurate:
3820
+
3821
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
3822
+ >>> a[0, :] = 1.0
3823
+ >>> a[1, :] = 0.1
3824
+ >>> np.mean(a)
3825
+ np.float32(0.54999924)
3826
+
3827
+ Computing the mean in float64 is more accurate:
3828
+
3829
+ >>> np.mean(a, dtype=np.float64)
3830
+ 0.55000000074505806 # may vary
3831
+
3832
+ Computing the mean in timedelta64 is available:
3833
+
3834
+ >>> b = np.array([1, 3], dtype="timedelta64[D]")
3835
+ >>> np.mean(b)
3836
+ np.timedelta64(2,'D')
3837
+
3838
+ Specifying a where argument:
3839
+
3840
+ >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
3841
+ >>> np.mean(a)
3842
+ 12.0
3843
+ >>> np.mean(a, where=[[True], [False], [False]])
3844
+ 9.0
3845
+
3846
+ """
3847
+ kwargs = {}
3848
+ if keepdims is not np._NoValue:
3849
+ kwargs['keepdims'] = keepdims
3850
+ if where is not np._NoValue:
3851
+ kwargs['where'] = where
3852
+ if type(a) is not mu.ndarray:
3853
+ try:
3854
+ mean = a.mean
3855
+ except AttributeError:
3856
+ pass
3857
+ else:
3858
+ return mean(axis=axis, dtype=dtype, out=out, **kwargs)
3859
+
3860
+ return _methods._mean(a, axis=axis, dtype=dtype,
3861
+ out=out, **kwargs)
3862
+
3863
+
3864
+ def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3865
+ keepdims=None, *, where=None, mean=None, correction=None):
3866
+ return (a, where, out, mean)
3867
+
3868
+
3869
+ @array_function_dispatch(_std_dispatcher)
3870
+ def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3871
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
3872
+ r"""
3873
+ Compute the standard deviation along the specified axis.
3874
+
3875
+ Returns the standard deviation, a measure of the spread of a distribution,
3876
+ of the array elements. The standard deviation is computed for the
3877
+ flattened array by default, otherwise over the specified axis.
3878
+
3879
+ Parameters
3880
+ ----------
3881
+ a : array_like
3882
+ Calculate the standard deviation of these values.
3883
+ axis : None or int or tuple of ints, optional
3884
+ Axis or axes along which the standard deviation is computed. The
3885
+ default is to compute the standard deviation of the flattened array.
3886
+ If this is a tuple of ints, a standard deviation is performed over
3887
+ multiple axes, instead of a single axis or all the axes as before.
3888
+ dtype : dtype, optional
3889
+ Type to use in computing the standard deviation. For arrays of
3890
+ integer type the default is float64, for arrays of float types it is
3891
+ the same as the array type.
3892
+ out : ndarray, optional
3893
+ Alternative output array in which to place the result. It must have
3894
+ the same shape as the expected output but the type (of the calculated
3895
+ values) will be cast if necessary.
3896
+ See :ref:`ufuncs-output-type` for more details.
3897
+ ddof : {int, float}, optional
3898
+ Means Delta Degrees of Freedom. The divisor used in calculations
3899
+ is ``N - ddof``, where ``N`` represents the number of elements.
3900
+ By default `ddof` is zero. See Notes for details about use of `ddof`.
3901
+ keepdims : bool, optional
3902
+ If this is set to True, the axes which are reduced are left
3903
+ in the result as dimensions with size one. With this option,
3904
+ the result will broadcast correctly against the input array.
3905
+
3906
+ If the default value is passed, then `keepdims` will not be
3907
+ passed through to the `std` method of sub-classes of
3908
+ `ndarray`, however any non-default value will be. If the
3909
+ sub-class' method does not implement `keepdims` any
3910
+ exceptions will be raised.
3911
+ where : array_like of bool, optional
3912
+ Elements to include in the standard deviation.
3913
+ See `~numpy.ufunc.reduce` for details.
3914
+
3915
+ .. versionadded:: 1.20.0
3916
+
3917
+ mean : array_like, optional
3918
+ Provide the mean to prevent its recalculation. The mean should have
3919
+ a shape as if it was calculated with ``keepdims=True``.
3920
+ The axis for the calculation of the mean should be the same as used in
3921
+ the call to this std function.
3922
+
3923
+ .. versionadded:: 2.0.0
3924
+
3925
+ correction : {int, float}, optional
3926
+ Array API compatible name for the ``ddof`` parameter. Only one of them
3927
+ can be provided at the same time.
3928
+
3929
+ .. versionadded:: 2.0.0
3930
+
3931
+ Returns
3932
+ -------
3933
+ standard_deviation : ndarray, see dtype parameter above.
3934
+ If `out` is None, return a new array containing the standard deviation,
3935
+ otherwise return a reference to the output array.
3936
+
3937
+ See Also
3938
+ --------
3939
+ var, mean, nanmean, nanstd, nanvar
3940
+ :ref:`ufuncs-output-type`
3941
+
3942
+ Notes
3943
+ -----
3944
+ There are several common variants of the array standard deviation
3945
+ calculation. Assuming the input `a` is a one-dimensional NumPy array
3946
+ and ``mean`` is either provided as an argument or computed as
3947
+ ``a.mean()``, NumPy computes the standard deviation of an array as::
3948
+
3949
+ N = len(a)
3950
+ d2 = abs(a - mean)**2 # abs is for complex `a`
3951
+ var = d2.sum() / (N - ddof) # note use of `ddof`
3952
+ std = var**0.5
3953
+
3954
+ Different values of the argument `ddof` are useful in different
3955
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
3956
+
3957
+ .. math::
3958
+
3959
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
3960
+
3961
+ which is sometimes called the "population standard deviation" in the field
3962
+ of statistics because it applies the definition of standard deviation to
3963
+ `a` as if `a` were a complete population of possible observations.
3964
+
3965
+ Many other libraries define the standard deviation of an array
3966
+ differently, e.g.:
3967
+
3968
+ .. math::
3969
+
3970
+ \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
3971
+
3972
+ In statistics, the resulting quantity is sometimes called the "sample
3973
+ standard deviation" because if `a` is a random sample from a larger
3974
+ population, this calculation provides the square root of an unbiased
3975
+ estimate of the variance of the population. The use of :math:`N-1` in the
3976
+ denominator is often called "Bessel's correction" because it corrects for
3977
+ bias (toward lower values) in the variance estimate introduced when the
3978
+ sample mean of `a` is used in place of the true mean of the population.
3979
+ The resulting estimate of the standard deviation is still biased, but less
3980
+ than it would have been without the correction. For this quantity, use
3981
+ ``ddof=1``.
3982
+
3983
+ Note that, for complex numbers, `std` takes the absolute
3984
+ value before squaring, so that the result is always real and nonnegative.
3985
+
3986
+ For floating-point input, the standard deviation is computed using the same
3987
+ precision the input has. Depending on the input data, this can cause
3988
+ the results to be inaccurate, especially for float32 (see example below).
3989
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
3990
+ alleviate this issue.
3991
+
3992
+ Examples
3993
+ --------
3994
+ >>> import numpy as np
3995
+ >>> a = np.array([[1, 2], [3, 4]])
3996
+ >>> np.std(a)
3997
+ 1.1180339887498949 # may vary
3998
+ >>> np.std(a, axis=0)
3999
+ array([1., 1.])
4000
+ >>> np.std(a, axis=1)
4001
+ array([0.5, 0.5])
4002
+
4003
+ In single precision, std() can be inaccurate:
4004
+
4005
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
4006
+ >>> a[0, :] = 1.0
4007
+ >>> a[1, :] = 0.1
4008
+ >>> np.std(a)
4009
+ np.float32(0.45000005)
4010
+
4011
+ Computing the standard deviation in float64 is more accurate:
4012
+
4013
+ >>> np.std(a, dtype=np.float64)
4014
+ 0.44999999925494177 # may vary
4015
+
4016
+ Specifying a where argument:
4017
+
4018
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4019
+ >>> np.std(a)
4020
+ 2.614064523559687 # may vary
4021
+ >>> np.std(a, where=[[True], [True], [False]])
4022
+ 2.0
4023
+
4024
+ Using the mean keyword to save computation time:
4025
+
4026
+ >>> import numpy as np
4027
+ >>> from timeit import timeit
4028
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4029
+ >>> mean = np.mean(a, axis=1, keepdims=True)
4030
+ >>>
4031
+ >>> g = globals()
4032
+ >>> n = 10000
4033
+ >>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
4034
+ >>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
4035
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
4036
+ #doctest: +SKIP
4037
+ Percentage execution time saved 30%
4038
+
4039
+ """
4040
+ kwargs = {}
4041
+ if keepdims is not np._NoValue:
4042
+ kwargs['keepdims'] = keepdims
4043
+ if where is not np._NoValue:
4044
+ kwargs['where'] = where
4045
+ if mean is not np._NoValue:
4046
+ kwargs['mean'] = mean
4047
+
4048
+ if correction != np._NoValue:
4049
+ if ddof != 0:
4050
+ raise ValueError(
4051
+ "ddof and correction can't be provided simultaneously."
4052
+ )
4053
+ else:
4054
+ ddof = correction
4055
+
4056
+ if type(a) is not mu.ndarray:
4057
+ try:
4058
+ std = a.std
4059
+ except AttributeError:
4060
+ pass
4061
+ else:
4062
+ return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
4063
+
4064
+ return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
4065
+ **kwargs)
4066
+
4067
+
4068
+ def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
4069
+ keepdims=None, *, where=None, mean=None, correction=None):
4070
+ return (a, where, out, mean)
4071
+
4072
+
4073
+ @array_function_dispatch(_var_dispatcher)
4074
+ def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
4075
+ where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
4076
+ r"""
4077
+ Compute the variance along the specified axis.
4078
+
4079
+ Returns the variance of the array elements, a measure of the spread of a
4080
+ distribution. The variance is computed for the flattened array by
4081
+ default, otherwise over the specified axis.
4082
+
4083
+ Parameters
4084
+ ----------
4085
+ a : array_like
4086
+ Array containing numbers whose variance is desired. If `a` is not an
4087
+ array, a conversion is attempted.
4088
+ axis : None or int or tuple of ints, optional
4089
+ Axis or axes along which the variance is computed. The default is to
4090
+ compute the variance of the flattened array.
4091
+ If this is a tuple of ints, a variance is performed over multiple axes,
4092
+ instead of a single axis or all the axes as before.
4093
+ dtype : data-type, optional
4094
+ Type to use in computing the variance. For arrays of integer type
4095
+ the default is `float64`; for arrays of float types it is the same as
4096
+ the array type.
4097
+ out : ndarray, optional
4098
+ Alternate output array in which to place the result. It must have
4099
+ the same shape as the expected output, but the type is cast if
4100
+ necessary.
4101
+ ddof : {int, float}, optional
4102
+ "Delta Degrees of Freedom": the divisor used in the calculation is
4103
+ ``N - ddof``, where ``N`` represents the number of elements. By
4104
+ default `ddof` is zero. See notes for details about use of `ddof`.
4105
+ keepdims : bool, optional
4106
+ If this is set to True, the axes which are reduced are left
4107
+ in the result as dimensions with size one. With this option,
4108
+ the result will broadcast correctly against the input array.
4109
+
4110
+ If the default value is passed, then `keepdims` will not be
4111
+ passed through to the `var` method of sub-classes of
4112
+ `ndarray`, however any non-default value will be. If the
4113
+ sub-class' method does not implement `keepdims` any
4114
+ exceptions will be raised.
4115
+ where : array_like of bool, optional
4116
+ Elements to include in the variance. See `~numpy.ufunc.reduce` for
4117
+ details.
4118
+
4119
+ .. versionadded:: 1.20.0
4120
+
4121
+ mean : array like, optional
4122
+ Provide the mean to prevent its recalculation. The mean should have
4123
+ a shape as if it was calculated with ``keepdims=True``.
4124
+ The axis for the calculation of the mean should be the same as used in
4125
+ the call to this var function.
4126
+
4127
+ .. versionadded:: 2.0.0
4128
+
4129
+ correction : {int, float}, optional
4130
+ Array API compatible name for the ``ddof`` parameter. Only one of them
4131
+ can be provided at the same time.
4132
+
4133
+ .. versionadded:: 2.0.0
4134
+
4135
+ Returns
4136
+ -------
4137
+ variance : ndarray, see dtype parameter above
4138
+ If ``out=None``, returns a new array containing the variance;
4139
+ otherwise, a reference to the output array is returned.
4140
+
4141
+ See Also
4142
+ --------
4143
+ std, mean, nanmean, nanstd, nanvar
4144
+ :ref:`ufuncs-output-type`
4145
+
4146
+ Notes
4147
+ -----
4148
+ There are several common variants of the array variance calculation.
4149
+ Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
4150
+ either provided as an argument or computed as ``a.mean()``, NumPy
4151
+ computes the variance of an array as::
4152
+
4153
+ N = len(a)
4154
+ d2 = abs(a - mean)**2 # abs is for complex `a`
4155
+ var = d2.sum() / (N - ddof) # note use of `ddof`
4156
+
4157
+ Different values of the argument `ddof` are useful in different
4158
+ contexts. NumPy's default ``ddof=0`` corresponds with the expression:
4159
+
4160
+ .. math::
4161
+
4162
+ \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
4163
+
4164
+ which is sometimes called the "population variance" in the field of
4165
+ statistics because it applies the definition of variance to `a` as if `a`
4166
+ were a complete population of possible observations.
4167
+
4168
+ Many other libraries define the variance of an array differently, e.g.:
4169
+
4170
+ .. math::
4171
+
4172
+ \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
4173
+
4174
+ In statistics, the resulting quantity is sometimes called the "sample
4175
+ variance" because if `a` is a random sample from a larger population,
4176
+ this calculation provides an unbiased estimate of the variance of the
4177
+ population. The use of :math:`N-1` in the denominator is often called
4178
+ "Bessel's correction" because it corrects for bias (toward lower values)
4179
+ in the variance estimate introduced when the sample mean of `a` is used
4180
+ in place of the true mean of the population. For this quantity, use
4181
+ ``ddof=1``.
4182
+
4183
+ Note that for complex numbers, the absolute value is taken before
4184
+ squaring, so that the result is always real and nonnegative.
4185
+
4186
+ For floating-point input, the variance is computed using the same
4187
+ precision the input has. Depending on the input data, this can cause
4188
+ the results to be inaccurate, especially for `float32` (see example
4189
+ below). Specifying a higher-accuracy accumulator using the ``dtype``
4190
+ keyword can alleviate this issue.
4191
+
4192
+ Examples
4193
+ --------
4194
+ >>> import numpy as np
4195
+ >>> a = np.array([[1, 2], [3, 4]])
4196
+ >>> np.var(a)
4197
+ 1.25
4198
+ >>> np.var(a, axis=0)
4199
+ array([1., 1.])
4200
+ >>> np.var(a, axis=1)
4201
+ array([0.25, 0.25])
4202
+
4203
+ In single precision, var() can be inaccurate:
4204
+
4205
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
4206
+ >>> a[0, :] = 1.0
4207
+ >>> a[1, :] = 0.1
4208
+ >>> np.var(a)
4209
+ np.float32(0.20250003)
4210
+
4211
+ Computing the variance in float64 is more accurate:
4212
+
4213
+ >>> np.var(a, dtype=np.float64)
4214
+ 0.20249999932944759 # may vary
4215
+ >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
4216
+ 0.2025
4217
+
4218
+ Specifying a where argument:
4219
+
4220
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4221
+ >>> np.var(a)
4222
+ 6.833333333333333 # may vary
4223
+ >>> np.var(a, where=[[True], [True], [False]])
4224
+ 4.0
4225
+
4226
+ Using the mean keyword to save computation time:
4227
+
4228
+ >>> import numpy as np
4229
+ >>> from timeit import timeit
4230
+ >>>
4231
+ >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4232
+ >>> mean = np.mean(a, axis=1, keepdims=True)
4233
+ >>>
4234
+ >>> g = globals()
4235
+ >>> n = 10000
4236
+ >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
4237
+ >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
4238
+ >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
4239
+ #doctest: +SKIP
4240
+ Percentage execution time saved 32%
4241
+
4242
+ """
4243
+ kwargs = {}
4244
+ if keepdims is not np._NoValue:
4245
+ kwargs['keepdims'] = keepdims
4246
+ if where is not np._NoValue:
4247
+ kwargs['where'] = where
4248
+ if mean is not np._NoValue:
4249
+ kwargs['mean'] = mean
4250
+
4251
+ if correction != np._NoValue:
4252
+ if ddof != 0:
4253
+ raise ValueError(
4254
+ "ddof and correction can't be provided simultaneously."
4255
+ )
4256
+ else:
4257
+ ddof = correction
4258
+
4259
+ if type(a) is not mu.ndarray:
4260
+ try:
4261
+ var = a.var
4262
+
4263
+ except AttributeError:
4264
+ pass
4265
+ else:
4266
+ return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
4267
+
4268
+ return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
4269
+ **kwargs)