numpy 2.5.2__cp315-cp315-win32.whl

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