numpy 2.3.5__cp313-cp313-macosx_14_0_arm64.whl

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

Potentially problematic release.


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

Files changed (897) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +102 -0
  3. numpy/__init__.cython-30.pxd +1241 -0
  4. numpy/__init__.pxd +1154 -0
  5. numpy/__init__.py +945 -0
  6. numpy/__init__.pyi +6147 -0
  7. numpy/_array_api_info.py +346 -0
  8. numpy/_array_api_info.pyi +207 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +186 -0
  12. numpy/_core/__init__.pyi +2 -0
  13. numpy/_core/_add_newdocs.py +6967 -0
  14. numpy/_core/_add_newdocs.pyi +3 -0
  15. numpy/_core/_add_newdocs_scalars.py +390 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +134 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +58 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +55 -0
  25. numpy/_core/_internal.py +958 -0
  26. numpy/_core/_internal.pyi +72 -0
  27. numpy/_core/_machar.py +355 -0
  28. numpy/_core/_machar.pyi +55 -0
  29. numpy/_core/_methods.py +255 -0
  30. numpy/_core/_methods.pyi +22 -0
  31. numpy/_core/_multiarray_tests.cpython-313-darwin.so +0 -0
  32. numpy/_core/_multiarray_umath.cpython-313-darwin.so +0 -0
  33. numpy/_core/_operand_flag_tests.cpython-313-darwin.so +0 -0
  34. numpy/_core/_rational_tests.cpython-313-darwin.so +0 -0
  35. numpy/_core/_simd.cpython-313-darwin.so +0 -0
  36. numpy/_core/_simd.pyi +25 -0
  37. numpy/_core/_string_helpers.py +100 -0
  38. numpy/_core/_string_helpers.pyi +12 -0
  39. numpy/_core/_struct_ufunc_tests.cpython-313-darwin.so +0 -0
  40. numpy/_core/_type_aliases.py +119 -0
  41. numpy/_core/_type_aliases.pyi +97 -0
  42. numpy/_core/_ufunc_config.py +491 -0
  43. numpy/_core/_ufunc_config.pyi +78 -0
  44. numpy/_core/_umath_tests.cpython-313-darwin.so +0 -0
  45. numpy/_core/arrayprint.py +1775 -0
  46. numpy/_core/arrayprint.pyi +238 -0
  47. numpy/_core/cversions.py +13 -0
  48. numpy/_core/defchararray.py +1427 -0
  49. numpy/_core/defchararray.pyi +1135 -0
  50. numpy/_core/einsumfunc.py +1498 -0
  51. numpy/_core/einsumfunc.pyi +184 -0
  52. numpy/_core/fromnumeric.py +4269 -0
  53. numpy/_core/fromnumeric.pyi +1750 -0
  54. numpy/_core/function_base.py +545 -0
  55. numpy/_core/function_base.pyi +278 -0
  56. numpy/_core/getlimits.py +748 -0
  57. numpy/_core/getlimits.pyi +3 -0
  58. numpy/_core/include/numpy/__multiarray_api.c +376 -0
  59. numpy/_core/include/numpy/__multiarray_api.h +1628 -0
  60. numpy/_core/include/numpy/__ufunc_api.c +54 -0
  61. numpy/_core/include/numpy/__ufunc_api.h +341 -0
  62. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  63. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  64. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  65. numpy/_core/include/numpy/arrayobject.h +7 -0
  66. numpy/_core/include/numpy/arrayscalars.h +196 -0
  67. numpy/_core/include/numpy/dtype_api.h +480 -0
  68. numpy/_core/include/numpy/halffloat.h +70 -0
  69. numpy/_core/include/numpy/ndarrayobject.h +304 -0
  70. numpy/_core/include/numpy/ndarraytypes.h +1950 -0
  71. numpy/_core/include/numpy/npy_2_compat.h +249 -0
  72. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  73. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  74. numpy/_core/include/numpy/npy_common.h +977 -0
  75. numpy/_core/include/numpy/npy_cpu.h +124 -0
  76. numpy/_core/include/numpy/npy_endian.h +78 -0
  77. numpy/_core/include/numpy/npy_math.h +602 -0
  78. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  79. numpy/_core/include/numpy/npy_os.h +42 -0
  80. numpy/_core/include/numpy/numpyconfig.h +182 -0
  81. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  82. numpy/_core/include/numpy/random/bitgen.h +20 -0
  83. numpy/_core/include/numpy/random/distributions.h +209 -0
  84. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  85. numpy/_core/include/numpy/ufuncobject.h +343 -0
  86. numpy/_core/include/numpy/utils.h +37 -0
  87. numpy/_core/lib/libnpymath.a +0 -0
  88. numpy/_core/lib/npy-pkg-config/mlib.ini +12 -0
  89. numpy/_core/lib/npy-pkg-config/npymath.ini +20 -0
  90. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  91. numpy/_core/memmap.py +363 -0
  92. numpy/_core/memmap.pyi +3 -0
  93. numpy/_core/multiarray.py +1762 -0
  94. numpy/_core/multiarray.pyi +1285 -0
  95. numpy/_core/numeric.py +2760 -0
  96. numpy/_core/numeric.pyi +882 -0
  97. numpy/_core/numerictypes.py +633 -0
  98. numpy/_core/numerictypes.pyi +197 -0
  99. numpy/_core/overrides.py +183 -0
  100. numpy/_core/overrides.pyi +48 -0
  101. numpy/_core/printoptions.py +32 -0
  102. numpy/_core/printoptions.pyi +28 -0
  103. numpy/_core/records.py +1089 -0
  104. numpy/_core/records.pyi +333 -0
  105. numpy/_core/shape_base.py +998 -0
  106. numpy/_core/shape_base.pyi +175 -0
  107. numpy/_core/strings.py +1829 -0
  108. numpy/_core/strings.pyi +511 -0
  109. numpy/_core/tests/_locales.py +72 -0
  110. numpy/_core/tests/_natype.py +205 -0
  111. numpy/_core/tests/data/astype_copy.pkl +0 -0
  112. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  113. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  114. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  115. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  116. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  117. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  118. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  119. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  123. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  125. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  127. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  128. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  129. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  131. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  132. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  133. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  135. numpy/_core/tests/examples/cython/checks.pyx +373 -0
  136. numpy/_core/tests/examples/cython/meson.build +43 -0
  137. numpy/_core/tests/examples/cython/setup.py +39 -0
  138. numpy/_core/tests/examples/limited_api/limited_api1.c +17 -0
  139. numpy/_core/tests/examples/limited_api/limited_api2.pyx +11 -0
  140. numpy/_core/tests/examples/limited_api/limited_api_latest.c +19 -0
  141. numpy/_core/tests/examples/limited_api/meson.build +59 -0
  142. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  143. numpy/_core/tests/test__exceptions.py +90 -0
  144. numpy/_core/tests/test_abc.py +54 -0
  145. numpy/_core/tests/test_api.py +654 -0
  146. numpy/_core/tests/test_argparse.py +92 -0
  147. numpy/_core/tests/test_array_api_info.py +113 -0
  148. numpy/_core/tests/test_array_coercion.py +911 -0
  149. numpy/_core/tests/test_array_interface.py +222 -0
  150. numpy/_core/tests/test_arraymethod.py +84 -0
  151. numpy/_core/tests/test_arrayobject.py +75 -0
  152. numpy/_core/tests/test_arrayprint.py +1328 -0
  153. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  154. numpy/_core/tests/test_casting_unittests.py +817 -0
  155. numpy/_core/tests/test_conversion_utils.py +206 -0
  156. numpy/_core/tests/test_cpu_dispatcher.py +49 -0
  157. numpy/_core/tests/test_cpu_features.py +432 -0
  158. numpy/_core/tests/test_custom_dtypes.py +315 -0
  159. numpy/_core/tests/test_cython.py +351 -0
  160. numpy/_core/tests/test_datetime.py +2734 -0
  161. numpy/_core/tests/test_defchararray.py +825 -0
  162. numpy/_core/tests/test_deprecations.py +454 -0
  163. numpy/_core/tests/test_dlpack.py +190 -0
  164. numpy/_core/tests/test_dtype.py +1995 -0
  165. numpy/_core/tests/test_einsum.py +1317 -0
  166. numpy/_core/tests/test_errstate.py +131 -0
  167. numpy/_core/tests/test_extint128.py +217 -0
  168. numpy/_core/tests/test_function_base.py +503 -0
  169. numpy/_core/tests/test_getlimits.py +205 -0
  170. numpy/_core/tests/test_half.py +568 -0
  171. numpy/_core/tests/test_hashtable.py +35 -0
  172. numpy/_core/tests/test_indexerrors.py +125 -0
  173. numpy/_core/tests/test_indexing.py +1455 -0
  174. numpy/_core/tests/test_item_selection.py +167 -0
  175. numpy/_core/tests/test_limited_api.py +102 -0
  176. numpy/_core/tests/test_longdouble.py +369 -0
  177. numpy/_core/tests/test_machar.py +30 -0
  178. numpy/_core/tests/test_mem_overlap.py +930 -0
  179. numpy/_core/tests/test_mem_policy.py +452 -0
  180. numpy/_core/tests/test_memmap.py +246 -0
  181. numpy/_core/tests/test_multiarray.py +10577 -0
  182. numpy/_core/tests/test_multithreading.py +292 -0
  183. numpy/_core/tests/test_nditer.py +3498 -0
  184. numpy/_core/tests/test_nep50_promotions.py +287 -0
  185. numpy/_core/tests/test_numeric.py +4247 -0
  186. numpy/_core/tests/test_numerictypes.py +651 -0
  187. numpy/_core/tests/test_overrides.py +791 -0
  188. numpy/_core/tests/test_print.py +200 -0
  189. numpy/_core/tests/test_protocols.py +46 -0
  190. numpy/_core/tests/test_records.py +544 -0
  191. numpy/_core/tests/test_regression.py +2670 -0
  192. numpy/_core/tests/test_scalar_ctors.py +207 -0
  193. numpy/_core/tests/test_scalar_methods.py +246 -0
  194. numpy/_core/tests/test_scalarbuffer.py +153 -0
  195. numpy/_core/tests/test_scalarinherit.py +105 -0
  196. numpy/_core/tests/test_scalarmath.py +1176 -0
  197. numpy/_core/tests/test_scalarprint.py +403 -0
  198. numpy/_core/tests/test_shape_base.py +891 -0
  199. numpy/_core/tests/test_simd.py +1341 -0
  200. numpy/_core/tests/test_simd_module.py +103 -0
  201. numpy/_core/tests/test_stringdtype.py +1814 -0
  202. numpy/_core/tests/test_strings.py +1499 -0
  203. numpy/_core/tests/test_ufunc.py +3313 -0
  204. numpy/_core/tests/test_umath.py +4928 -0
  205. numpy/_core/tests/test_umath_accuracy.py +124 -0
  206. numpy/_core/tests/test_umath_complex.py +626 -0
  207. numpy/_core/tests/test_unicode.py +368 -0
  208. numpy/_core/umath.py +60 -0
  209. numpy/_core/umath.pyi +197 -0
  210. numpy/_distributor_init.py +15 -0
  211. numpy/_distributor_init.pyi +1 -0
  212. numpy/_expired_attrs_2_0.py +79 -0
  213. numpy/_expired_attrs_2_0.pyi +62 -0
  214. numpy/_globals.py +96 -0
  215. numpy/_globals.pyi +17 -0
  216. numpy/_pyinstaller/__init__.py +0 -0
  217. numpy/_pyinstaller/__init__.pyi +0 -0
  218. numpy/_pyinstaller/hook-numpy.py +36 -0
  219. numpy/_pyinstaller/hook-numpy.pyi +13 -0
  220. numpy/_pyinstaller/tests/__init__.py +16 -0
  221. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  222. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  223. numpy/_pytesttester.py +201 -0
  224. numpy/_pytesttester.pyi +18 -0
  225. numpy/_typing/__init__.py +148 -0
  226. numpy/_typing/_add_docstring.py +153 -0
  227. numpy/_typing/_array_like.py +106 -0
  228. numpy/_typing/_char_codes.py +213 -0
  229. numpy/_typing/_dtype_like.py +114 -0
  230. numpy/_typing/_extended_precision.py +15 -0
  231. numpy/_typing/_nbit.py +19 -0
  232. numpy/_typing/_nbit_base.py +94 -0
  233. numpy/_typing/_nbit_base.pyi +40 -0
  234. numpy/_typing/_nested_sequence.py +79 -0
  235. numpy/_typing/_scalars.py +20 -0
  236. numpy/_typing/_shape.py +8 -0
  237. numpy/_typing/_ufunc.py +7 -0
  238. numpy/_typing/_ufunc.pyi +941 -0
  239. numpy/_utils/__init__.py +95 -0
  240. numpy/_utils/__init__.pyi +30 -0
  241. numpy/_utils/_convertions.py +18 -0
  242. numpy/_utils/_convertions.pyi +4 -0
  243. numpy/_utils/_inspect.py +192 -0
  244. numpy/_utils/_inspect.pyi +71 -0
  245. numpy/_utils/_pep440.py +486 -0
  246. numpy/_utils/_pep440.pyi +121 -0
  247. numpy/char/__init__.py +2 -0
  248. numpy/char/__init__.pyi +111 -0
  249. numpy/conftest.py +258 -0
  250. numpy/core/__init__.py +33 -0
  251. numpy/core/__init__.pyi +0 -0
  252. numpy/core/_dtype.py +10 -0
  253. numpy/core/_dtype.pyi +0 -0
  254. numpy/core/_dtype_ctypes.py +10 -0
  255. numpy/core/_dtype_ctypes.pyi +0 -0
  256. numpy/core/_internal.py +27 -0
  257. numpy/core/_multiarray_umath.py +57 -0
  258. numpy/core/_utils.py +21 -0
  259. numpy/core/arrayprint.py +10 -0
  260. numpy/core/defchararray.py +10 -0
  261. numpy/core/einsumfunc.py +10 -0
  262. numpy/core/fromnumeric.py +10 -0
  263. numpy/core/function_base.py +10 -0
  264. numpy/core/getlimits.py +10 -0
  265. numpy/core/multiarray.py +25 -0
  266. numpy/core/numeric.py +12 -0
  267. numpy/core/numerictypes.py +10 -0
  268. numpy/core/overrides.py +10 -0
  269. numpy/core/overrides.pyi +7 -0
  270. numpy/core/records.py +10 -0
  271. numpy/core/shape_base.py +10 -0
  272. numpy/core/umath.py +10 -0
  273. numpy/ctypeslib/__init__.py +13 -0
  274. numpy/ctypeslib/__init__.pyi +33 -0
  275. numpy/ctypeslib/_ctypeslib.py +603 -0
  276. numpy/ctypeslib/_ctypeslib.pyi +245 -0
  277. numpy/doc/ufuncs.py +138 -0
  278. numpy/dtypes.py +41 -0
  279. numpy/dtypes.pyi +631 -0
  280. numpy/exceptions.py +247 -0
  281. numpy/exceptions.pyi +27 -0
  282. numpy/f2py/__init__.py +86 -0
  283. numpy/f2py/__init__.pyi +6 -0
  284. numpy/f2py/__main__.py +5 -0
  285. numpy/f2py/__version__.py +1 -0
  286. numpy/f2py/__version__.pyi +1 -0
  287. numpy/f2py/_backends/__init__.py +9 -0
  288. numpy/f2py/_backends/__init__.pyi +5 -0
  289. numpy/f2py/_backends/_backend.py +44 -0
  290. numpy/f2py/_backends/_backend.pyi +46 -0
  291. numpy/f2py/_backends/_distutils.py +76 -0
  292. numpy/f2py/_backends/_distutils.pyi +13 -0
  293. numpy/f2py/_backends/_meson.py +231 -0
  294. numpy/f2py/_backends/_meson.pyi +63 -0
  295. numpy/f2py/_backends/meson.build.template +55 -0
  296. numpy/f2py/_isocbind.py +62 -0
  297. numpy/f2py/_isocbind.pyi +13 -0
  298. numpy/f2py/_src_pyf.py +247 -0
  299. numpy/f2py/_src_pyf.pyi +29 -0
  300. numpy/f2py/auxfuncs.py +1004 -0
  301. numpy/f2py/auxfuncs.pyi +264 -0
  302. numpy/f2py/capi_maps.py +811 -0
  303. numpy/f2py/capi_maps.pyi +33 -0
  304. numpy/f2py/cb_rules.py +665 -0
  305. numpy/f2py/cb_rules.pyi +17 -0
  306. numpy/f2py/cfuncs.py +1563 -0
  307. numpy/f2py/cfuncs.pyi +31 -0
  308. numpy/f2py/common_rules.py +143 -0
  309. numpy/f2py/common_rules.pyi +9 -0
  310. numpy/f2py/crackfortran.py +3725 -0
  311. numpy/f2py/crackfortran.pyi +258 -0
  312. numpy/f2py/diagnose.py +149 -0
  313. numpy/f2py/diagnose.pyi +1 -0
  314. numpy/f2py/f2py2e.py +786 -0
  315. numpy/f2py/f2py2e.pyi +76 -0
  316. numpy/f2py/f90mod_rules.py +269 -0
  317. numpy/f2py/f90mod_rules.pyi +16 -0
  318. numpy/f2py/func2subr.py +329 -0
  319. numpy/f2py/func2subr.pyi +7 -0
  320. numpy/f2py/rules.py +1629 -0
  321. numpy/f2py/rules.pyi +43 -0
  322. numpy/f2py/setup.cfg +3 -0
  323. numpy/f2py/src/fortranobject.c +1436 -0
  324. numpy/f2py/src/fortranobject.h +173 -0
  325. numpy/f2py/symbolic.py +1516 -0
  326. numpy/f2py/symbolic.pyi +221 -0
  327. numpy/f2py/tests/__init__.py +16 -0
  328. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  329. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  330. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +235 -0
  331. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  332. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  333. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  334. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  335. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  336. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  337. numpy/f2py/tests/src/callback/foo.f +62 -0
  338. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  339. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  340. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  341. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  342. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  343. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  344. numpy/f2py/tests/src/cli/hi77.f +3 -0
  345. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  346. numpy/f2py/tests/src/common/block.f +11 -0
  347. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  348. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  349. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  350. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  351. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  352. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  353. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  354. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  355. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  356. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  357. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  358. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  359. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  360. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  361. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  362. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  363. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  365. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  366. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  367. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  368. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  369. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  370. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  371. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  372. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  373. numpy/f2py/tests/src/mixed/foo.f +5 -0
  374. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  375. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  376. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  377. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  378. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  379. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  380. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  381. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  382. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  383. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  384. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  385. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  386. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  387. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  388. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  389. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  390. numpy/f2py/tests/src/regression/AB.inc +1 -0
  391. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  392. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  393. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  394. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  395. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  396. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  397. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  398. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  399. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  400. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  401. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  402. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  403. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  404. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  405. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  406. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  407. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  408. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  409. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  410. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  411. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  412. numpy/f2py/tests/src/routines/subrout.f +4 -0
  413. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  414. numpy/f2py/tests/src/size/foo.f90 +44 -0
  415. numpy/f2py/tests/src/string/char.f90 +29 -0
  416. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  417. numpy/f2py/tests/src/string/gh24008.f +8 -0
  418. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  419. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  420. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  421. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  422. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  423. numpy/f2py/tests/src/string/string.f +12 -0
  424. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  425. numpy/f2py/tests/test_abstract_interface.py +26 -0
  426. numpy/f2py/tests/test_array_from_pyobj.py +678 -0
  427. numpy/f2py/tests/test_assumed_shape.py +50 -0
  428. numpy/f2py/tests/test_block_docstring.py +20 -0
  429. numpy/f2py/tests/test_callback.py +263 -0
  430. numpy/f2py/tests/test_character.py +641 -0
  431. numpy/f2py/tests/test_common.py +23 -0
  432. numpy/f2py/tests/test_crackfortran.py +421 -0
  433. numpy/f2py/tests/test_data.py +71 -0
  434. numpy/f2py/tests/test_docs.py +64 -0
  435. numpy/f2py/tests/test_f2cmap.py +17 -0
  436. numpy/f2py/tests/test_f2py2e.py +964 -0
  437. numpy/f2py/tests/test_isoc.py +56 -0
  438. numpy/f2py/tests/test_kind.py +53 -0
  439. numpy/f2py/tests/test_mixed.py +35 -0
  440. numpy/f2py/tests/test_modules.py +83 -0
  441. numpy/f2py/tests/test_parameter.py +129 -0
  442. numpy/f2py/tests/test_pyf_src.py +43 -0
  443. numpy/f2py/tests/test_quoted_character.py +18 -0
  444. numpy/f2py/tests/test_regression.py +187 -0
  445. numpy/f2py/tests/test_return_character.py +48 -0
  446. numpy/f2py/tests/test_return_complex.py +67 -0
  447. numpy/f2py/tests/test_return_integer.py +55 -0
  448. numpy/f2py/tests/test_return_logical.py +65 -0
  449. numpy/f2py/tests/test_return_real.py +109 -0
  450. numpy/f2py/tests/test_routines.py +29 -0
  451. numpy/f2py/tests/test_semicolon_split.py +75 -0
  452. numpy/f2py/tests/test_size.py +45 -0
  453. numpy/f2py/tests/test_string.py +100 -0
  454. numpy/f2py/tests/test_symbolic.py +495 -0
  455. numpy/f2py/tests/test_value_attrspec.py +15 -0
  456. numpy/f2py/tests/util.py +442 -0
  457. numpy/f2py/use_rules.py +99 -0
  458. numpy/f2py/use_rules.pyi +9 -0
  459. numpy/fft/__init__.py +215 -0
  460. numpy/fft/__init__.pyi +43 -0
  461. numpy/fft/_helper.py +235 -0
  462. numpy/fft/_helper.pyi +45 -0
  463. numpy/fft/_pocketfft.py +1693 -0
  464. numpy/fft/_pocketfft.pyi +138 -0
  465. numpy/fft/_pocketfft_umath.cpython-313-darwin.so +0 -0
  466. numpy/fft/helper.py +17 -0
  467. numpy/fft/helper.pyi +22 -0
  468. numpy/fft/tests/__init__.py +0 -0
  469. numpy/fft/tests/test_helper.py +167 -0
  470. numpy/fft/tests/test_pocketfft.py +589 -0
  471. numpy/lib/__init__.py +97 -0
  472. numpy/lib/__init__.pyi +44 -0
  473. numpy/lib/_array_utils_impl.py +62 -0
  474. numpy/lib/_array_utils_impl.pyi +26 -0
  475. numpy/lib/_arraypad_impl.py +890 -0
  476. numpy/lib/_arraypad_impl.pyi +89 -0
  477. numpy/lib/_arraysetops_impl.py +1260 -0
  478. numpy/lib/_arraysetops_impl.pyi +468 -0
  479. numpy/lib/_arrayterator_impl.py +224 -0
  480. numpy/lib/_arrayterator_impl.pyi +46 -0
  481. numpy/lib/_datasource.py +700 -0
  482. numpy/lib/_datasource.pyi +31 -0
  483. numpy/lib/_format_impl.py +1036 -0
  484. numpy/lib/_format_impl.pyi +26 -0
  485. numpy/lib/_function_base_impl.py +5844 -0
  486. numpy/lib/_function_base_impl.pyi +1164 -0
  487. numpy/lib/_histograms_impl.py +1085 -0
  488. numpy/lib/_histograms_impl.pyi +50 -0
  489. numpy/lib/_index_tricks_impl.py +1067 -0
  490. numpy/lib/_index_tricks_impl.pyi +208 -0
  491. numpy/lib/_iotools.py +900 -0
  492. numpy/lib/_iotools.pyi +114 -0
  493. numpy/lib/_nanfunctions_impl.py +2024 -0
  494. numpy/lib/_nanfunctions_impl.pyi +52 -0
  495. numpy/lib/_npyio_impl.py +2596 -0
  496. numpy/lib/_npyio_impl.pyi +301 -0
  497. numpy/lib/_polynomial_impl.py +1465 -0
  498. numpy/lib/_polynomial_impl.pyi +318 -0
  499. numpy/lib/_scimath_impl.py +642 -0
  500. numpy/lib/_scimath_impl.pyi +93 -0
  501. numpy/lib/_shape_base_impl.py +1301 -0
  502. numpy/lib/_shape_base_impl.pyi +235 -0
  503. numpy/lib/_stride_tricks_impl.py +549 -0
  504. numpy/lib/_stride_tricks_impl.pyi +74 -0
  505. numpy/lib/_twodim_base_impl.py +1201 -0
  506. numpy/lib/_twodim_base_impl.pyi +438 -0
  507. numpy/lib/_type_check_impl.py +699 -0
  508. numpy/lib/_type_check_impl.pyi +350 -0
  509. numpy/lib/_ufunclike_impl.py +207 -0
  510. numpy/lib/_ufunclike_impl.pyi +67 -0
  511. numpy/lib/_user_array_impl.py +299 -0
  512. numpy/lib/_user_array_impl.pyi +225 -0
  513. numpy/lib/_utils_impl.py +784 -0
  514. numpy/lib/_utils_impl.pyi +10 -0
  515. numpy/lib/_version.py +154 -0
  516. numpy/lib/_version.pyi +17 -0
  517. numpy/lib/array_utils.py +7 -0
  518. numpy/lib/array_utils.pyi +12 -0
  519. numpy/lib/format.py +24 -0
  520. numpy/lib/format.pyi +66 -0
  521. numpy/lib/introspect.py +95 -0
  522. numpy/lib/introspect.pyi +3 -0
  523. numpy/lib/mixins.py +180 -0
  524. numpy/lib/mixins.pyi +77 -0
  525. numpy/lib/npyio.py +1 -0
  526. numpy/lib/npyio.pyi +9 -0
  527. numpy/lib/recfunctions.py +1681 -0
  528. numpy/lib/recfunctions.pyi +435 -0
  529. numpy/lib/scimath.py +13 -0
  530. numpy/lib/scimath.pyi +30 -0
  531. numpy/lib/stride_tricks.py +1 -0
  532. numpy/lib/stride_tricks.pyi +6 -0
  533. numpy/lib/tests/__init__.py +0 -0
  534. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  535. numpy/lib/tests/data/py2-objarr.npy +0 -0
  536. numpy/lib/tests/data/py2-objarr.npz +0 -0
  537. numpy/lib/tests/data/py3-objarr.npy +0 -0
  538. numpy/lib/tests/data/py3-objarr.npz +0 -0
  539. numpy/lib/tests/data/python3.npy +0 -0
  540. numpy/lib/tests/data/win64python2.npy +0 -0
  541. numpy/lib/tests/test__datasource.py +352 -0
  542. numpy/lib/tests/test__iotools.py +360 -0
  543. numpy/lib/tests/test__version.py +64 -0
  544. numpy/lib/tests/test_array_utils.py +32 -0
  545. numpy/lib/tests/test_arraypad.py +1415 -0
  546. numpy/lib/tests/test_arraysetops.py +1074 -0
  547. numpy/lib/tests/test_arrayterator.py +46 -0
  548. numpy/lib/tests/test_format.py +1054 -0
  549. numpy/lib/tests/test_function_base.py +4573 -0
  550. numpy/lib/tests/test_histograms.py +855 -0
  551. numpy/lib/tests/test_index_tricks.py +573 -0
  552. numpy/lib/tests/test_io.py +2848 -0
  553. numpy/lib/tests/test_loadtxt.py +1101 -0
  554. numpy/lib/tests/test_mixins.py +215 -0
  555. numpy/lib/tests/test_nanfunctions.py +1438 -0
  556. numpy/lib/tests/test_packbits.py +376 -0
  557. numpy/lib/tests/test_polynomial.py +320 -0
  558. numpy/lib/tests/test_recfunctions.py +1052 -0
  559. numpy/lib/tests/test_regression.py +231 -0
  560. numpy/lib/tests/test_shape_base.py +813 -0
  561. numpy/lib/tests/test_stride_tricks.py +656 -0
  562. numpy/lib/tests/test_twodim_base.py +559 -0
  563. numpy/lib/tests/test_type_check.py +473 -0
  564. numpy/lib/tests/test_ufunclike.py +97 -0
  565. numpy/lib/tests/test_utils.py +80 -0
  566. numpy/lib/user_array.py +1 -0
  567. numpy/lib/user_array.pyi +1 -0
  568. numpy/linalg/__init__.py +98 -0
  569. numpy/linalg/__init__.pyi +73 -0
  570. numpy/linalg/_linalg.py +3682 -0
  571. numpy/linalg/_linalg.pyi +475 -0
  572. numpy/linalg/_umath_linalg.cpython-313-darwin.so +0 -0
  573. numpy/linalg/_umath_linalg.pyi +61 -0
  574. numpy/linalg/lapack_lite.cpython-313-darwin.so +0 -0
  575. numpy/linalg/lapack_lite.pyi +141 -0
  576. numpy/linalg/linalg.py +17 -0
  577. numpy/linalg/linalg.pyi +69 -0
  578. numpy/linalg/tests/__init__.py +0 -0
  579. numpy/linalg/tests/test_deprecations.py +20 -0
  580. numpy/linalg/tests/test_linalg.py +2443 -0
  581. numpy/linalg/tests/test_regression.py +181 -0
  582. numpy/ma/API_CHANGES.txt +135 -0
  583. numpy/ma/LICENSE +24 -0
  584. numpy/ma/README.rst +236 -0
  585. numpy/ma/__init__.py +53 -0
  586. numpy/ma/__init__.pyi +458 -0
  587. numpy/ma/core.py +8933 -0
  588. numpy/ma/core.pyi +1462 -0
  589. numpy/ma/extras.py +2344 -0
  590. numpy/ma/extras.pyi +138 -0
  591. numpy/ma/mrecords.py +773 -0
  592. numpy/ma/mrecords.pyi +96 -0
  593. numpy/ma/tests/__init__.py +0 -0
  594. numpy/ma/tests/test_arrayobject.py +40 -0
  595. numpy/ma/tests/test_core.py +5886 -0
  596. numpy/ma/tests/test_deprecations.py +87 -0
  597. numpy/ma/tests/test_extras.py +1998 -0
  598. numpy/ma/tests/test_mrecords.py +497 -0
  599. numpy/ma/tests/test_old_ma.py +942 -0
  600. numpy/ma/tests/test_regression.py +100 -0
  601. numpy/ma/tests/test_subclassing.py +469 -0
  602. numpy/ma/testutils.py +294 -0
  603. numpy/matlib.py +380 -0
  604. numpy/matlib.pyi +582 -0
  605. numpy/matrixlib/__init__.py +12 -0
  606. numpy/matrixlib/__init__.pyi +5 -0
  607. numpy/matrixlib/defmatrix.py +1119 -0
  608. numpy/matrixlib/defmatrix.pyi +17 -0
  609. numpy/matrixlib/tests/__init__.py +0 -0
  610. numpy/matrixlib/tests/test_defmatrix.py +455 -0
  611. numpy/matrixlib/tests/test_interaction.py +360 -0
  612. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  613. numpy/matrixlib/tests/test_matrix_linalg.py +105 -0
  614. numpy/matrixlib/tests/test_multiarray.py +17 -0
  615. numpy/matrixlib/tests/test_numeric.py +18 -0
  616. numpy/matrixlib/tests/test_regression.py +31 -0
  617. numpy/polynomial/__init__.py +187 -0
  618. numpy/polynomial/__init__.pyi +25 -0
  619. numpy/polynomial/_polybase.py +1191 -0
  620. numpy/polynomial/_polybase.pyi +285 -0
  621. numpy/polynomial/_polytypes.pyi +892 -0
  622. numpy/polynomial/chebyshev.py +2003 -0
  623. numpy/polynomial/chebyshev.pyi +181 -0
  624. numpy/polynomial/hermite.py +1740 -0
  625. numpy/polynomial/hermite.pyi +107 -0
  626. numpy/polynomial/hermite_e.py +1642 -0
  627. numpy/polynomial/hermite_e.pyi +107 -0
  628. numpy/polynomial/laguerre.py +1675 -0
  629. numpy/polynomial/laguerre.pyi +100 -0
  630. numpy/polynomial/legendre.py +1605 -0
  631. numpy/polynomial/legendre.pyi +100 -0
  632. numpy/polynomial/polynomial.py +1616 -0
  633. numpy/polynomial/polynomial.pyi +89 -0
  634. numpy/polynomial/polyutils.py +759 -0
  635. numpy/polynomial/polyutils.pyi +423 -0
  636. numpy/polynomial/tests/__init__.py +0 -0
  637. numpy/polynomial/tests/test_chebyshev.py +623 -0
  638. numpy/polynomial/tests/test_classes.py +618 -0
  639. numpy/polynomial/tests/test_hermite.py +558 -0
  640. numpy/polynomial/tests/test_hermite_e.py +559 -0
  641. numpy/polynomial/tests/test_laguerre.py +540 -0
  642. numpy/polynomial/tests/test_legendre.py +571 -0
  643. numpy/polynomial/tests/test_polynomial.py +669 -0
  644. numpy/polynomial/tests/test_polyutils.py +128 -0
  645. numpy/polynomial/tests/test_printing.py +555 -0
  646. numpy/polynomial/tests/test_symbol.py +217 -0
  647. numpy/py.typed +0 -0
  648. numpy/random/LICENSE.md +71 -0
  649. numpy/random/__init__.pxd +14 -0
  650. numpy/random/__init__.py +213 -0
  651. numpy/random/__init__.pyi +124 -0
  652. numpy/random/_bounded_integers.cpython-313-darwin.so +0 -0
  653. numpy/random/_bounded_integers.pxd +29 -0
  654. numpy/random/_bounded_integers.pyi +1 -0
  655. numpy/random/_common.cpython-313-darwin.so +0 -0
  656. numpy/random/_common.pxd +107 -0
  657. numpy/random/_common.pyi +16 -0
  658. numpy/random/_examples/cffi/extending.py +44 -0
  659. numpy/random/_examples/cffi/parse.py +53 -0
  660. numpy/random/_examples/cython/extending.pyx +77 -0
  661. numpy/random/_examples/cython/extending_distributions.pyx +118 -0
  662. numpy/random/_examples/cython/meson.build +53 -0
  663. numpy/random/_examples/numba/extending.py +86 -0
  664. numpy/random/_examples/numba/extending_distributions.py +67 -0
  665. numpy/random/_generator.cpython-313-darwin.so +0 -0
  666. numpy/random/_generator.pyi +861 -0
  667. numpy/random/_mt19937.cpython-313-darwin.so +0 -0
  668. numpy/random/_mt19937.pyi +25 -0
  669. numpy/random/_pcg64.cpython-313-darwin.so +0 -0
  670. numpy/random/_pcg64.pyi +44 -0
  671. numpy/random/_philox.cpython-313-darwin.so +0 -0
  672. numpy/random/_philox.pyi +39 -0
  673. numpy/random/_pickle.py +88 -0
  674. numpy/random/_pickle.pyi +43 -0
  675. numpy/random/_sfc64.cpython-313-darwin.so +0 -0
  676. numpy/random/_sfc64.pyi +28 -0
  677. numpy/random/bit_generator.cpython-313-darwin.so +0 -0
  678. numpy/random/bit_generator.pxd +35 -0
  679. numpy/random/bit_generator.pyi +124 -0
  680. numpy/random/c_distributions.pxd +119 -0
  681. numpy/random/lib/libnpyrandom.a +0 -0
  682. numpy/random/mtrand.cpython-313-darwin.so +0 -0
  683. numpy/random/mtrand.pyi +703 -0
  684. numpy/random/tests/__init__.py +0 -0
  685. numpy/random/tests/data/__init__.py +0 -0
  686. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  687. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  688. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  689. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  690. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  691. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  692. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  693. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  694. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  695. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  696. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  697. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  698. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  699. numpy/random/tests/test_direct.py +592 -0
  700. numpy/random/tests/test_extending.py +127 -0
  701. numpy/random/tests/test_generator_mt19937.py +2809 -0
  702. numpy/random/tests/test_generator_mt19937_regressions.py +207 -0
  703. numpy/random/tests/test_random.py +1757 -0
  704. numpy/random/tests/test_randomstate.py +2130 -0
  705. numpy/random/tests/test_randomstate_regression.py +217 -0
  706. numpy/random/tests/test_regression.py +152 -0
  707. numpy/random/tests/test_seed_sequence.py +79 -0
  708. numpy/random/tests/test_smoke.py +819 -0
  709. numpy/rec/__init__.py +2 -0
  710. numpy/rec/__init__.pyi +23 -0
  711. numpy/strings/__init__.py +2 -0
  712. numpy/strings/__init__.pyi +97 -0
  713. numpy/testing/__init__.py +22 -0
  714. numpy/testing/__init__.pyi +102 -0
  715. numpy/testing/_private/__init__.py +0 -0
  716. numpy/testing/_private/__init__.pyi +0 -0
  717. numpy/testing/_private/extbuild.py +250 -0
  718. numpy/testing/_private/extbuild.pyi +25 -0
  719. numpy/testing/_private/utils.py +2752 -0
  720. numpy/testing/_private/utils.pyi +499 -0
  721. numpy/testing/overrides.py +84 -0
  722. numpy/testing/overrides.pyi +11 -0
  723. numpy/testing/print_coercion_tables.py +207 -0
  724. numpy/testing/print_coercion_tables.pyi +27 -0
  725. numpy/testing/tests/__init__.py +0 -0
  726. numpy/testing/tests/test_utils.py +1917 -0
  727. numpy/tests/__init__.py +0 -0
  728. numpy/tests/test__all__.py +10 -0
  729. numpy/tests/test_configtool.py +48 -0
  730. numpy/tests/test_ctypeslib.py +377 -0
  731. numpy/tests/test_lazyloading.py +38 -0
  732. numpy/tests/test_matlib.py +59 -0
  733. numpy/tests/test_numpy_config.py +46 -0
  734. numpy/tests/test_numpy_version.py +54 -0
  735. numpy/tests/test_public_api.py +806 -0
  736. numpy/tests/test_reloading.py +74 -0
  737. numpy/tests/test_scripts.py +49 -0
  738. numpy/tests/test_warnings.py +78 -0
  739. numpy/typing/__init__.py +201 -0
  740. numpy/typing/mypy_plugin.py +195 -0
  741. numpy/typing/tests/__init__.py +0 -0
  742. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  743. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  744. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  745. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  746. numpy/typing/tests/data/fail/arrayprint.pyi +16 -0
  747. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  748. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  749. numpy/typing/tests/data/fail/char.pyi +65 -0
  750. numpy/typing/tests/data/fail/chararray.pyi +62 -0
  751. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  752. numpy/typing/tests/data/fail/constants.pyi +3 -0
  753. numpy/typing/tests/data/fail/datasource.pyi +15 -0
  754. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  755. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  756. numpy/typing/tests/data/fail/flatiter.pyi +20 -0
  757. numpy/typing/tests/data/fail/fromnumeric.pyi +148 -0
  758. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  759. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  760. numpy/typing/tests/data/fail/lib_function_base.pyi +62 -0
  761. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  762. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  763. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  764. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  765. numpy/typing/tests/data/fail/ma.pyi +143 -0
  766. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  767. numpy/typing/tests/data/fail/modules.pyi +17 -0
  768. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  769. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  770. numpy/typing/tests/data/fail/ndarray_misc.pyi +36 -0
  771. numpy/typing/tests/data/fail/nditer.pyi +8 -0
  772. numpy/typing/tests/data/fail/nested_sequence.pyi +16 -0
  773. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  774. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  775. numpy/typing/tests/data/fail/random.pyi +62 -0
  776. numpy/typing/tests/data/fail/rec.pyi +17 -0
  777. numpy/typing/tests/data/fail/scalars.pyi +87 -0
  778. numpy/typing/tests/data/fail/shape.pyi +6 -0
  779. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  780. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  781. numpy/typing/tests/data/fail/strings.pyi +52 -0
  782. numpy/typing/tests/data/fail/testing.pyi +28 -0
  783. numpy/typing/tests/data/fail/twodim_base.pyi +32 -0
  784. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  785. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  786. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  787. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  788. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  789. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  790. numpy/typing/tests/data/mypy.ini +9 -0
  791. numpy/typing/tests/data/pass/arithmetic.py +612 -0
  792. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  793. numpy/typing/tests/data/pass/array_like.py +43 -0
  794. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  795. numpy/typing/tests/data/pass/arrayterator.py +27 -0
  796. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  797. numpy/typing/tests/data/pass/comparisons.py +315 -0
  798. numpy/typing/tests/data/pass/dtype.py +57 -0
  799. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  800. numpy/typing/tests/data/pass/flatiter.py +19 -0
  801. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  802. numpy/typing/tests/data/pass/index_tricks.py +60 -0
  803. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  804. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  805. numpy/typing/tests/data/pass/lib_version.py +18 -0
  806. numpy/typing/tests/data/pass/literal.py +51 -0
  807. numpy/typing/tests/data/pass/ma.py +174 -0
  808. numpy/typing/tests/data/pass/mod.py +149 -0
  809. numpy/typing/tests/data/pass/modules.py +45 -0
  810. numpy/typing/tests/data/pass/multiarray.py +76 -0
  811. numpy/typing/tests/data/pass/ndarray_conversion.py +87 -0
  812. numpy/typing/tests/data/pass/ndarray_misc.py +203 -0
  813. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  814. numpy/typing/tests/data/pass/nditer.py +4 -0
  815. numpy/typing/tests/data/pass/numeric.py +95 -0
  816. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  817. numpy/typing/tests/data/pass/random.py +1497 -0
  818. numpy/typing/tests/data/pass/recfunctions.py +161 -0
  819. numpy/typing/tests/data/pass/scalars.py +248 -0
  820. numpy/typing/tests/data/pass/shape.py +19 -0
  821. numpy/typing/tests/data/pass/simple.py +168 -0
  822. numpy/typing/tests/data/pass/simple_py3.py +6 -0
  823. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  824. numpy/typing/tests/data/pass/ufunclike.py +47 -0
  825. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  826. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  827. numpy/typing/tests/data/reveal/arithmetic.pyi +720 -0
  828. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  829. numpy/typing/tests/data/reveal/array_constructors.pyi +249 -0
  830. numpy/typing/tests/data/reveal/arraypad.pyi +22 -0
  831. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  832. numpy/typing/tests/data/reveal/arraysetops.pyi +74 -0
  833. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  834. numpy/typing/tests/data/reveal/bitwise_ops.pyi +167 -0
  835. numpy/typing/tests/data/reveal/char.pyi +224 -0
  836. numpy/typing/tests/data/reveal/chararray.pyi +137 -0
  837. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  838. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  839. numpy/typing/tests/data/reveal/ctypeslib.pyi +81 -0
  840. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  841. numpy/typing/tests/data/reveal/dtype.pyi +136 -0
  842. numpy/typing/tests/data/reveal/einsumfunc.pyi +39 -0
  843. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  844. numpy/typing/tests/data/reveal/fft.pyi +37 -0
  845. numpy/typing/tests/data/reveal/flatiter.pyi +47 -0
  846. numpy/typing/tests/data/reveal/fromnumeric.pyi +347 -0
  847. numpy/typing/tests/data/reveal/getlimits.pyi +51 -0
  848. numpy/typing/tests/data/reveal/histograms.pyi +25 -0
  849. numpy/typing/tests/data/reveal/index_tricks.pyi +70 -0
  850. numpy/typing/tests/data/reveal/lib_function_base.pyi +213 -0
  851. numpy/typing/tests/data/reveal/lib_polynomial.pyi +144 -0
  852. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  853. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  854. numpy/typing/tests/data/reveal/linalg.pyi +132 -0
  855. numpy/typing/tests/data/reveal/ma.pyi +369 -0
  856. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  857. numpy/typing/tests/data/reveal/memmap.pyi +19 -0
  858. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  859. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  860. numpy/typing/tests/data/reveal/multiarray.pyi +194 -0
  861. numpy/typing/tests/data/reveal/nbit_base_example.pyi +21 -0
  862. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +77 -0
  863. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +85 -0
  864. numpy/typing/tests/data/reveal/ndarray_misc.pyi +247 -0
  865. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +39 -0
  866. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  867. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  868. numpy/typing/tests/data/reveal/npyio.pyi +83 -0
  869. numpy/typing/tests/data/reveal/numeric.pyi +134 -0
  870. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  871. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +220 -0
  872. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +219 -0
  873. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  874. numpy/typing/tests/data/reveal/random.pyi +1546 -0
  875. numpy/typing/tests/data/reveal/rec.pyi +171 -0
  876. numpy/typing/tests/data/reveal/scalars.pyi +191 -0
  877. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  878. numpy/typing/tests/data/reveal/shape_base.pyi +52 -0
  879. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  880. numpy/typing/tests/data/reveal/strings.pyi +196 -0
  881. numpy/typing/tests/data/reveal/testing.pyi +198 -0
  882. numpy/typing/tests/data/reveal/twodim_base.pyi +145 -0
  883. numpy/typing/tests/data/reveal/type_check.pyi +67 -0
  884. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  885. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  886. numpy/typing/tests/data/reveal/ufuncs.pyi +123 -0
  887. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  888. numpy/typing/tests/test_isfile.py +32 -0
  889. numpy/typing/tests/test_runtime.py +102 -0
  890. numpy/typing/tests/test_typing.py +205 -0
  891. numpy/version.py +11 -0
  892. numpy/version.pyi +18 -0
  893. numpy-2.3.5.dist-info/LICENSE.txt +971 -0
  894. numpy-2.3.5.dist-info/METADATA +1093 -0
  895. numpy-2.3.5.dist-info/RECORD +897 -0
  896. numpy-2.3.5.dist-info/WHEEL +6 -0
  897. numpy-2.3.5.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,2596 @@
1
+ """
2
+ IO related functions.
3
+ """
4
+ import contextlib
5
+ import functools
6
+ import itertools
7
+ import operator
8
+ import os
9
+ import pickle
10
+ import re
11
+ import warnings
12
+ import weakref
13
+ from collections.abc import Mapping
14
+ from operator import itemgetter
15
+
16
+ import numpy as np
17
+ from numpy._core import overrides
18
+ from numpy._core._multiarray_umath import _load_from_filelike
19
+ from numpy._core.multiarray import packbits, unpackbits
20
+ from numpy._core.overrides import finalize_array_function_like, set_module
21
+ from numpy._utils import asbytes, asunicode
22
+
23
+ from . import format
24
+ from ._datasource import DataSource # noqa: F401
25
+ from ._format_impl import _MAX_HEADER_SIZE
26
+ from ._iotools import (
27
+ ConversionWarning,
28
+ ConverterError,
29
+ ConverterLockError,
30
+ LineSplitter,
31
+ NameValidator,
32
+ StringConverter,
33
+ _decode_line,
34
+ _is_string_like,
35
+ easy_dtype,
36
+ flatten_dtype,
37
+ has_nested_fields,
38
+ )
39
+
40
+ __all__ = [
41
+ 'savetxt', 'loadtxt', 'genfromtxt', 'load', 'save', 'savez',
42
+ 'savez_compressed', 'packbits', 'unpackbits', 'fromregex'
43
+ ]
44
+
45
+
46
+ array_function_dispatch = functools.partial(
47
+ overrides.array_function_dispatch, module='numpy')
48
+
49
+
50
+ class BagObj:
51
+ """
52
+ BagObj(obj)
53
+
54
+ Convert attribute look-ups to getitems on the object passed in.
55
+
56
+ Parameters
57
+ ----------
58
+ obj : class instance
59
+ Object on which attribute look-up is performed.
60
+
61
+ Examples
62
+ --------
63
+ >>> import numpy as np
64
+ >>> from numpy.lib._npyio_impl import BagObj as BO
65
+ >>> class BagDemo:
66
+ ... def __getitem__(self, key): # An instance of BagObj(BagDemo)
67
+ ... # will call this method when any
68
+ ... # attribute look-up is required
69
+ ... result = "Doesn't matter what you want, "
70
+ ... return result + "you're gonna get this"
71
+ ...
72
+ >>> demo_obj = BagDemo()
73
+ >>> bagobj = BO(demo_obj)
74
+ >>> bagobj.hello_there
75
+ "Doesn't matter what you want, you're gonna get this"
76
+ >>> bagobj.I_can_be_anything
77
+ "Doesn't matter what you want, you're gonna get this"
78
+
79
+ """
80
+
81
+ def __init__(self, obj):
82
+ # Use weakref to make NpzFile objects collectable by refcount
83
+ self._obj = weakref.proxy(obj)
84
+
85
+ def __getattribute__(self, key):
86
+ try:
87
+ return object.__getattribute__(self, '_obj')[key]
88
+ except KeyError:
89
+ raise AttributeError(key) from None
90
+
91
+ def __dir__(self):
92
+ """
93
+ Enables dir(bagobj) to list the files in an NpzFile.
94
+
95
+ This also enables tab-completion in an interpreter or IPython.
96
+ """
97
+ return list(object.__getattribute__(self, '_obj').keys())
98
+
99
+
100
+ def zipfile_factory(file, *args, **kwargs):
101
+ """
102
+ Create a ZipFile.
103
+
104
+ Allows for Zip64, and the `file` argument can accept file, str, or
105
+ pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
106
+ constructor.
107
+ """
108
+ if not hasattr(file, 'read'):
109
+ file = os.fspath(file)
110
+ import zipfile
111
+ kwargs['allowZip64'] = True
112
+ return zipfile.ZipFile(file, *args, **kwargs)
113
+
114
+
115
+ @set_module('numpy.lib.npyio')
116
+ class NpzFile(Mapping):
117
+ """
118
+ NpzFile(fid)
119
+
120
+ A dictionary-like object with lazy-loading of files in the zipped
121
+ archive provided on construction.
122
+
123
+ `NpzFile` is used to load files in the NumPy ``.npz`` data archive
124
+ format. It assumes that files in the archive have a ``.npy`` extension,
125
+ other files are ignored.
126
+
127
+ The arrays and file strings are lazily loaded on either
128
+ getitem access using ``obj['key']`` or attribute lookup using
129
+ ``obj.f.key``. A list of all files (without ``.npy`` extensions) can
130
+ be obtained with ``obj.files`` and the ZipFile object itself using
131
+ ``obj.zip``.
132
+
133
+ Attributes
134
+ ----------
135
+ files : list of str
136
+ List of all files in the archive with a ``.npy`` extension.
137
+ zip : ZipFile instance
138
+ The ZipFile object initialized with the zipped archive.
139
+ f : BagObj instance
140
+ An object on which attribute can be performed as an alternative
141
+ to getitem access on the `NpzFile` instance itself.
142
+ allow_pickle : bool, optional
143
+ Allow loading pickled data. Default: False
144
+ pickle_kwargs : dict, optional
145
+ Additional keyword arguments to pass on to pickle.load.
146
+ These are only useful when loading object arrays saved on
147
+ Python 2.
148
+ max_header_size : int, optional
149
+ Maximum allowed size of the header. Large headers may not be safe
150
+ to load securely and thus require explicitly passing a larger value.
151
+ See :py:func:`ast.literal_eval()` for details.
152
+ This option is ignored when `allow_pickle` is passed. In that case
153
+ the file is by definition trusted and the limit is unnecessary.
154
+
155
+ Parameters
156
+ ----------
157
+ fid : file, str, or pathlib.Path
158
+ The zipped archive to open. This is either a file-like object
159
+ or a string containing the path to the archive.
160
+ own_fid : bool, optional
161
+ Whether NpzFile should close the file handle.
162
+ Requires that `fid` is a file-like object.
163
+
164
+ Examples
165
+ --------
166
+ >>> import numpy as np
167
+ >>> from tempfile import TemporaryFile
168
+ >>> outfile = TemporaryFile()
169
+ >>> x = np.arange(10)
170
+ >>> y = np.sin(x)
171
+ >>> np.savez(outfile, x=x, y=y)
172
+ >>> _ = outfile.seek(0)
173
+
174
+ >>> npz = np.load(outfile)
175
+ >>> isinstance(npz, np.lib.npyio.NpzFile)
176
+ True
177
+ >>> npz
178
+ NpzFile 'object' with keys: x, y
179
+ >>> sorted(npz.files)
180
+ ['x', 'y']
181
+ >>> npz['x'] # getitem access
182
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
183
+ >>> npz.f.x # attribute lookup
184
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
185
+
186
+ """
187
+ # Make __exit__ safe if zipfile_factory raises an exception
188
+ zip = None
189
+ fid = None
190
+ _MAX_REPR_ARRAY_COUNT = 5
191
+
192
+ def __init__(self, fid, own_fid=False, allow_pickle=False,
193
+ pickle_kwargs=None, *,
194
+ max_header_size=_MAX_HEADER_SIZE):
195
+ # Import is postponed to here since zipfile depends on gzip, an
196
+ # optional component of the so-called standard library.
197
+ _zip = zipfile_factory(fid)
198
+ _files = _zip.namelist()
199
+ self.files = [name.removesuffix(".npy") for name in _files]
200
+ self._files = dict(zip(self.files, _files))
201
+ self._files.update(zip(_files, _files))
202
+ self.allow_pickle = allow_pickle
203
+ self.max_header_size = max_header_size
204
+ self.pickle_kwargs = pickle_kwargs
205
+ self.zip = _zip
206
+ self.f = BagObj(self)
207
+ if own_fid:
208
+ self.fid = fid
209
+
210
+ def __enter__(self):
211
+ return self
212
+
213
+ def __exit__(self, exc_type, exc_value, traceback):
214
+ self.close()
215
+
216
+ def close(self):
217
+ """
218
+ Close the file.
219
+
220
+ """
221
+ if self.zip is not None:
222
+ self.zip.close()
223
+ self.zip = None
224
+ if self.fid is not None:
225
+ self.fid.close()
226
+ self.fid = None
227
+ self.f = None # break reference cycle
228
+
229
+ def __del__(self):
230
+ self.close()
231
+
232
+ # Implement the Mapping ABC
233
+ def __iter__(self):
234
+ return iter(self.files)
235
+
236
+ def __len__(self):
237
+ return len(self.files)
238
+
239
+ def __getitem__(self, key):
240
+ try:
241
+ key = self._files[key]
242
+ except KeyError:
243
+ raise KeyError(f"{key} is not a file in the archive") from None
244
+ else:
245
+ with self.zip.open(key) as bytes:
246
+ magic = bytes.read(len(format.MAGIC_PREFIX))
247
+ bytes.seek(0)
248
+ if magic == format.MAGIC_PREFIX:
249
+ # FIXME: This seems like it will copy strings around
250
+ # more than is strictly necessary. The zipfile
251
+ # will read the string and then
252
+ # the format.read_array will copy the string
253
+ # to another place in memory.
254
+ # It would be better if the zipfile could read
255
+ # (or at least uncompress) the data
256
+ # directly into the array memory.
257
+ return format.read_array(
258
+ bytes,
259
+ allow_pickle=self.allow_pickle,
260
+ pickle_kwargs=self.pickle_kwargs,
261
+ max_header_size=self.max_header_size
262
+ )
263
+ else:
264
+ return bytes.read()
265
+
266
+ def __contains__(self, key):
267
+ return (key in self._files)
268
+
269
+ def __repr__(self):
270
+ # Get filename or default to `object`
271
+ if isinstance(self.fid, str):
272
+ filename = self.fid
273
+ else:
274
+ filename = getattr(self.fid, "name", "object")
275
+
276
+ # Get the name of arrays
277
+ array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT])
278
+ if len(self.files) > self._MAX_REPR_ARRAY_COUNT:
279
+ array_names += "..."
280
+ return f"NpzFile {filename!r} with keys: {array_names}"
281
+
282
+ # Work around problems with the docstrings in the Mapping methods
283
+ # They contain a `->`, which confuses the type annotation interpretations
284
+ # of sphinx-docs. See gh-25964
285
+
286
+ def get(self, key, default=None, /):
287
+ """
288
+ D.get(k,[,d]) returns D[k] if k in D, else d. d defaults to None.
289
+ """
290
+ return Mapping.get(self, key, default)
291
+
292
+ def items(self):
293
+ """
294
+ D.items() returns a set-like object providing a view on the items
295
+ """
296
+ return Mapping.items(self)
297
+
298
+ def keys(self):
299
+ """
300
+ D.keys() returns a set-like object providing a view on the keys
301
+ """
302
+ return Mapping.keys(self)
303
+
304
+ def values(self):
305
+ """
306
+ D.values() returns a set-like object providing a view on the values
307
+ """
308
+ return Mapping.values(self)
309
+
310
+
311
+ @set_module('numpy')
312
+ def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,
313
+ encoding='ASCII', *, max_header_size=_MAX_HEADER_SIZE):
314
+ """
315
+ Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
316
+
317
+ .. warning:: Loading files that contain object arrays uses the ``pickle``
318
+ module, which is not secure against erroneous or maliciously
319
+ constructed data. Consider passing ``allow_pickle=False`` to
320
+ load data that is known not to contain object arrays for the
321
+ safer handling of untrusted sources.
322
+
323
+ Parameters
324
+ ----------
325
+ file : file-like object, string, or pathlib.Path
326
+ The file to read. File-like objects must support the
327
+ ``seek()`` and ``read()`` methods and must always
328
+ be opened in binary mode. Pickled files require that the
329
+ file-like object support the ``readline()`` method as well.
330
+ mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
331
+ If not None, then memory-map the file, using the given mode (see
332
+ `numpy.memmap` for a detailed description of the modes). A
333
+ memory-mapped array is kept on disk. However, it can be accessed
334
+ and sliced like any ndarray. Memory mapping is especially useful
335
+ for accessing small fragments of large files without reading the
336
+ entire file into memory.
337
+ allow_pickle : bool, optional
338
+ Allow loading pickled object arrays stored in npy files. Reasons for
339
+ disallowing pickles include security, as loading pickled data can
340
+ execute arbitrary code. If pickles are disallowed, loading object
341
+ arrays will fail. Default: False
342
+ fix_imports : bool, optional
343
+ Only useful when loading Python 2 generated pickled files,
344
+ which includes npy/npz files containing object arrays. If `fix_imports`
345
+ is True, pickle will try to map the old Python 2 names to the new names
346
+ used in Python 3.
347
+ encoding : str, optional
348
+ What encoding to use when reading Python 2 strings. Only useful when
349
+ loading Python 2 generated pickled files, which includes
350
+ npy/npz files containing object arrays. Values other than 'latin1',
351
+ 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
352
+ data. Default: 'ASCII'
353
+ max_header_size : int, optional
354
+ Maximum allowed size of the header. Large headers may not be safe
355
+ to load securely and thus require explicitly passing a larger value.
356
+ See :py:func:`ast.literal_eval()` for details.
357
+ This option is ignored when `allow_pickle` is passed. In that case
358
+ the file is by definition trusted and the limit is unnecessary.
359
+
360
+ Returns
361
+ -------
362
+ result : array, tuple, dict, etc.
363
+ Data stored in the file. For ``.npz`` files, the returned instance
364
+ of NpzFile class must be closed to avoid leaking file descriptors.
365
+
366
+ Raises
367
+ ------
368
+ OSError
369
+ If the input file does not exist or cannot be read.
370
+ UnpicklingError
371
+ If ``allow_pickle=True``, but the file cannot be loaded as a pickle.
372
+ ValueError
373
+ The file contains an object array, but ``allow_pickle=False`` given.
374
+ EOFError
375
+ When calling ``np.load`` multiple times on the same file handle,
376
+ if all data has already been read
377
+
378
+ See Also
379
+ --------
380
+ save, savez, savez_compressed, loadtxt
381
+ memmap : Create a memory-map to an array stored in a file on disk.
382
+ lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
383
+
384
+ Notes
385
+ -----
386
+ - If the file contains pickle data, then whatever object is stored
387
+ in the pickle is returned.
388
+ - If the file is a ``.npy`` file, then a single array is returned.
389
+ - If the file is a ``.npz`` file, then a dictionary-like object is
390
+ returned, containing ``{filename: array}`` key-value pairs, one for
391
+ each file in the archive.
392
+ - If the file is a ``.npz`` file, the returned value supports the
393
+ context manager protocol in a similar fashion to the open function::
394
+
395
+ with load('foo.npz') as data:
396
+ a = data['a']
397
+
398
+ The underlying file descriptor is closed when exiting the 'with'
399
+ block.
400
+
401
+ Examples
402
+ --------
403
+ >>> import numpy as np
404
+
405
+ Store data to disk, and load it again:
406
+
407
+ >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
408
+ >>> np.load('/tmp/123.npy')
409
+ array([[1, 2, 3],
410
+ [4, 5, 6]])
411
+
412
+ Store compressed data to disk, and load it again:
413
+
414
+ >>> a=np.array([[1, 2, 3], [4, 5, 6]])
415
+ >>> b=np.array([1, 2])
416
+ >>> np.savez('/tmp/123.npz', a=a, b=b)
417
+ >>> data = np.load('/tmp/123.npz')
418
+ >>> data['a']
419
+ array([[1, 2, 3],
420
+ [4, 5, 6]])
421
+ >>> data['b']
422
+ array([1, 2])
423
+ >>> data.close()
424
+
425
+ Mem-map the stored array, and then access the second row
426
+ directly from disk:
427
+
428
+ >>> X = np.load('/tmp/123.npy', mmap_mode='r')
429
+ >>> X[1, :]
430
+ memmap([4, 5, 6])
431
+
432
+ """
433
+ if encoding not in ('ASCII', 'latin1', 'bytes'):
434
+ # The 'encoding' value for pickle also affects what encoding
435
+ # the serialized binary data of NumPy arrays is loaded
436
+ # in. Pickle does not pass on the encoding information to
437
+ # NumPy. The unpickling code in numpy._core.multiarray is
438
+ # written to assume that unicode data appearing where binary
439
+ # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'.
440
+ #
441
+ # Other encoding values can corrupt binary data, and we
442
+ # purposefully disallow them. For the same reason, the errors=
443
+ # argument is not exposed, as values other than 'strict'
444
+ # result can similarly silently corrupt numerical data.
445
+ raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'")
446
+
447
+ pickle_kwargs = {'encoding': encoding, 'fix_imports': fix_imports}
448
+
449
+ with contextlib.ExitStack() as stack:
450
+ if hasattr(file, 'read'):
451
+ fid = file
452
+ own_fid = False
453
+ else:
454
+ fid = stack.enter_context(open(os.fspath(file), "rb"))
455
+ own_fid = True
456
+
457
+ # Code to distinguish from NumPy binary files and pickles.
458
+ _ZIP_PREFIX = b'PK\x03\x04'
459
+ _ZIP_SUFFIX = b'PK\x05\x06' # empty zip files start with this
460
+ N = len(format.MAGIC_PREFIX)
461
+ magic = fid.read(N)
462
+ if not magic:
463
+ raise EOFError("No data left in file")
464
+ # If the file size is less than N, we need to make sure not
465
+ # to seek past the beginning of the file
466
+ fid.seek(-min(N, len(magic)), 1) # back-up
467
+ if magic.startswith((_ZIP_PREFIX, _ZIP_SUFFIX)):
468
+ # zip-file (assume .npz)
469
+ # Potentially transfer file ownership to NpzFile
470
+ stack.pop_all()
471
+ ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle,
472
+ pickle_kwargs=pickle_kwargs,
473
+ max_header_size=max_header_size)
474
+ return ret
475
+ elif magic == format.MAGIC_PREFIX:
476
+ # .npy file
477
+ if mmap_mode:
478
+ if allow_pickle:
479
+ max_header_size = 2**64
480
+ return format.open_memmap(file, mode=mmap_mode,
481
+ max_header_size=max_header_size)
482
+ else:
483
+ return format.read_array(fid, allow_pickle=allow_pickle,
484
+ pickle_kwargs=pickle_kwargs,
485
+ max_header_size=max_header_size)
486
+ else:
487
+ # Try a pickle
488
+ if not allow_pickle:
489
+ raise ValueError(
490
+ "This file contains pickled (object) data. If you trust "
491
+ "the file you can load it unsafely using the "
492
+ "`allow_pickle=` keyword argument or `pickle.load()`.")
493
+ try:
494
+ return pickle.load(fid, **pickle_kwargs)
495
+ except Exception as e:
496
+ raise pickle.UnpicklingError(
497
+ f"Failed to interpret file {file!r} as a pickle") from e
498
+
499
+
500
+ def _save_dispatcher(file, arr, allow_pickle=None, fix_imports=None):
501
+ return (arr,)
502
+
503
+
504
+ @array_function_dispatch(_save_dispatcher)
505
+ def save(file, arr, allow_pickle=True, fix_imports=np._NoValue):
506
+ """
507
+ Save an array to a binary file in NumPy ``.npy`` format.
508
+
509
+ Parameters
510
+ ----------
511
+ file : file, str, or pathlib.Path
512
+ File or filename to which the data is saved. If file is a file-object,
513
+ then the filename is unchanged. If file is a string or Path,
514
+ a ``.npy`` extension will be appended to the filename if it does not
515
+ already have one.
516
+ arr : array_like
517
+ Array data to be saved.
518
+ allow_pickle : bool, optional
519
+ Allow saving object arrays using Python pickles. Reasons for
520
+ disallowing pickles include security (loading pickled data can execute
521
+ arbitrary code) and portability (pickled objects may not be loadable
522
+ on different Python installations, for example if the stored objects
523
+ require libraries that are not available, and not all pickled data is
524
+ compatible between different versions of Python).
525
+ Default: True
526
+ fix_imports : bool, optional
527
+ The `fix_imports` flag is deprecated and has no effect.
528
+
529
+ .. deprecated:: 2.1
530
+ This flag is ignored since NumPy 1.17 and was only needed to
531
+ support loading in Python 2 some files written in Python 3.
532
+
533
+ See Also
534
+ --------
535
+ savez : Save several arrays into a ``.npz`` archive
536
+ savetxt, load
537
+
538
+ Notes
539
+ -----
540
+ For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
541
+
542
+ Any data saved to the file is appended to the end of the file.
543
+
544
+ Examples
545
+ --------
546
+ >>> import numpy as np
547
+
548
+ >>> from tempfile import TemporaryFile
549
+ >>> outfile = TemporaryFile()
550
+
551
+ >>> x = np.arange(10)
552
+ >>> np.save(outfile, x)
553
+
554
+ >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
555
+ >>> np.load(outfile)
556
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
557
+
558
+
559
+ >>> with open('test.npy', 'wb') as f:
560
+ ... np.save(f, np.array([1, 2]))
561
+ ... np.save(f, np.array([1, 3]))
562
+ >>> with open('test.npy', 'rb') as f:
563
+ ... a = np.load(f)
564
+ ... b = np.load(f)
565
+ >>> print(a, b)
566
+ # [1 2] [1 3]
567
+ """
568
+ if fix_imports is not np._NoValue:
569
+ # Deprecated 2024-05-16, NumPy 2.1
570
+ warnings.warn(
571
+ "The 'fix_imports' flag is deprecated and has no effect. "
572
+ "(Deprecated in NumPy 2.1)",
573
+ DeprecationWarning, stacklevel=2)
574
+ if hasattr(file, 'write'):
575
+ file_ctx = contextlib.nullcontext(file)
576
+ else:
577
+ file = os.fspath(file)
578
+ if not file.endswith('.npy'):
579
+ file = file + '.npy'
580
+ file_ctx = open(file, "wb")
581
+
582
+ with file_ctx as fid:
583
+ arr = np.asanyarray(arr)
584
+ format.write_array(fid, arr, allow_pickle=allow_pickle,
585
+ pickle_kwargs={'fix_imports': fix_imports})
586
+
587
+
588
+ def _savez_dispatcher(file, *args, allow_pickle=True, **kwds):
589
+ yield from args
590
+ yield from kwds.values()
591
+
592
+
593
+ @array_function_dispatch(_savez_dispatcher)
594
+ def savez(file, *args, allow_pickle=True, **kwds):
595
+ """Save several arrays into a single file in uncompressed ``.npz`` format.
596
+
597
+ Provide arrays as keyword arguments to store them under the
598
+ corresponding name in the output file: ``savez(fn, x=x, y=y)``.
599
+
600
+ If arrays are specified as positional arguments, i.e., ``savez(fn,
601
+ x, y)``, their names will be `arr_0`, `arr_1`, etc.
602
+
603
+ Parameters
604
+ ----------
605
+ file : file, str, or pathlib.Path
606
+ Either the filename (string) or an open file (file-like object)
607
+ where the data will be saved. If file is a string or a Path, the
608
+ ``.npz`` extension will be appended to the filename if it is not
609
+ already there.
610
+ args : Arguments, optional
611
+ Arrays to save to the file. Please use keyword arguments (see
612
+ `kwds` below) to assign names to arrays. Arrays specified as
613
+ args will be named "arr_0", "arr_1", and so on.
614
+ allow_pickle : bool, optional
615
+ Allow saving object arrays using Python pickles. Reasons for
616
+ disallowing pickles include security (loading pickled data can execute
617
+ arbitrary code) and portability (pickled objects may not be loadable
618
+ on different Python installations, for example if the stored objects
619
+ require libraries that are not available, and not all pickled data is
620
+ compatible between different versions of Python).
621
+ Default: True
622
+ kwds : Keyword arguments, optional
623
+ Arrays to save to the file. Each array will be saved to the
624
+ output file with its corresponding keyword name.
625
+
626
+ Returns
627
+ -------
628
+ None
629
+
630
+ See Also
631
+ --------
632
+ save : Save a single array to a binary file in NumPy format.
633
+ savetxt : Save an array to a file as plain text.
634
+ savez_compressed : Save several arrays into a compressed ``.npz`` archive
635
+
636
+ Notes
637
+ -----
638
+ The ``.npz`` file format is a zipped archive of files named after the
639
+ variables they contain. The archive is not compressed and each file
640
+ in the archive contains one variable in ``.npy`` format. For a
641
+ description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
642
+
643
+ When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
644
+ object is returned. This is a dictionary-like object which can be queried
645
+ for its list of arrays (with the ``.files`` attribute), and for the arrays
646
+ themselves.
647
+
648
+ Keys passed in `kwds` are used as filenames inside the ZIP archive.
649
+ Therefore, keys should be valid filenames; e.g., avoid keys that begin with
650
+ ``/`` or contain ``.``.
651
+
652
+ When naming variables with keyword arguments, it is not possible to name a
653
+ variable ``file``, as this would cause the ``file`` argument to be defined
654
+ twice in the call to ``savez``.
655
+
656
+ Examples
657
+ --------
658
+ >>> import numpy as np
659
+ >>> from tempfile import TemporaryFile
660
+ >>> outfile = TemporaryFile()
661
+ >>> x = np.arange(10)
662
+ >>> y = np.sin(x)
663
+
664
+ Using `savez` with \\*args, the arrays are saved with default names.
665
+
666
+ >>> np.savez(outfile, x, y)
667
+ >>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
668
+ >>> npzfile = np.load(outfile)
669
+ >>> npzfile.files
670
+ ['arr_0', 'arr_1']
671
+ >>> npzfile['arr_0']
672
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
673
+
674
+ Using `savez` with \\**kwds, the arrays are saved with the keyword names.
675
+
676
+ >>> outfile = TemporaryFile()
677
+ >>> np.savez(outfile, x=x, y=y)
678
+ >>> _ = outfile.seek(0)
679
+ >>> npzfile = np.load(outfile)
680
+ >>> sorted(npzfile.files)
681
+ ['x', 'y']
682
+ >>> npzfile['x']
683
+ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
684
+
685
+ """
686
+ _savez(file, args, kwds, False, allow_pickle=allow_pickle)
687
+
688
+
689
+ def _savez_compressed_dispatcher(file, *args, allow_pickle=True, **kwds):
690
+ yield from args
691
+ yield from kwds.values()
692
+
693
+
694
+ @array_function_dispatch(_savez_compressed_dispatcher)
695
+ def savez_compressed(file, *args, allow_pickle=True, **kwds):
696
+ """
697
+ Save several arrays into a single file in compressed ``.npz`` format.
698
+
699
+ Provide arrays as keyword arguments to store them under the
700
+ corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``.
701
+
702
+ If arrays are specified as positional arguments, i.e.,
703
+ ``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc.
704
+
705
+ Parameters
706
+ ----------
707
+ file : file, str, or pathlib.Path
708
+ Either the filename (string) or an open file (file-like object)
709
+ where the data will be saved. If file is a string or a Path, the
710
+ ``.npz`` extension will be appended to the filename if it is not
711
+ already there.
712
+ args : Arguments, optional
713
+ Arrays to save to the file. Please use keyword arguments (see
714
+ `kwds` below) to assign names to arrays. Arrays specified as
715
+ args will be named "arr_0", "arr_1", and so on.
716
+ allow_pickle : bool, optional
717
+ Allow saving object arrays using Python pickles. Reasons for
718
+ disallowing pickles include security (loading pickled data can execute
719
+ arbitrary code) and portability (pickled objects may not be loadable
720
+ on different Python installations, for example if the stored objects
721
+ require libraries that are not available, and not all pickled data is
722
+ compatible between different versions of Python).
723
+ Default: True
724
+ kwds : Keyword arguments, optional
725
+ Arrays to save to the file. Each array will be saved to the
726
+ output file with its corresponding keyword name.
727
+
728
+ Returns
729
+ -------
730
+ None
731
+
732
+ See Also
733
+ --------
734
+ numpy.save : Save a single array to a binary file in NumPy format.
735
+ numpy.savetxt : Save an array to a file as plain text.
736
+ numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
737
+ numpy.load : Load the files created by savez_compressed.
738
+
739
+ Notes
740
+ -----
741
+ The ``.npz`` file format is a zipped archive of files named after the
742
+ variables they contain. The archive is compressed with
743
+ ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable
744
+ in ``.npy`` format. For a description of the ``.npy`` format, see
745
+ :py:mod:`numpy.lib.format`.
746
+
747
+
748
+ When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
749
+ object is returned. This is a dictionary-like object which can be queried
750
+ for its list of arrays (with the ``.files`` attribute), and for the arrays
751
+ themselves.
752
+
753
+ Examples
754
+ --------
755
+ >>> import numpy as np
756
+ >>> test_array = np.random.rand(3, 2)
757
+ >>> test_vector = np.random.rand(4)
758
+ >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
759
+ >>> loaded = np.load('/tmp/123.npz')
760
+ >>> print(np.array_equal(test_array, loaded['a']))
761
+ True
762
+ >>> print(np.array_equal(test_vector, loaded['b']))
763
+ True
764
+
765
+ """
766
+ _savez(file, args, kwds, True, allow_pickle=allow_pickle)
767
+
768
+
769
+ def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):
770
+ # Import is postponed to here since zipfile depends on gzip, an optional
771
+ # component of the so-called standard library.
772
+ import zipfile
773
+
774
+ if not hasattr(file, 'write'):
775
+ file = os.fspath(file)
776
+ if not file.endswith('.npz'):
777
+ file = file + '.npz'
778
+
779
+ namedict = kwds
780
+ for i, val in enumerate(args):
781
+ key = 'arr_%d' % i
782
+ if key in namedict.keys():
783
+ raise ValueError(
784
+ f"Cannot use un-named variables and keyword {key}")
785
+ namedict[key] = val
786
+
787
+ if compress:
788
+ compression = zipfile.ZIP_DEFLATED
789
+ else:
790
+ compression = zipfile.ZIP_STORED
791
+
792
+ zipf = zipfile_factory(file, mode="w", compression=compression)
793
+ try:
794
+ for key, val in namedict.items():
795
+ fname = key + '.npy'
796
+ val = np.asanyarray(val)
797
+ # always force zip64, gh-10776
798
+ with zipf.open(fname, 'w', force_zip64=True) as fid:
799
+ format.write_array(fid, val,
800
+ allow_pickle=allow_pickle,
801
+ pickle_kwargs=pickle_kwargs)
802
+ finally:
803
+ zipf.close()
804
+
805
+
806
+ def _ensure_ndmin_ndarray_check_param(ndmin):
807
+ """Just checks if the param ndmin is supported on
808
+ _ensure_ndmin_ndarray. It is intended to be used as
809
+ verification before running anything expensive.
810
+ e.g. loadtxt, genfromtxt
811
+ """
812
+ # Check correctness of the values of `ndmin`
813
+ if ndmin not in [0, 1, 2]:
814
+ raise ValueError(f"Illegal value of ndmin keyword: {ndmin}")
815
+
816
+ def _ensure_ndmin_ndarray(a, *, ndmin: int):
817
+ """This is a helper function of loadtxt and genfromtxt to ensure
818
+ proper minimum dimension as requested
819
+
820
+ ndim : int. Supported values 1, 2, 3
821
+ ^^ whenever this changes, keep in sync with
822
+ _ensure_ndmin_ndarray_check_param
823
+ """
824
+ # Verify that the array has at least dimensions `ndmin`.
825
+ # Tweak the size and shape of the arrays - remove extraneous dimensions
826
+ if a.ndim > ndmin:
827
+ a = np.squeeze(a)
828
+ # and ensure we have the minimum number of dimensions asked for
829
+ # - has to be in this order for the odd case ndmin=1, a.squeeze().ndim=0
830
+ if a.ndim < ndmin:
831
+ if ndmin == 1:
832
+ a = np.atleast_1d(a)
833
+ elif ndmin == 2:
834
+ a = np.atleast_2d(a).T
835
+
836
+ return a
837
+
838
+
839
+ # amount of lines loadtxt reads in one chunk, can be overridden for testing
840
+ _loadtxt_chunksize = 50000
841
+
842
+
843
+ def _check_nonneg_int(value, name="argument"):
844
+ try:
845
+ operator.index(value)
846
+ except TypeError:
847
+ raise TypeError(f"{name} must be an integer") from None
848
+ if value < 0:
849
+ raise ValueError(f"{name} must be nonnegative")
850
+
851
+
852
+ def _preprocess_comments(iterable, comments, encoding):
853
+ """
854
+ Generator that consumes a line iterated iterable and strips out the
855
+ multiple (or multi-character) comments from lines.
856
+ This is a pre-processing step to achieve feature parity with loadtxt
857
+ (we assume that this feature is a nieche feature).
858
+ """
859
+ for line in iterable:
860
+ if isinstance(line, bytes):
861
+ # Need to handle conversion here, or the splitting would fail
862
+ line = line.decode(encoding)
863
+
864
+ for c in comments:
865
+ line = line.split(c, 1)[0]
866
+
867
+ yield line
868
+
869
+
870
+ # The number of rows we read in one go if confronted with a parametric dtype
871
+ _loadtxt_chunksize = 50000
872
+
873
+
874
+ def _read(fname, *, delimiter=',', comment='#', quote='"',
875
+ imaginary_unit='j', usecols=None, skiplines=0,
876
+ max_rows=None, converters=None, ndmin=None, unpack=False,
877
+ dtype=np.float64, encoding=None):
878
+ r"""
879
+ Read a NumPy array from a text file.
880
+ This is a helper function for loadtxt.
881
+
882
+ Parameters
883
+ ----------
884
+ fname : file, str, or pathlib.Path
885
+ The filename or the file to be read.
886
+ delimiter : str, optional
887
+ Field delimiter of the fields in line of the file.
888
+ Default is a comma, ','. If None any sequence of whitespace is
889
+ considered a delimiter.
890
+ comment : str or sequence of str or None, optional
891
+ Character that begins a comment. All text from the comment
892
+ character to the end of the line is ignored.
893
+ Multiple comments or multiple-character comment strings are supported,
894
+ but may be slower and `quote` must be empty if used.
895
+ Use None to disable all use of comments.
896
+ quote : str or None, optional
897
+ Character that is used to quote string fields. Default is '"'
898
+ (a double quote). Use None to disable quote support.
899
+ imaginary_unit : str, optional
900
+ Character that represent the imaginary unit `sqrt(-1)`.
901
+ Default is 'j'.
902
+ usecols : array_like, optional
903
+ A one-dimensional array of integer column numbers. These are the
904
+ columns from the file to be included in the array. If this value
905
+ is not given, all the columns are used.
906
+ skiplines : int, optional
907
+ Number of lines to skip before interpreting the data in the file.
908
+ max_rows : int, optional
909
+ Maximum number of rows of data to read. Default is to read the
910
+ entire file.
911
+ converters : dict or callable, optional
912
+ A function to parse all columns strings into the desired value, or
913
+ a dictionary mapping column number to a parser function.
914
+ E.g. if column 0 is a date string: ``converters = {0: datestr2num}``.
915
+ Converters can also be used to provide a default value for missing
916
+ data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will
917
+ convert empty fields to 0.
918
+ Default: None
919
+ ndmin : int, optional
920
+ Minimum dimension of the array returned.
921
+ Allowed values are 0, 1 or 2. Default is 0.
922
+ unpack : bool, optional
923
+ If True, the returned array is transposed, so that arguments may be
924
+ unpacked using ``x, y, z = read(...)``. When used with a structured
925
+ data-type, arrays are returned for each field. Default is False.
926
+ dtype : numpy data type
927
+ A NumPy dtype instance, can be a structured dtype to map to the
928
+ columns of the file.
929
+ encoding : str, optional
930
+ Encoding used to decode the inputfile. The special value 'bytes'
931
+ (the default) enables backwards-compatible behavior for `converters`,
932
+ ensuring that inputs to the converter functions are encoded
933
+ bytes objects. The special value 'bytes' has no additional effect if
934
+ ``converters=None``. If encoding is ``'bytes'`` or ``None``, the
935
+ default system encoding is used.
936
+
937
+ Returns
938
+ -------
939
+ ndarray
940
+ NumPy array.
941
+ """
942
+ # Handle special 'bytes' keyword for encoding
943
+ byte_converters = False
944
+ if encoding == 'bytes':
945
+ encoding = None
946
+ byte_converters = True
947
+
948
+ if dtype is None:
949
+ raise TypeError("a dtype must be provided.")
950
+ dtype = np.dtype(dtype)
951
+
952
+ read_dtype_via_object_chunks = None
953
+ if dtype.kind in 'SUM' and dtype in {
954
+ np.dtype("S0"), np.dtype("U0"), np.dtype("M8"), np.dtype("m8")}:
955
+ # This is a legacy "flexible" dtype. We do not truly support
956
+ # parametric dtypes currently (no dtype discovery step in the core),
957
+ # but have to support these for backward compatibility.
958
+ read_dtype_via_object_chunks = dtype
959
+ dtype = np.dtype(object)
960
+
961
+ if usecols is not None:
962
+ # Allow usecols to be a single int or a sequence of ints, the C-code
963
+ # handles the rest
964
+ try:
965
+ usecols = list(usecols)
966
+ except TypeError:
967
+ usecols = [usecols]
968
+
969
+ _ensure_ndmin_ndarray_check_param(ndmin)
970
+
971
+ if comment is None:
972
+ comments = None
973
+ else:
974
+ # assume comments are a sequence of strings
975
+ if "" in comment:
976
+ raise ValueError(
977
+ "comments cannot be an empty string. Use comments=None to "
978
+ "disable comments."
979
+ )
980
+ comments = tuple(comment)
981
+ comment = None
982
+ if len(comments) == 0:
983
+ comments = None # No comments at all
984
+ elif len(comments) == 1:
985
+ # If there is only one comment, and that comment has one character,
986
+ # the normal parsing can deal with it just fine.
987
+ if isinstance(comments[0], str) and len(comments[0]) == 1:
988
+ comment = comments[0]
989
+ comments = None
990
+ # Input validation if there are multiple comment characters
991
+ elif delimiter in comments:
992
+ raise TypeError(
993
+ f"Comment characters '{comments}' cannot include the "
994
+ f"delimiter '{delimiter}'"
995
+ )
996
+
997
+ # comment is now either a 1 or 0 character string or a tuple:
998
+ if comments is not None:
999
+ # Note: An earlier version support two character comments (and could
1000
+ # have been extended to multiple characters, we assume this is
1001
+ # rare enough to not optimize for.
1002
+ if quote is not None:
1003
+ raise ValueError(
1004
+ "when multiple comments or a multi-character comment is "
1005
+ "given, quotes are not supported. In this case quotechar "
1006
+ "must be set to None.")
1007
+
1008
+ if len(imaginary_unit) != 1:
1009
+ raise ValueError('len(imaginary_unit) must be 1.')
1010
+
1011
+ _check_nonneg_int(skiplines)
1012
+ if max_rows is not None:
1013
+ _check_nonneg_int(max_rows)
1014
+ else:
1015
+ # Passing -1 to the C code means "read the entire file".
1016
+ max_rows = -1
1017
+
1018
+ fh_closing_ctx = contextlib.nullcontext()
1019
+ filelike = False
1020
+ try:
1021
+ if isinstance(fname, os.PathLike):
1022
+ fname = os.fspath(fname)
1023
+ if isinstance(fname, str):
1024
+ fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
1025
+ if encoding is None:
1026
+ encoding = getattr(fh, 'encoding', 'latin1')
1027
+
1028
+ fh_closing_ctx = contextlib.closing(fh)
1029
+ data = fh
1030
+ filelike = True
1031
+ else:
1032
+ if encoding is None:
1033
+ encoding = getattr(fname, 'encoding', 'latin1')
1034
+ data = iter(fname)
1035
+ except TypeError as e:
1036
+ raise ValueError(
1037
+ f"fname must be a string, filehandle, list of strings,\n"
1038
+ f"or generator. Got {type(fname)} instead.") from e
1039
+
1040
+ with fh_closing_ctx:
1041
+ if comments is not None:
1042
+ if filelike:
1043
+ data = iter(data)
1044
+ filelike = False
1045
+ data = _preprocess_comments(data, comments, encoding)
1046
+
1047
+ if read_dtype_via_object_chunks is None:
1048
+ arr = _load_from_filelike(
1049
+ data, delimiter=delimiter, comment=comment, quote=quote,
1050
+ imaginary_unit=imaginary_unit,
1051
+ usecols=usecols, skiplines=skiplines, max_rows=max_rows,
1052
+ converters=converters, dtype=dtype,
1053
+ encoding=encoding, filelike=filelike,
1054
+ byte_converters=byte_converters)
1055
+
1056
+ else:
1057
+ # This branch reads the file into chunks of object arrays and then
1058
+ # casts them to the desired actual dtype. This ensures correct
1059
+ # string-length and datetime-unit discovery (like `arr.astype()`).
1060
+ # Due to chunking, certain error reports are less clear, currently.
1061
+ if filelike:
1062
+ data = iter(data) # cannot chunk when reading from file
1063
+ filelike = False
1064
+
1065
+ c_byte_converters = False
1066
+ if read_dtype_via_object_chunks == "S":
1067
+ c_byte_converters = True # Use latin1 rather than ascii
1068
+
1069
+ chunks = []
1070
+ while max_rows != 0:
1071
+ if max_rows < 0:
1072
+ chunk_size = _loadtxt_chunksize
1073
+ else:
1074
+ chunk_size = min(_loadtxt_chunksize, max_rows)
1075
+
1076
+ next_arr = _load_from_filelike(
1077
+ data, delimiter=delimiter, comment=comment, quote=quote,
1078
+ imaginary_unit=imaginary_unit,
1079
+ usecols=usecols, skiplines=skiplines, max_rows=chunk_size,
1080
+ converters=converters, dtype=dtype,
1081
+ encoding=encoding, filelike=filelike,
1082
+ byte_converters=byte_converters,
1083
+ c_byte_converters=c_byte_converters)
1084
+ # Cast here already. We hope that this is better even for
1085
+ # large files because the storage is more compact. It could
1086
+ # be adapted (in principle the concatenate could cast).
1087
+ chunks.append(next_arr.astype(read_dtype_via_object_chunks))
1088
+
1089
+ skiplines = 0 # Only have to skip for first chunk
1090
+ if max_rows >= 0:
1091
+ max_rows -= chunk_size
1092
+ if len(next_arr) < chunk_size:
1093
+ # There was less data than requested, so we are done.
1094
+ break
1095
+
1096
+ # Need at least one chunk, but if empty, the last one may have
1097
+ # the wrong shape.
1098
+ if len(chunks) > 1 and len(chunks[-1]) == 0:
1099
+ del chunks[-1]
1100
+ if len(chunks) == 1:
1101
+ arr = chunks[0]
1102
+ else:
1103
+ arr = np.concatenate(chunks, axis=0)
1104
+
1105
+ # NOTE: ndmin works as advertised for structured dtypes, but normally
1106
+ # these would return a 1D result plus the structured dimension,
1107
+ # so ndmin=2 adds a third dimension even when no squeezing occurs.
1108
+ # A `squeeze=False` could be a better solution (pandas uses squeeze).
1109
+ arr = _ensure_ndmin_ndarray(arr, ndmin=ndmin)
1110
+
1111
+ if arr.shape:
1112
+ if arr.shape[0] == 0:
1113
+ warnings.warn(
1114
+ f'loadtxt: input contained no data: "{fname}"',
1115
+ category=UserWarning,
1116
+ stacklevel=3
1117
+ )
1118
+
1119
+ if unpack:
1120
+ # Unpack structured dtypes if requested:
1121
+ dt = arr.dtype
1122
+ if dt.names is not None:
1123
+ # For structured arrays, return an array for each field.
1124
+ return [arr[field] for field in dt.names]
1125
+ else:
1126
+ return arr.T
1127
+ else:
1128
+ return arr
1129
+
1130
+
1131
+ @finalize_array_function_like
1132
+ @set_module('numpy')
1133
+ def loadtxt(fname, dtype=float, comments='#', delimiter=None,
1134
+ converters=None, skiprows=0, usecols=None, unpack=False,
1135
+ ndmin=0, encoding=None, max_rows=None, *, quotechar=None,
1136
+ like=None):
1137
+ r"""
1138
+ Load data from a text file.
1139
+
1140
+ Parameters
1141
+ ----------
1142
+ fname : file, str, pathlib.Path, list of str, generator
1143
+ File, filename, list, or generator to read. If the filename
1144
+ extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
1145
+ that generators must return bytes or strings. The strings
1146
+ in a list or produced by a generator are treated as lines.
1147
+ dtype : data-type, optional
1148
+ Data-type of the resulting array; default: float. If this is a
1149
+ structured data-type, the resulting array will be 1-dimensional, and
1150
+ each row will be interpreted as an element of the array. In this
1151
+ case, the number of columns used must match the number of fields in
1152
+ the data-type.
1153
+ comments : str or sequence of str or None, optional
1154
+ The characters or list of characters used to indicate the start of a
1155
+ comment. None implies no comments. For backwards compatibility, byte
1156
+ strings will be decoded as 'latin1'. The default is '#'.
1157
+ delimiter : str, optional
1158
+ The character used to separate the values. For backwards compatibility,
1159
+ byte strings will be decoded as 'latin1'. The default is whitespace.
1160
+
1161
+ .. versionchanged:: 1.23.0
1162
+ Only single character delimiters are supported. Newline characters
1163
+ cannot be used as the delimiter.
1164
+
1165
+ converters : dict or callable, optional
1166
+ Converter functions to customize value parsing. If `converters` is
1167
+ callable, the function is applied to all columns, else it must be a
1168
+ dict that maps column number to a parser function.
1169
+ See examples for further details.
1170
+ Default: None.
1171
+
1172
+ .. versionchanged:: 1.23.0
1173
+ The ability to pass a single callable to be applied to all columns
1174
+ was added.
1175
+
1176
+ skiprows : int, optional
1177
+ Skip the first `skiprows` lines, including comments; default: 0.
1178
+ usecols : int or sequence, optional
1179
+ Which columns to read, with 0 being the first. For example,
1180
+ ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
1181
+ The default, None, results in all columns being read.
1182
+ unpack : bool, optional
1183
+ If True, the returned array is transposed, so that arguments may be
1184
+ unpacked using ``x, y, z = loadtxt(...)``. When used with a
1185
+ structured data-type, arrays are returned for each field.
1186
+ Default is False.
1187
+ ndmin : int, optional
1188
+ The returned array will have at least `ndmin` dimensions.
1189
+ Otherwise mono-dimensional axes will be squeezed.
1190
+ Legal values: 0 (default), 1 or 2.
1191
+ encoding : str, optional
1192
+ Encoding used to decode the inputfile. Does not apply to input streams.
1193
+ The special value 'bytes' enables backward compatibility workarounds
1194
+ that ensures you receive byte arrays as results if possible and passes
1195
+ 'latin1' encoded strings to converters. Override this value to receive
1196
+ unicode arrays and pass strings as input to converters. If set to None
1197
+ the system default is used. The default value is None.
1198
+
1199
+ .. versionchanged:: 2.0
1200
+ Before NumPy 2, the default was ``'bytes'`` for Python 2
1201
+ compatibility. The default is now ``None``.
1202
+
1203
+ max_rows : int, optional
1204
+ Read `max_rows` rows of content after `skiprows` lines. The default is
1205
+ to read all the rows. Note that empty rows containing no data such as
1206
+ empty lines and comment lines are not counted towards `max_rows`,
1207
+ while such lines are counted in `skiprows`.
1208
+
1209
+ .. versionchanged:: 1.23.0
1210
+ Lines containing no data, including comment lines (e.g., lines
1211
+ starting with '#' or as specified via `comments`) are not counted
1212
+ towards `max_rows`.
1213
+ quotechar : unicode character or None, optional
1214
+ The character used to denote the start and end of a quoted item.
1215
+ Occurrences of the delimiter or comment characters are ignored within
1216
+ a quoted item. The default value is ``quotechar=None``, which means
1217
+ quoting support is disabled.
1218
+
1219
+ If two consecutive instances of `quotechar` are found within a quoted
1220
+ field, the first is treated as an escape character. See examples.
1221
+
1222
+ .. versionadded:: 1.23.0
1223
+ ${ARRAY_FUNCTION_LIKE}
1224
+
1225
+ .. versionadded:: 1.20.0
1226
+
1227
+ Returns
1228
+ -------
1229
+ out : ndarray
1230
+ Data read from the text file.
1231
+
1232
+ See Also
1233
+ --------
1234
+ load, fromstring, fromregex
1235
+ genfromtxt : Load data with missing values handled as specified.
1236
+ scipy.io.loadmat : reads MATLAB data files
1237
+
1238
+ Notes
1239
+ -----
1240
+ This function aims to be a fast reader for simply formatted files. The
1241
+ `genfromtxt` function provides more sophisticated handling of, e.g.,
1242
+ lines with missing values.
1243
+
1244
+ Each row in the input text file must have the same number of values to be
1245
+ able to read all values. If all rows do not have same number of values, a
1246
+ subset of up to n columns (where n is the least number of values present
1247
+ in all rows) can be read by specifying the columns via `usecols`.
1248
+
1249
+ The strings produced by the Python float.hex method can be used as
1250
+ input for floats.
1251
+
1252
+ Examples
1253
+ --------
1254
+ >>> import numpy as np
1255
+ >>> from io import StringIO # StringIO behaves like a file object
1256
+ >>> c = StringIO("0 1\n2 3")
1257
+ >>> np.loadtxt(c)
1258
+ array([[0., 1.],
1259
+ [2., 3.]])
1260
+
1261
+ >>> d = StringIO("M 21 72\nF 35 58")
1262
+ >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
1263
+ ... 'formats': ('S1', 'i4', 'f4')})
1264
+ array([(b'M', 21, 72.), (b'F', 35, 58.)],
1265
+ dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])
1266
+
1267
+ >>> c = StringIO("1,0,2\n3,0,4")
1268
+ >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
1269
+ >>> x
1270
+ array([1., 3.])
1271
+ >>> y
1272
+ array([2., 4.])
1273
+
1274
+ The `converters` argument is used to specify functions to preprocess the
1275
+ text prior to parsing. `converters` can be a dictionary that maps
1276
+ preprocessing functions to each column:
1277
+
1278
+ >>> s = StringIO("1.618, 2.296\n3.141, 4.669\n")
1279
+ >>> conv = {
1280
+ ... 0: lambda x: np.floor(float(x)), # conversion fn for column 0
1281
+ ... 1: lambda x: np.ceil(float(x)), # conversion fn for column 1
1282
+ ... }
1283
+ >>> np.loadtxt(s, delimiter=",", converters=conv)
1284
+ array([[1., 3.],
1285
+ [3., 5.]])
1286
+
1287
+ `converters` can be a callable instead of a dictionary, in which case it
1288
+ is applied to all columns:
1289
+
1290
+ >>> s = StringIO("0xDE 0xAD\n0xC0 0xDE")
1291
+ >>> import functools
1292
+ >>> conv = functools.partial(int, base=16)
1293
+ >>> np.loadtxt(s, converters=conv)
1294
+ array([[222., 173.],
1295
+ [192., 222.]])
1296
+
1297
+ This example shows how `converters` can be used to convert a field
1298
+ with a trailing minus sign into a negative number.
1299
+
1300
+ >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
1301
+ >>> def conv(fld):
1302
+ ... return -float(fld[:-1]) if fld.endswith("-") else float(fld)
1303
+ ...
1304
+ >>> np.loadtxt(s, converters=conv)
1305
+ array([[ 10.01, -31.25],
1306
+ [ 19.22, 64.31],
1307
+ [-17.57, 63.94]])
1308
+
1309
+ Using a callable as the converter can be particularly useful for handling
1310
+ values with different formatting, e.g. floats with underscores:
1311
+
1312
+ >>> s = StringIO("1 2.7 100_000")
1313
+ >>> np.loadtxt(s, converters=float)
1314
+ array([1.e+00, 2.7e+00, 1.e+05])
1315
+
1316
+ This idea can be extended to automatically handle values specified in
1317
+ many different formats, such as hex values:
1318
+
1319
+ >>> def conv(val):
1320
+ ... try:
1321
+ ... return float(val)
1322
+ ... except ValueError:
1323
+ ... return float.fromhex(val)
1324
+ >>> s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2")
1325
+ >>> np.loadtxt(s, delimiter=",", converters=conv)
1326
+ array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00])
1327
+
1328
+ Or a format where the ``-`` sign comes after the number:
1329
+
1330
+ >>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
1331
+ >>> conv = lambda x: -float(x[:-1]) if x.endswith("-") else float(x)
1332
+ >>> np.loadtxt(s, converters=conv)
1333
+ array([[ 10.01, -31.25],
1334
+ [ 19.22, 64.31],
1335
+ [-17.57, 63.94]])
1336
+
1337
+ Support for quoted fields is enabled with the `quotechar` parameter.
1338
+ Comment and delimiter characters are ignored when they appear within a
1339
+ quoted item delineated by `quotechar`:
1340
+
1341
+ >>> s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n')
1342
+ >>> dtype = np.dtype([("label", "U12"), ("value", float)])
1343
+ >>> np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"')
1344
+ array([('alpha, #42', 10.), ('beta, #64', 2.)],
1345
+ dtype=[('label', '<U12'), ('value', '<f8')])
1346
+
1347
+ Quoted fields can be separated by multiple whitespace characters:
1348
+
1349
+ >>> s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n')
1350
+ >>> dtype = np.dtype([("label", "U12"), ("value", float)])
1351
+ >>> np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"')
1352
+ array([('alpha, #42', 10.), ('beta, #64', 2.)],
1353
+ dtype=[('label', '<U12'), ('value', '<f8')])
1354
+
1355
+ Two consecutive quote characters within a quoted field are treated as a
1356
+ single escaped character:
1357
+
1358
+ >>> s = StringIO('"Hello, my name is ""Monty""!"')
1359
+ >>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"')
1360
+ array('Hello, my name is "Monty"!', dtype='<U26')
1361
+
1362
+ Read subset of columns when all rows do not contain equal number of values:
1363
+
1364
+ >>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20")
1365
+ >>> np.loadtxt(d, usecols=(0, 1))
1366
+ array([[ 1., 2.],
1367
+ [ 2., 4.],
1368
+ [ 3., 9.],
1369
+ [ 4., 16.]])
1370
+
1371
+ """
1372
+
1373
+ if like is not None:
1374
+ return _loadtxt_with_like(
1375
+ like, fname, dtype=dtype, comments=comments, delimiter=delimiter,
1376
+ converters=converters, skiprows=skiprows, usecols=usecols,
1377
+ unpack=unpack, ndmin=ndmin, encoding=encoding,
1378
+ max_rows=max_rows
1379
+ )
1380
+
1381
+ if isinstance(delimiter, bytes):
1382
+ delimiter.decode("latin1")
1383
+
1384
+ if dtype is None:
1385
+ dtype = np.float64
1386
+
1387
+ comment = comments
1388
+ # Control character type conversions for Py3 convenience
1389
+ if comment is not None:
1390
+ if isinstance(comment, (str, bytes)):
1391
+ comment = [comment]
1392
+ comment = [
1393
+ x.decode('latin1') if isinstance(x, bytes) else x for x in comment]
1394
+ if isinstance(delimiter, bytes):
1395
+ delimiter = delimiter.decode('latin1')
1396
+
1397
+ arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter,
1398
+ converters=converters, skiplines=skiprows, usecols=usecols,
1399
+ unpack=unpack, ndmin=ndmin, encoding=encoding,
1400
+ max_rows=max_rows, quote=quotechar)
1401
+
1402
+ return arr
1403
+
1404
+
1405
+ _loadtxt_with_like = array_function_dispatch()(loadtxt)
1406
+
1407
+
1408
+ def _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None,
1409
+ header=None, footer=None, comments=None,
1410
+ encoding=None):
1411
+ return (X,)
1412
+
1413
+
1414
+ @array_function_dispatch(_savetxt_dispatcher)
1415
+ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
1416
+ footer='', comments='# ', encoding=None):
1417
+ """
1418
+ Save an array to a text file.
1419
+
1420
+ Parameters
1421
+ ----------
1422
+ fname : filename, file handle or pathlib.Path
1423
+ If the filename ends in ``.gz``, the file is automatically saved in
1424
+ compressed gzip format. `loadtxt` understands gzipped files
1425
+ transparently.
1426
+ X : 1D or 2D array_like
1427
+ Data to be saved to a text file.
1428
+ fmt : str or sequence of strs, optional
1429
+ A single format (%10.5f), a sequence of formats, or a
1430
+ multi-format string, e.g. 'Iteration %d -- %10.5f', in which
1431
+ case `delimiter` is ignored. For complex `X`, the legal options
1432
+ for `fmt` are:
1433
+
1434
+ * a single specifier, ``fmt='%.4e'``, resulting in numbers formatted
1435
+ like ``' (%s+%sj)' % (fmt, fmt)``
1436
+ * a full string specifying every real and imaginary part, e.g.
1437
+ ``' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'`` for 3 columns
1438
+ * a list of specifiers, one per column - in this case, the real
1439
+ and imaginary part must have separate specifiers,
1440
+ e.g. ``['%.3e + %.3ej', '(%.15e%+.15ej)']`` for 2 columns
1441
+ delimiter : str, optional
1442
+ String or character separating columns.
1443
+ newline : str, optional
1444
+ String or character separating lines.
1445
+ header : str, optional
1446
+ String that will be written at the beginning of the file.
1447
+ footer : str, optional
1448
+ String that will be written at the end of the file.
1449
+ comments : str, optional
1450
+ String that will be prepended to the ``header`` and ``footer`` strings,
1451
+ to mark them as comments. Default: '# ', as expected by e.g.
1452
+ ``numpy.loadtxt``.
1453
+ encoding : {None, str}, optional
1454
+ Encoding used to encode the outputfile. Does not apply to output
1455
+ streams. If the encoding is something other than 'bytes' or 'latin1'
1456
+ you will not be able to load the file in NumPy versions < 1.14. Default
1457
+ is 'latin1'.
1458
+
1459
+ See Also
1460
+ --------
1461
+ save : Save an array to a binary file in NumPy ``.npy`` format
1462
+ savez : Save several arrays into an uncompressed ``.npz`` archive
1463
+ savez_compressed : Save several arrays into a compressed ``.npz`` archive
1464
+
1465
+ Notes
1466
+ -----
1467
+ Further explanation of the `fmt` parameter
1468
+ (``%[flag]width[.precision]specifier``):
1469
+
1470
+ flags:
1471
+ ``-`` : left justify
1472
+
1473
+ ``+`` : Forces to precede result with + or -.
1474
+
1475
+ ``0`` : Left pad the number with zeros instead of space (see width).
1476
+
1477
+ width:
1478
+ Minimum number of characters to be printed. The value is not truncated
1479
+ if it has more characters.
1480
+
1481
+ precision:
1482
+ - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
1483
+ digits.
1484
+ - For ``e, E`` and ``f`` specifiers, the number of digits to print
1485
+ after the decimal point.
1486
+ - For ``g`` and ``G``, the maximum number of significant digits.
1487
+ - For ``s``, the maximum number of characters.
1488
+
1489
+ specifiers:
1490
+ ``c`` : character
1491
+
1492
+ ``d`` or ``i`` : signed decimal integer
1493
+
1494
+ ``e`` or ``E`` : scientific notation with ``e`` or ``E``.
1495
+
1496
+ ``f`` : decimal floating point
1497
+
1498
+ ``g,G`` : use the shorter of ``e,E`` or ``f``
1499
+
1500
+ ``o`` : signed octal
1501
+
1502
+ ``s`` : string of characters
1503
+
1504
+ ``u`` : unsigned decimal integer
1505
+
1506
+ ``x,X`` : unsigned hexadecimal integer
1507
+
1508
+ This explanation of ``fmt`` is not complete, for an exhaustive
1509
+ specification see [1]_.
1510
+
1511
+ References
1512
+ ----------
1513
+ .. [1] `Format Specification Mini-Language
1514
+ <https://docs.python.org/library/string.html#format-specification-mini-language>`_,
1515
+ Python Documentation.
1516
+
1517
+ Examples
1518
+ --------
1519
+ >>> import numpy as np
1520
+ >>> x = y = z = np.arange(0.0,5.0,1.0)
1521
+ >>> np.savetxt('test.out', x, delimiter=',') # X is an array
1522
+ >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays
1523
+ >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
1524
+
1525
+ """
1526
+
1527
+ class WriteWrap:
1528
+ """Convert to bytes on bytestream inputs.
1529
+
1530
+ """
1531
+ def __init__(self, fh, encoding):
1532
+ self.fh = fh
1533
+ self.encoding = encoding
1534
+ self.do_write = self.first_write
1535
+
1536
+ def close(self):
1537
+ self.fh.close()
1538
+
1539
+ def write(self, v):
1540
+ self.do_write(v)
1541
+
1542
+ def write_bytes(self, v):
1543
+ if isinstance(v, bytes):
1544
+ self.fh.write(v)
1545
+ else:
1546
+ self.fh.write(v.encode(self.encoding))
1547
+
1548
+ def write_normal(self, v):
1549
+ self.fh.write(asunicode(v))
1550
+
1551
+ def first_write(self, v):
1552
+ try:
1553
+ self.write_normal(v)
1554
+ self.write = self.write_normal
1555
+ except TypeError:
1556
+ # input is probably a bytestream
1557
+ self.write_bytes(v)
1558
+ self.write = self.write_bytes
1559
+
1560
+ own_fh = False
1561
+ if isinstance(fname, os.PathLike):
1562
+ fname = os.fspath(fname)
1563
+ if _is_string_like(fname):
1564
+ # datasource doesn't support creating a new file ...
1565
+ open(fname, 'wt').close()
1566
+ fh = np.lib._datasource.open(fname, 'wt', encoding=encoding)
1567
+ own_fh = True
1568
+ elif hasattr(fname, 'write'):
1569
+ # wrap to handle byte output streams
1570
+ fh = WriteWrap(fname, encoding or 'latin1')
1571
+ else:
1572
+ raise ValueError('fname must be a string or file handle')
1573
+
1574
+ try:
1575
+ X = np.asarray(X)
1576
+
1577
+ # Handle 1-dimensional arrays
1578
+ if X.ndim == 0 or X.ndim > 2:
1579
+ raise ValueError(
1580
+ "Expected 1D or 2D array, got %dD array instead" % X.ndim)
1581
+ elif X.ndim == 1:
1582
+ # Common case -- 1d array of numbers
1583
+ if X.dtype.names is None:
1584
+ X = np.atleast_2d(X).T
1585
+ ncol = 1
1586
+
1587
+ # Complex dtype -- each field indicates a separate column
1588
+ else:
1589
+ ncol = len(X.dtype.names)
1590
+ else:
1591
+ ncol = X.shape[1]
1592
+
1593
+ iscomplex_X = np.iscomplexobj(X)
1594
+ # `fmt` can be a string with multiple insertion points or a
1595
+ # list of formats. E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')
1596
+ if type(fmt) in (list, tuple):
1597
+ if len(fmt) != ncol:
1598
+ raise AttributeError(f'fmt has wrong shape. {str(fmt)}')
1599
+ format = delimiter.join(fmt)
1600
+ elif isinstance(fmt, str):
1601
+ n_fmt_chars = fmt.count('%')
1602
+ error = ValueError(f'fmt has wrong number of % formats: {fmt}')
1603
+ if n_fmt_chars == 1:
1604
+ if iscomplex_X:
1605
+ fmt = [f' ({fmt}+{fmt}j)', ] * ncol
1606
+ else:
1607
+ fmt = [fmt, ] * ncol
1608
+ format = delimiter.join(fmt)
1609
+ elif iscomplex_X and n_fmt_chars != (2 * ncol):
1610
+ raise error
1611
+ elif ((not iscomplex_X) and n_fmt_chars != ncol):
1612
+ raise error
1613
+ else:
1614
+ format = fmt
1615
+ else:
1616
+ raise ValueError(f'invalid fmt: {fmt!r}')
1617
+
1618
+ if len(header) > 0:
1619
+ header = header.replace('\n', '\n' + comments)
1620
+ fh.write(comments + header + newline)
1621
+ if iscomplex_X:
1622
+ for row in X:
1623
+ row2 = []
1624
+ for number in row:
1625
+ row2.extend((number.real, number.imag))
1626
+ s = format % tuple(row2) + newline
1627
+ fh.write(s.replace('+-', '-'))
1628
+ else:
1629
+ for row in X:
1630
+ try:
1631
+ v = format % tuple(row) + newline
1632
+ except TypeError as e:
1633
+ raise TypeError("Mismatch between array dtype ('%s') and "
1634
+ "format specifier ('%s')"
1635
+ % (str(X.dtype), format)) from e
1636
+ fh.write(v)
1637
+
1638
+ if len(footer) > 0:
1639
+ footer = footer.replace('\n', '\n' + comments)
1640
+ fh.write(comments + footer + newline)
1641
+ finally:
1642
+ if own_fh:
1643
+ fh.close()
1644
+
1645
+
1646
+ @set_module('numpy')
1647
+ def fromregex(file, regexp, dtype, encoding=None):
1648
+ r"""
1649
+ Construct an array from a text file, using regular expression parsing.
1650
+
1651
+ The returned array is always a structured array, and is constructed from
1652
+ all matches of the regular expression in the file. Groups in the regular
1653
+ expression are converted to fields of the structured array.
1654
+
1655
+ Parameters
1656
+ ----------
1657
+ file : file, str, or pathlib.Path
1658
+ Filename or file object to read.
1659
+
1660
+ .. versionchanged:: 1.22.0
1661
+ Now accepts `os.PathLike` implementations.
1662
+
1663
+ regexp : str or regexp
1664
+ Regular expression used to parse the file.
1665
+ Groups in the regular expression correspond to fields in the dtype.
1666
+ dtype : dtype or list of dtypes
1667
+ Dtype for the structured array; must be a structured datatype.
1668
+ encoding : str, optional
1669
+ Encoding used to decode the inputfile. Does not apply to input streams.
1670
+
1671
+ Returns
1672
+ -------
1673
+ output : ndarray
1674
+ The output array, containing the part of the content of `file` that
1675
+ was matched by `regexp`. `output` is always a structured array.
1676
+
1677
+ Raises
1678
+ ------
1679
+ TypeError
1680
+ When `dtype` is not a valid dtype for a structured array.
1681
+
1682
+ See Also
1683
+ --------
1684
+ fromstring, loadtxt
1685
+
1686
+ Notes
1687
+ -----
1688
+ Dtypes for structured arrays can be specified in several forms, but all
1689
+ forms specify at least the data type and field name. For details see
1690
+ `basics.rec`.
1691
+
1692
+ Examples
1693
+ --------
1694
+ >>> import numpy as np
1695
+ >>> from io import StringIO
1696
+ >>> text = StringIO("1312 foo\n1534 bar\n444 qux")
1697
+
1698
+ >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything]
1699
+ >>> output = np.fromregex(text, regexp,
1700
+ ... [('num', np.int64), ('key', 'S3')])
1701
+ >>> output
1702
+ array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
1703
+ dtype=[('num', '<i8'), ('key', 'S3')])
1704
+ >>> output['num']
1705
+ array([1312, 1534, 444])
1706
+
1707
+ """
1708
+ own_fh = False
1709
+ if not hasattr(file, "read"):
1710
+ file = os.fspath(file)
1711
+ file = np.lib._datasource.open(file, 'rt', encoding=encoding)
1712
+ own_fh = True
1713
+
1714
+ try:
1715
+ if not isinstance(dtype, np.dtype):
1716
+ dtype = np.dtype(dtype)
1717
+ if dtype.names is None:
1718
+ raise TypeError('dtype must be a structured datatype.')
1719
+
1720
+ content = file.read()
1721
+ if isinstance(content, bytes) and isinstance(regexp, str):
1722
+ regexp = asbytes(regexp)
1723
+
1724
+ if not hasattr(regexp, 'match'):
1725
+ regexp = re.compile(regexp)
1726
+ seq = regexp.findall(content)
1727
+ if seq and not isinstance(seq[0], tuple):
1728
+ # Only one group is in the regexp.
1729
+ # Create the new array as a single data-type and then
1730
+ # re-interpret as a single-field structured array.
1731
+ newdtype = np.dtype(dtype[dtype.names[0]])
1732
+ output = np.array(seq, dtype=newdtype)
1733
+ output.dtype = dtype
1734
+ else:
1735
+ output = np.array(seq, dtype=dtype)
1736
+
1737
+ return output
1738
+ finally:
1739
+ if own_fh:
1740
+ file.close()
1741
+
1742
+
1743
+ #####--------------------------------------------------------------------------
1744
+ #---- --- ASCII functions ---
1745
+ #####--------------------------------------------------------------------------
1746
+
1747
+
1748
+ @finalize_array_function_like
1749
+ @set_module('numpy')
1750
+ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
1751
+ skip_header=0, skip_footer=0, converters=None,
1752
+ missing_values=None, filling_values=None, usecols=None,
1753
+ names=None, excludelist=None,
1754
+ deletechars=''.join(sorted(NameValidator.defaultdeletechars)), # noqa: B008
1755
+ replace_space='_', autostrip=False, case_sensitive=True,
1756
+ defaultfmt="f%i", unpack=None, usemask=False, loose=True,
1757
+ invalid_raise=True, max_rows=None, encoding=None,
1758
+ *, ndmin=0, like=None):
1759
+ """
1760
+ Load data from a text file, with missing values handled as specified.
1761
+
1762
+ Each line past the first `skip_header` lines is split at the `delimiter`
1763
+ character, and characters following the `comments` character are discarded.
1764
+
1765
+ Parameters
1766
+ ----------
1767
+ fname : file, str, pathlib.Path, list of str, generator
1768
+ File, filename, list, or generator to read. If the filename
1769
+ extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
1770
+ that generators must return bytes or strings. The strings
1771
+ in a list or produced by a generator are treated as lines.
1772
+ dtype : dtype, optional
1773
+ Data type of the resulting array.
1774
+ If None, the dtypes will be determined by the contents of each
1775
+ column, individually.
1776
+ comments : str, optional
1777
+ The character used to indicate the start of a comment.
1778
+ All the characters occurring on a line after a comment are discarded.
1779
+ delimiter : str, int, or sequence, optional
1780
+ The string used to separate values. By default, any consecutive
1781
+ whitespaces act as delimiter. An integer or sequence of integers
1782
+ can also be provided as width(s) of each field.
1783
+ skiprows : int, optional
1784
+ `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
1785
+ skip_header : int, optional
1786
+ The number of lines to skip at the beginning of the file.
1787
+ skip_footer : int, optional
1788
+ The number of lines to skip at the end of the file.
1789
+ converters : variable, optional
1790
+ The set of functions that convert the data of a column to a value.
1791
+ The converters can also be used to provide a default value
1792
+ for missing data: ``converters = {3: lambda s: float(s or 0)}``.
1793
+ missing : variable, optional
1794
+ `missing` was removed in numpy 1.10. Please use `missing_values`
1795
+ instead.
1796
+ missing_values : variable, optional
1797
+ The set of strings corresponding to missing data.
1798
+ filling_values : variable, optional
1799
+ The set of values to be used as default when the data are missing.
1800
+ usecols : sequence, optional
1801
+ Which columns to read, with 0 being the first. For example,
1802
+ ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
1803
+ names : {None, True, str, sequence}, optional
1804
+ If `names` is True, the field names are read from the first line after
1805
+ the first `skip_header` lines. This line can optionally be preceded
1806
+ by a comment delimiter. Any content before the comment delimiter is
1807
+ discarded. If `names` is a sequence or a single-string of
1808
+ comma-separated names, the names will be used to define the field
1809
+ names in a structured dtype. If `names` is None, the names of the
1810
+ dtype fields will be used, if any.
1811
+ excludelist : sequence, optional
1812
+ A list of names to exclude. This list is appended to the default list
1813
+ ['return','file','print']. Excluded names are appended with an
1814
+ underscore: for example, `file` would become `file_`.
1815
+ deletechars : str, optional
1816
+ A string combining invalid characters that must be deleted from the
1817
+ names.
1818
+ defaultfmt : str, optional
1819
+ A format used to define default field names, such as "f%i" or "f_%02i".
1820
+ autostrip : bool, optional
1821
+ Whether to automatically strip white spaces from the variables.
1822
+ replace_space : char, optional
1823
+ Character(s) used in replacement of white spaces in the variable
1824
+ names. By default, use a '_'.
1825
+ case_sensitive : {True, False, 'upper', 'lower'}, optional
1826
+ If True, field names are case sensitive.
1827
+ If False or 'upper', field names are converted to upper case.
1828
+ If 'lower', field names are converted to lower case.
1829
+ unpack : bool, optional
1830
+ If True, the returned array is transposed, so that arguments may be
1831
+ unpacked using ``x, y, z = genfromtxt(...)``. When used with a
1832
+ structured data-type, arrays are returned for each field.
1833
+ Default is False.
1834
+ usemask : bool, optional
1835
+ If True, return a masked array.
1836
+ If False, return a regular array.
1837
+ loose : bool, optional
1838
+ If True, do not raise errors for invalid values.
1839
+ invalid_raise : bool, optional
1840
+ If True, an exception is raised if an inconsistency is detected in the
1841
+ number of columns.
1842
+ If False, a warning is emitted and the offending lines are skipped.
1843
+ max_rows : int, optional
1844
+ The maximum number of rows to read. Must not be used with skip_footer
1845
+ at the same time. If given, the value must be at least 1. Default is
1846
+ to read the entire file.
1847
+ encoding : str, optional
1848
+ Encoding used to decode the inputfile. Does not apply when `fname`
1849
+ is a file object. The special value 'bytes' enables backward
1850
+ compatibility workarounds that ensure that you receive byte arrays
1851
+ when possible and passes latin1 encoded strings to converters.
1852
+ Override this value to receive unicode arrays and pass strings
1853
+ as input to converters. If set to None the system default is used.
1854
+ The default value is 'bytes'.
1855
+
1856
+ .. versionchanged:: 2.0
1857
+ Before NumPy 2, the default was ``'bytes'`` for Python 2
1858
+ compatibility. The default is now ``None``.
1859
+
1860
+ ndmin : int, optional
1861
+ Same parameter as `loadtxt`
1862
+
1863
+ .. versionadded:: 1.23.0
1864
+ ${ARRAY_FUNCTION_LIKE}
1865
+
1866
+ .. versionadded:: 1.20.0
1867
+
1868
+ Returns
1869
+ -------
1870
+ out : ndarray
1871
+ Data read from the text file. If `usemask` is True, this is a
1872
+ masked array.
1873
+
1874
+ See Also
1875
+ --------
1876
+ numpy.loadtxt : equivalent function when no data is missing.
1877
+
1878
+ Notes
1879
+ -----
1880
+ * When spaces are used as delimiters, or when no delimiter has been given
1881
+ as input, there should not be any missing data between two fields.
1882
+ * When variables are named (either by a flexible dtype or with a `names`
1883
+ sequence), there must not be any header in the file (else a ValueError
1884
+ exception is raised).
1885
+ * Individual values are not stripped of spaces by default.
1886
+ When using a custom converter, make sure the function does remove spaces.
1887
+ * Custom converters may receive unexpected values due to dtype
1888
+ discovery.
1889
+
1890
+ References
1891
+ ----------
1892
+ .. [1] NumPy User Guide, section `I/O with NumPy
1893
+ <https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
1894
+
1895
+ Examples
1896
+ --------
1897
+ >>> from io import StringIO
1898
+ >>> import numpy as np
1899
+
1900
+ Comma delimited file with mixed dtype
1901
+
1902
+ >>> s = StringIO("1,1.3,abcde")
1903
+ >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
1904
+ ... ('mystring','S5')], delimiter=",")
1905
+ >>> data
1906
+ array((1, 1.3, b'abcde'),
1907
+ dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
1908
+
1909
+ Using dtype = None
1910
+
1911
+ >>> _ = s.seek(0) # needed for StringIO example only
1912
+ >>> data = np.genfromtxt(s, dtype=None,
1913
+ ... names = ['myint','myfloat','mystring'], delimiter=",")
1914
+ >>> data
1915
+ array((1, 1.3, 'abcde'),
1916
+ dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '<U5')])
1917
+
1918
+ Specifying dtype and names
1919
+
1920
+ >>> _ = s.seek(0)
1921
+ >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
1922
+ ... names=['myint','myfloat','mystring'], delimiter=",")
1923
+ >>> data
1924
+ array((1, 1.3, b'abcde'),
1925
+ dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
1926
+
1927
+ An example with fixed-width columns
1928
+
1929
+ >>> s = StringIO("11.3abcde")
1930
+ >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
1931
+ ... delimiter=[1,3,5])
1932
+ >>> data
1933
+ array((1, 1.3, 'abcde'),
1934
+ dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '<U5')])
1935
+
1936
+ An example to show comments
1937
+
1938
+ >>> f = StringIO('''
1939
+ ... text,# of chars
1940
+ ... hello world,11
1941
+ ... numpy,5''')
1942
+ >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
1943
+ array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
1944
+ dtype=[('f0', 'S12'), ('f1', 'S12')])
1945
+
1946
+ """
1947
+
1948
+ if like is not None:
1949
+ return _genfromtxt_with_like(
1950
+ like, fname, dtype=dtype, comments=comments, delimiter=delimiter,
1951
+ skip_header=skip_header, skip_footer=skip_footer,
1952
+ converters=converters, missing_values=missing_values,
1953
+ filling_values=filling_values, usecols=usecols, names=names,
1954
+ excludelist=excludelist, deletechars=deletechars,
1955
+ replace_space=replace_space, autostrip=autostrip,
1956
+ case_sensitive=case_sensitive, defaultfmt=defaultfmt,
1957
+ unpack=unpack, usemask=usemask, loose=loose,
1958
+ invalid_raise=invalid_raise, max_rows=max_rows, encoding=encoding,
1959
+ ndmin=ndmin,
1960
+ )
1961
+
1962
+ _ensure_ndmin_ndarray_check_param(ndmin)
1963
+
1964
+ if max_rows is not None:
1965
+ if skip_footer:
1966
+ raise ValueError(
1967
+ "The keywords 'skip_footer' and 'max_rows' can not be "
1968
+ "specified at the same time.")
1969
+ if max_rows < 1:
1970
+ raise ValueError("'max_rows' must be at least 1.")
1971
+
1972
+ if usemask:
1973
+ from numpy.ma import MaskedArray, make_mask_descr
1974
+ # Check the input dictionary of converters
1975
+ user_converters = converters or {}
1976
+ if not isinstance(user_converters, dict):
1977
+ raise TypeError(
1978
+ "The input argument 'converter' should be a valid dictionary "
1979
+ "(got '%s' instead)" % type(user_converters))
1980
+
1981
+ if encoding == 'bytes':
1982
+ encoding = None
1983
+ byte_converters = True
1984
+ else:
1985
+ byte_converters = False
1986
+
1987
+ # Initialize the filehandle, the LineSplitter and the NameValidator
1988
+ if isinstance(fname, os.PathLike):
1989
+ fname = os.fspath(fname)
1990
+ if isinstance(fname, str):
1991
+ fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
1992
+ fid_ctx = contextlib.closing(fid)
1993
+ else:
1994
+ fid = fname
1995
+ fid_ctx = contextlib.nullcontext(fid)
1996
+ try:
1997
+ fhd = iter(fid)
1998
+ except TypeError as e:
1999
+ raise TypeError(
2000
+ "fname must be a string, a filehandle, a sequence of strings,\n"
2001
+ f"or an iterator of strings. Got {type(fname)} instead."
2002
+ ) from e
2003
+ with fid_ctx:
2004
+ split_line = LineSplitter(delimiter=delimiter, comments=comments,
2005
+ autostrip=autostrip, encoding=encoding)
2006
+ validate_names = NameValidator(excludelist=excludelist,
2007
+ deletechars=deletechars,
2008
+ case_sensitive=case_sensitive,
2009
+ replace_space=replace_space)
2010
+
2011
+ # Skip the first `skip_header` rows
2012
+ try:
2013
+ for i in range(skip_header):
2014
+ next(fhd)
2015
+
2016
+ # Keep on until we find the first valid values
2017
+ first_values = None
2018
+
2019
+ while not first_values:
2020
+ first_line = _decode_line(next(fhd), encoding)
2021
+ if (names is True) and (comments is not None):
2022
+ if comments in first_line:
2023
+ first_line = (
2024
+ ''.join(first_line.split(comments)[1:]))
2025
+ first_values = split_line(first_line)
2026
+ except StopIteration:
2027
+ # return an empty array if the datafile is empty
2028
+ first_line = ''
2029
+ first_values = []
2030
+ warnings.warn(
2031
+ f'genfromtxt: Empty input file: "{fname}"', stacklevel=2
2032
+ )
2033
+
2034
+ # Should we take the first values as names ?
2035
+ if names is True:
2036
+ fval = first_values[0].strip()
2037
+ if comments is not None:
2038
+ if fval in comments:
2039
+ del first_values[0]
2040
+
2041
+ # Check the columns to use: make sure `usecols` is a list
2042
+ if usecols is not None:
2043
+ try:
2044
+ usecols = [_.strip() for _ in usecols.split(",")]
2045
+ except AttributeError:
2046
+ try:
2047
+ usecols = list(usecols)
2048
+ except TypeError:
2049
+ usecols = [usecols, ]
2050
+ nbcols = len(usecols or first_values)
2051
+
2052
+ # Check the names and overwrite the dtype.names if needed
2053
+ if names is True:
2054
+ names = validate_names([str(_.strip()) for _ in first_values])
2055
+ first_line = ''
2056
+ elif _is_string_like(names):
2057
+ names = validate_names([_.strip() for _ in names.split(',')])
2058
+ elif names:
2059
+ names = validate_names(names)
2060
+ # Get the dtype
2061
+ if dtype is not None:
2062
+ dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names,
2063
+ excludelist=excludelist,
2064
+ deletechars=deletechars,
2065
+ case_sensitive=case_sensitive,
2066
+ replace_space=replace_space)
2067
+ # Make sure the names is a list (for 2.5)
2068
+ if names is not None:
2069
+ names = list(names)
2070
+
2071
+ if usecols:
2072
+ for (i, current) in enumerate(usecols):
2073
+ # if usecols is a list of names, convert to a list of indices
2074
+ if _is_string_like(current):
2075
+ usecols[i] = names.index(current)
2076
+ elif current < 0:
2077
+ usecols[i] = current + len(first_values)
2078
+ # If the dtype is not None, make sure we update it
2079
+ if (dtype is not None) and (len(dtype) > nbcols):
2080
+ descr = dtype.descr
2081
+ dtype = np.dtype([descr[_] for _ in usecols])
2082
+ names = list(dtype.names)
2083
+ # If `names` is not None, update the names
2084
+ elif (names is not None) and (len(names) > nbcols):
2085
+ names = [names[_] for _ in usecols]
2086
+ elif (names is not None) and (dtype is not None):
2087
+ names = list(dtype.names)
2088
+
2089
+ # Process the missing values ...............................
2090
+ # Rename missing_values for convenience
2091
+ user_missing_values = missing_values or ()
2092
+ if isinstance(user_missing_values, bytes):
2093
+ user_missing_values = user_missing_values.decode('latin1')
2094
+
2095
+ # Define the list of missing_values (one column: one list)
2096
+ missing_values = [[''] for _ in range(nbcols)]
2097
+
2098
+ # We have a dictionary: process it field by field
2099
+ if isinstance(user_missing_values, dict):
2100
+ # Loop on the items
2101
+ for (key, val) in user_missing_values.items():
2102
+ # Is the key a string ?
2103
+ if _is_string_like(key):
2104
+ try:
2105
+ # Transform it into an integer
2106
+ key = names.index(key)
2107
+ except ValueError:
2108
+ # We couldn't find it: the name must have been dropped
2109
+ continue
2110
+ # Redefine the key as needed if it's a column number
2111
+ if usecols:
2112
+ try:
2113
+ key = usecols.index(key)
2114
+ except ValueError:
2115
+ pass
2116
+ # Transform the value as a list of string
2117
+ if isinstance(val, (list, tuple)):
2118
+ val = [str(_) for _ in val]
2119
+ else:
2120
+ val = [str(val), ]
2121
+ # Add the value(s) to the current list of missing
2122
+ if key is None:
2123
+ # None acts as default
2124
+ for miss in missing_values:
2125
+ miss.extend(val)
2126
+ else:
2127
+ missing_values[key].extend(val)
2128
+ # We have a sequence : each item matches a column
2129
+ elif isinstance(user_missing_values, (list, tuple)):
2130
+ for (value, entry) in zip(user_missing_values, missing_values):
2131
+ value = str(value)
2132
+ if value not in entry:
2133
+ entry.append(value)
2134
+ # We have a string : apply it to all entries
2135
+ elif isinstance(user_missing_values, str):
2136
+ user_value = user_missing_values.split(",")
2137
+ for entry in missing_values:
2138
+ entry.extend(user_value)
2139
+ # We have something else: apply it to all entries
2140
+ else:
2141
+ for entry in missing_values:
2142
+ entry.extend([str(user_missing_values)])
2143
+
2144
+ # Process the filling_values ...............................
2145
+ # Rename the input for convenience
2146
+ user_filling_values = filling_values
2147
+ if user_filling_values is None:
2148
+ user_filling_values = []
2149
+ # Define the default
2150
+ filling_values = [None] * nbcols
2151
+ # We have a dictionary : update each entry individually
2152
+ if isinstance(user_filling_values, dict):
2153
+ for (key, val) in user_filling_values.items():
2154
+ if _is_string_like(key):
2155
+ try:
2156
+ # Transform it into an integer
2157
+ key = names.index(key)
2158
+ except ValueError:
2159
+ # We couldn't find it: the name must have been dropped
2160
+ continue
2161
+ # Redefine the key if it's a column number
2162
+ # and usecols is defined
2163
+ if usecols:
2164
+ try:
2165
+ key = usecols.index(key)
2166
+ except ValueError:
2167
+ pass
2168
+ # Add the value to the list
2169
+ filling_values[key] = val
2170
+ # We have a sequence : update on a one-to-one basis
2171
+ elif isinstance(user_filling_values, (list, tuple)):
2172
+ n = len(user_filling_values)
2173
+ if (n <= nbcols):
2174
+ filling_values[:n] = user_filling_values
2175
+ else:
2176
+ filling_values = user_filling_values[:nbcols]
2177
+ # We have something else : use it for all entries
2178
+ else:
2179
+ filling_values = [user_filling_values] * nbcols
2180
+
2181
+ # Initialize the converters ................................
2182
+ if dtype is None:
2183
+ # Note: we can't use a [...]*nbcols, as we would have 3 times
2184
+ # the same converter, instead of 3 different converters.
2185
+ converters = [
2186
+ StringConverter(None, missing_values=miss, default=fill)
2187
+ for (miss, fill) in zip(missing_values, filling_values)
2188
+ ]
2189
+ else:
2190
+ dtype_flat = flatten_dtype(dtype, flatten_base=True)
2191
+ # Initialize the converters
2192
+ if len(dtype_flat) > 1:
2193
+ # Flexible type : get a converter from each dtype
2194
+ zipit = zip(dtype_flat, missing_values, filling_values)
2195
+ converters = [StringConverter(dt,
2196
+ locked=True,
2197
+ missing_values=miss,
2198
+ default=fill)
2199
+ for (dt, miss, fill) in zipit]
2200
+ else:
2201
+ # Set to a default converter (but w/ different missing values)
2202
+ zipit = zip(missing_values, filling_values)
2203
+ converters = [StringConverter(dtype,
2204
+ locked=True,
2205
+ missing_values=miss,
2206
+ default=fill)
2207
+ for (miss, fill) in zipit]
2208
+ # Update the converters to use the user-defined ones
2209
+ uc_update = []
2210
+ for (j, conv) in user_converters.items():
2211
+ # If the converter is specified by column names,
2212
+ # use the index instead
2213
+ if _is_string_like(j):
2214
+ try:
2215
+ j = names.index(j)
2216
+ i = j
2217
+ except ValueError:
2218
+ continue
2219
+ elif usecols:
2220
+ try:
2221
+ i = usecols.index(j)
2222
+ except ValueError:
2223
+ # Unused converter specified
2224
+ continue
2225
+ else:
2226
+ i = j
2227
+ # Find the value to test - first_line is not filtered by usecols:
2228
+ if len(first_line):
2229
+ testing_value = first_values[j]
2230
+ else:
2231
+ testing_value = None
2232
+ if conv is bytes:
2233
+ user_conv = asbytes
2234
+ elif byte_converters:
2235
+ # Converters may use decode to workaround numpy's old
2236
+ # behavior, so encode the string again before passing
2237
+ # to the user converter.
2238
+ def tobytes_first(x, conv):
2239
+ if type(x) is bytes:
2240
+ return conv(x)
2241
+ return conv(x.encode("latin1"))
2242
+ user_conv = functools.partial(tobytes_first, conv=conv)
2243
+ else:
2244
+ user_conv = conv
2245
+ converters[i].update(user_conv, locked=True,
2246
+ testing_value=testing_value,
2247
+ default=filling_values[i],
2248
+ missing_values=missing_values[i],)
2249
+ uc_update.append((i, user_conv))
2250
+ # Make sure we have the corrected keys in user_converters...
2251
+ user_converters.update(uc_update)
2252
+
2253
+ # Fixme: possible error as following variable never used.
2254
+ # miss_chars = [_.missing_values for _ in converters]
2255
+
2256
+ # Initialize the output lists ...
2257
+ # ... rows
2258
+ rows = []
2259
+ append_to_rows = rows.append
2260
+ # ... masks
2261
+ if usemask:
2262
+ masks = []
2263
+ append_to_masks = masks.append
2264
+ # ... invalid
2265
+ invalid = []
2266
+ append_to_invalid = invalid.append
2267
+
2268
+ # Parse each line
2269
+ for (i, line) in enumerate(itertools.chain([first_line, ], fhd)):
2270
+ values = split_line(line)
2271
+ nbvalues = len(values)
2272
+ # Skip an empty line
2273
+ if nbvalues == 0:
2274
+ continue
2275
+ if usecols:
2276
+ # Select only the columns we need
2277
+ try:
2278
+ values = [values[_] for _ in usecols]
2279
+ except IndexError:
2280
+ append_to_invalid((i + skip_header + 1, nbvalues))
2281
+ continue
2282
+ elif nbvalues != nbcols:
2283
+ append_to_invalid((i + skip_header + 1, nbvalues))
2284
+ continue
2285
+ # Store the values
2286
+ append_to_rows(tuple(values))
2287
+ if usemask:
2288
+ append_to_masks(tuple(v.strip() in m
2289
+ for (v, m) in zip(values,
2290
+ missing_values)))
2291
+ if len(rows) == max_rows:
2292
+ break
2293
+
2294
+ # Upgrade the converters (if needed)
2295
+ if dtype is None:
2296
+ for (i, converter) in enumerate(converters):
2297
+ current_column = [itemgetter(i)(_m) for _m in rows]
2298
+ try:
2299
+ converter.iterupgrade(current_column)
2300
+ except ConverterLockError:
2301
+ errmsg = f"Converter #{i} is locked and cannot be upgraded: "
2302
+ current_column = map(itemgetter(i), rows)
2303
+ for (j, value) in enumerate(current_column):
2304
+ try:
2305
+ converter.upgrade(value)
2306
+ except (ConverterError, ValueError):
2307
+ line_number = j + 1 + skip_header
2308
+ errmsg += f"(occurred line #{line_number} for value '{value}')"
2309
+ raise ConverterError(errmsg)
2310
+
2311
+ # Check that we don't have invalid values
2312
+ nbinvalid = len(invalid)
2313
+ if nbinvalid > 0:
2314
+ nbrows = len(rows) + nbinvalid - skip_footer
2315
+ # Construct the error message
2316
+ template = f" Line #%i (got %i columns instead of {nbcols})"
2317
+ if skip_footer > 0:
2318
+ nbinvalid_skipped = len([_ for _ in invalid
2319
+ if _[0] > nbrows + skip_header])
2320
+ invalid = invalid[:nbinvalid - nbinvalid_skipped]
2321
+ skip_footer -= nbinvalid_skipped
2322
+ #
2323
+ # nbrows -= skip_footer
2324
+ # errmsg = [template % (i, nb)
2325
+ # for (i, nb) in invalid if i < nbrows]
2326
+ # else:
2327
+ errmsg = [template % (i, nb)
2328
+ for (i, nb) in invalid]
2329
+ if len(errmsg):
2330
+ errmsg.insert(0, "Some errors were detected !")
2331
+ errmsg = "\n".join(errmsg)
2332
+ # Raise an exception ?
2333
+ if invalid_raise:
2334
+ raise ValueError(errmsg)
2335
+ # Issue a warning ?
2336
+ else:
2337
+ warnings.warn(errmsg, ConversionWarning, stacklevel=2)
2338
+
2339
+ # Strip the last skip_footer data
2340
+ if skip_footer > 0:
2341
+ rows = rows[:-skip_footer]
2342
+ if usemask:
2343
+ masks = masks[:-skip_footer]
2344
+
2345
+ # Convert each value according to the converter:
2346
+ # We want to modify the list in place to avoid creating a new one...
2347
+ if loose:
2348
+ rows = list(
2349
+ zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)]
2350
+ for (i, conv) in enumerate(converters)]))
2351
+ else:
2352
+ rows = list(
2353
+ zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)]
2354
+ for (i, conv) in enumerate(converters)]))
2355
+
2356
+ # Reset the dtype
2357
+ data = rows
2358
+ if dtype is None:
2359
+ # Get the dtypes from the types of the converters
2360
+ column_types = [conv.type for conv in converters]
2361
+ # Find the columns with strings...
2362
+ strcolidx = [i for (i, v) in enumerate(column_types)
2363
+ if v == np.str_]
2364
+
2365
+ if byte_converters and strcolidx:
2366
+ # convert strings back to bytes for backward compatibility
2367
+ warnings.warn(
2368
+ "Reading unicode strings without specifying the encoding "
2369
+ "argument is deprecated. Set the encoding, use None for the "
2370
+ "system default.",
2371
+ np.exceptions.VisibleDeprecationWarning, stacklevel=2)
2372
+
2373
+ def encode_unicode_cols(row_tup):
2374
+ row = list(row_tup)
2375
+ for i in strcolidx:
2376
+ row[i] = row[i].encode('latin1')
2377
+ return tuple(row)
2378
+
2379
+ try:
2380
+ data = [encode_unicode_cols(r) for r in data]
2381
+ except UnicodeEncodeError:
2382
+ pass
2383
+ else:
2384
+ for i in strcolidx:
2385
+ column_types[i] = np.bytes_
2386
+
2387
+ # Update string types to be the right length
2388
+ sized_column_types = column_types.copy()
2389
+ for i, col_type in enumerate(column_types):
2390
+ if np.issubdtype(col_type, np.character):
2391
+ n_chars = max(len(row[i]) for row in data)
2392
+ sized_column_types[i] = (col_type, n_chars)
2393
+
2394
+ if names is None:
2395
+ # If the dtype is uniform (before sizing strings)
2396
+ base = {
2397
+ c_type
2398
+ for c, c_type in zip(converters, column_types)
2399
+ if c._checked}
2400
+ if len(base) == 1:
2401
+ uniform_type, = base
2402
+ (ddtype, mdtype) = (uniform_type, bool)
2403
+ else:
2404
+ ddtype = [(defaultfmt % i, dt)
2405
+ for (i, dt) in enumerate(sized_column_types)]
2406
+ if usemask:
2407
+ mdtype = [(defaultfmt % i, bool)
2408
+ for (i, dt) in enumerate(sized_column_types)]
2409
+ else:
2410
+ ddtype = list(zip(names, sized_column_types))
2411
+ mdtype = list(zip(names, [bool] * len(sized_column_types)))
2412
+ output = np.array(data, dtype=ddtype)
2413
+ if usemask:
2414
+ outputmask = np.array(masks, dtype=mdtype)
2415
+ else:
2416
+ # Overwrite the initial dtype names if needed
2417
+ if names and dtype.names is not None:
2418
+ dtype.names = names
2419
+ # Case 1. We have a structured type
2420
+ if len(dtype_flat) > 1:
2421
+ # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])]
2422
+ # First, create the array using a flattened dtype:
2423
+ # [('a', int), ('b1', int), ('b2', float)]
2424
+ # Then, view the array using the specified dtype.
2425
+ if 'O' in (_.char for _ in dtype_flat):
2426
+ if has_nested_fields(dtype):
2427
+ raise NotImplementedError(
2428
+ "Nested fields involving objects are not supported...")
2429
+ else:
2430
+ output = np.array(data, dtype=dtype)
2431
+ else:
2432
+ rows = np.array(data, dtype=[('', _) for _ in dtype_flat])
2433
+ output = rows.view(dtype)
2434
+ # Now, process the rowmasks the same way
2435
+ if usemask:
2436
+ rowmasks = np.array(
2437
+ masks, dtype=np.dtype([('', bool) for t in dtype_flat]))
2438
+ # Construct the new dtype
2439
+ mdtype = make_mask_descr(dtype)
2440
+ outputmask = rowmasks.view(mdtype)
2441
+ # Case #2. We have a basic dtype
2442
+ else:
2443
+ # We used some user-defined converters
2444
+ if user_converters:
2445
+ ishomogeneous = True
2446
+ descr = []
2447
+ for i, ttype in enumerate([conv.type for conv in converters]):
2448
+ # Keep the dtype of the current converter
2449
+ if i in user_converters:
2450
+ ishomogeneous &= (ttype == dtype.type)
2451
+ if np.issubdtype(ttype, np.character):
2452
+ ttype = (ttype, max(len(row[i]) for row in data))
2453
+ descr.append(('', ttype))
2454
+ else:
2455
+ descr.append(('', dtype))
2456
+ # So we changed the dtype ?
2457
+ if not ishomogeneous:
2458
+ # We have more than one field
2459
+ if len(descr) > 1:
2460
+ dtype = np.dtype(descr)
2461
+ # We have only one field: drop the name if not needed.
2462
+ else:
2463
+ dtype = np.dtype(ttype)
2464
+ #
2465
+ output = np.array(data, dtype)
2466
+ if usemask:
2467
+ if dtype.names is not None:
2468
+ mdtype = [(_, bool) for _ in dtype.names]
2469
+ else:
2470
+ mdtype = bool
2471
+ outputmask = np.array(masks, dtype=mdtype)
2472
+ # Try to take care of the missing data we missed
2473
+ names = output.dtype.names
2474
+ if usemask and names:
2475
+ for (name, conv) in zip(names, converters):
2476
+ missing_values = [conv(_) for _ in conv.missing_values
2477
+ if _ != '']
2478
+ for mval in missing_values:
2479
+ outputmask[name] |= (output[name] == mval)
2480
+ # Construct the final array
2481
+ if usemask:
2482
+ output = output.view(MaskedArray)
2483
+ output._mask = outputmask
2484
+
2485
+ output = _ensure_ndmin_ndarray(output, ndmin=ndmin)
2486
+
2487
+ if unpack:
2488
+ if names is None:
2489
+ return output.T
2490
+ elif len(names) == 1:
2491
+ # squeeze single-name dtypes too
2492
+ return output[names[0]]
2493
+ else:
2494
+ # For structured arrays with multiple fields,
2495
+ # return an array for each field.
2496
+ return [output[field] for field in names]
2497
+ return output
2498
+
2499
+
2500
+ _genfromtxt_with_like = array_function_dispatch()(genfromtxt)
2501
+
2502
+
2503
+ def recfromtxt(fname, **kwargs):
2504
+ """
2505
+ Load ASCII data from a file and return it in a record array.
2506
+
2507
+ If ``usemask=False`` a standard `recarray` is returned,
2508
+ if ``usemask=True`` a MaskedRecords array is returned.
2509
+
2510
+ .. deprecated:: 2.0
2511
+ Use `numpy.genfromtxt` instead.
2512
+
2513
+ Parameters
2514
+ ----------
2515
+ fname, kwargs : For a description of input parameters, see `genfromtxt`.
2516
+
2517
+ See Also
2518
+ --------
2519
+ numpy.genfromtxt : generic function
2520
+
2521
+ Notes
2522
+ -----
2523
+ By default, `dtype` is None, which means that the data-type of the output
2524
+ array will be determined from the data.
2525
+
2526
+ """
2527
+
2528
+ # Deprecated in NumPy 2.0, 2023-07-11
2529
+ warnings.warn(
2530
+ "`recfromtxt` is deprecated, "
2531
+ "use `numpy.genfromtxt` instead."
2532
+ "(deprecated in NumPy 2.0)",
2533
+ DeprecationWarning,
2534
+ stacklevel=2
2535
+ )
2536
+
2537
+ kwargs.setdefault("dtype", None)
2538
+ usemask = kwargs.get('usemask', False)
2539
+ output = genfromtxt(fname, **kwargs)
2540
+ if usemask:
2541
+ from numpy.ma.mrecords import MaskedRecords
2542
+ output = output.view(MaskedRecords)
2543
+ else:
2544
+ output = output.view(np.recarray)
2545
+ return output
2546
+
2547
+
2548
+ def recfromcsv(fname, **kwargs):
2549
+ """
2550
+ Load ASCII data stored in a comma-separated file.
2551
+
2552
+ The returned array is a record array (if ``usemask=False``, see
2553
+ `recarray`) or a masked record array (if ``usemask=True``,
2554
+ see `ma.mrecords.MaskedRecords`).
2555
+
2556
+ .. deprecated:: 2.0
2557
+ Use `numpy.genfromtxt` with comma as `delimiter` instead.
2558
+
2559
+ Parameters
2560
+ ----------
2561
+ fname, kwargs : For a description of input parameters, see `genfromtxt`.
2562
+
2563
+ See Also
2564
+ --------
2565
+ numpy.genfromtxt : generic function to load ASCII data.
2566
+
2567
+ Notes
2568
+ -----
2569
+ By default, `dtype` is None, which means that the data-type of the output
2570
+ array will be determined from the data.
2571
+
2572
+ """
2573
+
2574
+ # Deprecated in NumPy 2.0, 2023-07-11
2575
+ warnings.warn(
2576
+ "`recfromcsv` is deprecated, "
2577
+ "use `numpy.genfromtxt` with comma as `delimiter` instead. "
2578
+ "(deprecated in NumPy 2.0)",
2579
+ DeprecationWarning,
2580
+ stacklevel=2
2581
+ )
2582
+
2583
+ # Set default kwargs for genfromtxt as relevant to csv import.
2584
+ kwargs.setdefault("case_sensitive", "lower")
2585
+ kwargs.setdefault("names", True)
2586
+ kwargs.setdefault("delimiter", ",")
2587
+ kwargs.setdefault("dtype", None)
2588
+ output = genfromtxt(fname, **kwargs)
2589
+
2590
+ usemask = kwargs.get("usemask", False)
2591
+ if usemask:
2592
+ from numpy.ma.mrecords import MaskedRecords
2593
+ output = output.view(MaskedRecords)
2594
+ else:
2595
+ output = output.view(np.recarray)
2596
+ return output