codekingpro commited on
Commit
555e8c5
·
verified ·
1 Parent(s): 00b5c10

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/user_packages/Python313/site-packages/numpy/_core/__init__.py +203 -0
  2. python/user_packages/Python313/site-packages/numpy/_core/__init__.pyi +666 -0
  3. python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs.py +0 -0
  4. python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs.pyi +2 -0
  5. python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs_scalars.py +381 -0
  6. python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs_scalars.pyi +16 -0
  7. python/user_packages/Python313/site-packages/numpy/_core/_asarray.py +130 -0
  8. python/user_packages/Python313/site-packages/numpy/_core/_asarray.pyi +43 -0
  9. python/user_packages/Python313/site-packages/numpy/_core/_dtype.py +366 -0
  10. python/user_packages/Python313/site-packages/numpy/_core/_dtype.pyi +56 -0
  11. python/user_packages/Python313/site-packages/numpy/_core/_dtype_ctypes.py +120 -0
  12. python/user_packages/Python313/site-packages/numpy/_core/_dtype_ctypes.pyi +83 -0
  13. python/user_packages/Python313/site-packages/numpy/_core/_exceptions.py +162 -0
  14. python/user_packages/Python313/site-packages/numpy/_core/_exceptions.pyi +54 -0
  15. python/user_packages/Python313/site-packages/numpy/_core/_internal.py +968 -0
  16. python/user_packages/Python313/site-packages/numpy/_core/_internal.pyi +61 -0
  17. python/user_packages/Python313/site-packages/numpy/_core/_methods.py +252 -0
  18. python/user_packages/Python313/site-packages/numpy/_core/_methods.pyi +22 -0
  19. python/user_packages/Python313/site-packages/numpy/_core/_multiarray_tests.cp313-win_amd64.lib +0 -0
  20. python/user_packages/Python313/site-packages/numpy/_core/_multiarray_tests.cp313-win_amd64.pyd +0 -0
  21. python/user_packages/Python313/site-packages/numpy/_core/_multiarray_umath.cp313-win_amd64.lib +0 -0
  22. python/user_packages/Python313/site-packages/numpy/_core/_operand_flag_tests.cp313-win_amd64.lib +0 -0
  23. python/user_packages/Python313/site-packages/numpy/_core/_operand_flag_tests.cp313-win_amd64.pyd +0 -0
  24. python/user_packages/Python313/site-packages/numpy/_core/_rational_tests.cp313-win_amd64.lib +0 -0
  25. python/user_packages/Python313/site-packages/numpy/_core/_rational_tests.cp313-win_amd64.pyd +0 -0
  26. python/user_packages/Python313/site-packages/numpy/_core/_simd.cp313-win_amd64.lib +0 -0
  27. python/user_packages/Python313/site-packages/numpy/_core/_simd.pyi +35 -0
  28. python/user_packages/Python313/site-packages/numpy/_core/_string_helpers.py +100 -0
  29. python/user_packages/Python313/site-packages/numpy/_core/_string_helpers.pyi +12 -0
  30. python/user_packages/Python313/site-packages/numpy/_core/_struct_ufunc_tests.cp313-win_amd64.lib +0 -0
  31. python/user_packages/Python313/site-packages/numpy/_core/_struct_ufunc_tests.cp313-win_amd64.pyd +0 -0
  32. python/user_packages/Python313/site-packages/numpy/_core/_type_aliases.py +131 -0
  33. python/user_packages/Python313/site-packages/numpy/_core/_type_aliases.pyi +86 -0
  34. python/user_packages/Python313/site-packages/numpy/_core/_ufunc_config.py +515 -0
  35. python/user_packages/Python313/site-packages/numpy/_core/_ufunc_config.pyi +69 -0
  36. python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.cp313-win_amd64.lib +0 -0
  37. python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.cp313-win_amd64.pyd +0 -0
  38. python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.pyi +47 -0
  39. python/user_packages/Python313/site-packages/numpy/_core/arrayprint.py +1779 -0
  40. python/user_packages/Python313/site-packages/numpy/_core/arrayprint.pyi +158 -0
  41. python/user_packages/Python313/site-packages/numpy/_core/cversions.py +13 -0
  42. python/user_packages/Python313/site-packages/numpy/_core/defchararray.py +1414 -0
  43. python/user_packages/Python313/site-packages/numpy/_core/defchararray.pyi +1150 -0
  44. python/user_packages/Python313/site-packages/numpy/_core/einsumfunc.py +1650 -0
  45. python/user_packages/Python313/site-packages/numpy/_core/einsumfunc.pyi +184 -0
  46. python/user_packages/Python313/site-packages/numpy/_core/fromnumeric.py +0 -0
  47. python/user_packages/Python313/site-packages/numpy/_core/fromnumeric.pyi +1735 -0
  48. python/user_packages/Python313/site-packages/numpy/_core/function_base.py +547 -0
  49. python/user_packages/Python313/site-packages/numpy/_core/function_base.pyi +276 -0
  50. python/user_packages/Python313/site-packages/numpy/_core/getlimits.py +462 -0
python/user_packages/Python313/site-packages/numpy/_core/__init__.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains the core of NumPy: ndarray, ufuncs, dtypes, etc.
3
+
4
+ Please note that this module is private. All functions and objects
5
+ are available in the main ``numpy`` namespace - use that instead.
6
+
7
+ """
8
+
9
+ import os
10
+
11
+ from numpy.version import version as __version__
12
+
13
+ # disables OpenBLAS affinity setting of the main thread that limits
14
+ # python threads or processes to one core
15
+ env_added = []
16
+ for envkey in ['OPENBLAS_MAIN_FREE']:
17
+ if envkey not in os.environ:
18
+ # Note: using `putenv` (and `unsetenv` further down) instead of updating
19
+ # `os.environ` on purpose to avoid a race condition, see gh-30627.
20
+ os.putenv(envkey, '1')
21
+ env_added.append(envkey)
22
+
23
+ try:
24
+ from . import multiarray
25
+ except ImportError as exc:
26
+ import sys
27
+
28
+ # Bypass for the module re-initialization opt-out
29
+ if exc.msg == "cannot load module more than once per process":
30
+ raise
31
+
32
+ # Basically always, the problem should be that the C module is wrong/missing...
33
+ if (
34
+ isinstance(exc, ModuleNotFoundError)
35
+ and exc.name == "numpy._core._multiarray_umath"
36
+ ):
37
+ import sys
38
+ candidates = []
39
+ for path in __path__:
40
+ candidates.extend(
41
+ f for f in os.listdir(path) if f.startswith("_multiarray_umath"))
42
+ if len(candidates) == 0:
43
+ bad_c_module_info = (
44
+ "We found no compiled module, did NumPy build successfully?\n")
45
+ else:
46
+ candidate_str = '\n * '.join(candidates)
47
+ # cache_tag is documented to be possibly None, so just use name if it is
48
+ # this guesses at cache_tag being the same as the extension module scheme
49
+ tag = sys.implementation.cache_tag or sys.implementation.name
50
+ bad_c_module_info = (
51
+ f"The following compiled module files exist, but seem incompatible\n"
52
+ f"with with either python '{tag}' or the "
53
+ f"platform '{sys.platform}':\n\n * {candidate_str}\n"
54
+ )
55
+ else:
56
+ bad_c_module_info = ""
57
+
58
+ major, minor, *_ = sys.version_info
59
+ msg = f"""
60
+
61
+ IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
62
+
63
+ Importing the numpy C-extensions failed. This error can happen for
64
+ many reasons, often due to issues with your setup or how NumPy was
65
+ installed.
66
+ {bad_c_module_info}
67
+ We have compiled some common reasons and troubleshooting tips at:
68
+
69
+ https://numpy.org/devdocs/user/troubleshooting-importerror.html
70
+
71
+ Please note and check the following:
72
+
73
+ * The Python version is: Python {major}.{minor} from "{sys.executable}"
74
+ * The NumPy version is: "{__version__}"
75
+
76
+ and make sure that they are the versions you expect.
77
+
78
+ Please carefully study the information and documentation linked above.
79
+ This is unlikely to be a NumPy issue but will be caused by a bad install
80
+ or environment on your machine.
81
+
82
+ Original error was: {exc}
83
+ """
84
+
85
+ raise ImportError(msg) from exc
86
+ finally:
87
+ for envkey in env_added:
88
+ os.unsetenv(envkey)
89
+ del envkey
90
+ del env_added
91
+ del os
92
+
93
+ from . import umath
94
+
95
+ # Check that multiarray,umath are pure python modules wrapping
96
+ # _multiarray_umath and not either of the old c-extension modules
97
+ if not (hasattr(multiarray, '_multiarray_umath') and
98
+ hasattr(umath, '_multiarray_umath')):
99
+ import sys
100
+ path = sys.modules['numpy'].__path__
101
+ msg = ("Something is wrong with the numpy installation. "
102
+ "While importing we detected an older version of "
103
+ "numpy in {}. One method of fixing this is to repeatedly uninstall "
104
+ "numpy until none is found, then reinstall this version.")
105
+ raise ImportError(msg.format(path))
106
+
107
+ from . import numerictypes as nt
108
+ from .numerictypes import sctypeDict, sctypes
109
+
110
+ multiarray.set_typeDict(nt.sctypeDict)
111
+ from . import einsumfunc, fromnumeric, function_base, getlimits, numeric, shape_base
112
+ from .einsumfunc import *
113
+ from .fromnumeric import *
114
+ from .function_base import *
115
+ from .getlimits import *
116
+
117
+ # Note: module name memmap is overwritten by a class with same name
118
+ from .memmap import *
119
+ from .numeric import *
120
+ from .records import recarray, record
121
+ from .shape_base import *
122
+
123
+ del nt
124
+
125
+ # do this after everything else, to minimize the chance of this misleadingly
126
+ # appearing in an import-time traceback
127
+ # add these for module-freeze analysis (like PyInstaller)
128
+ from . import (
129
+ _add_newdocs,
130
+ _add_newdocs_scalars,
131
+ _dtype,
132
+ _dtype_ctypes,
133
+ _internal,
134
+ _methods,
135
+ )
136
+ from .numeric import absolute as abs
137
+
138
+ acos = numeric.arccos
139
+ acosh = numeric.arccosh
140
+ asin = numeric.arcsin
141
+ asinh = numeric.arcsinh
142
+ atan = numeric.arctan
143
+ atanh = numeric.arctanh
144
+ atan2 = numeric.arctan2
145
+ concat = numeric.concatenate
146
+ bitwise_left_shift = numeric.left_shift
147
+ bitwise_invert = numeric.invert
148
+ bitwise_right_shift = numeric.right_shift
149
+ permute_dims = numeric.transpose
150
+ pow = numeric.power
151
+
152
+ __all__ = [
153
+ "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2",
154
+ "bitwise_invert", "bitwise_left_shift", "bitwise_right_shift", "concat",
155
+ "pow", "permute_dims", "memmap", "sctypeDict", "record", "recarray"
156
+ ]
157
+ __all__ += numeric.__all__
158
+ __all__ += function_base.__all__
159
+ __all__ += getlimits.__all__
160
+ __all__ += shape_base.__all__
161
+ __all__ += einsumfunc.__all__
162
+
163
+
164
+ def _ufunc_reduce(func):
165
+ # Report the `__name__`. pickle will try to find the module. Note that
166
+ # pickle supports for this `__name__` to be a `__qualname__`. It may
167
+ # make sense to add a `__qualname__` to ufuncs, to allow this more
168
+ # explicitly (Numba has ufuncs as attributes).
169
+ # See also: https://github.com/dask/distributed/issues/3450
170
+ return func.__name__
171
+
172
+
173
+ def _DType_reconstruct(scalar_type):
174
+ # This is a work-around to pickle type(np.dtype(np.float64)), etc.
175
+ # and it should eventually be replaced with a better solution, e.g. when
176
+ # DTypes become HeapTypes.
177
+ return type(dtype(scalar_type))
178
+
179
+
180
+ def _DType_reduce(DType):
181
+ # As types/classes, most DTypes can simply be pickled by their name:
182
+ if not DType._legacy or DType.__module__ == "numpy.dtypes":
183
+ return DType.__name__
184
+
185
+ # However, user defined legacy dtypes (like rational) do not end up in
186
+ # `numpy.dtypes` as module and do not have a public class at all.
187
+ # For these, we pickle them by reconstructing them from the scalar type:
188
+ scalar_type = DType.type
189
+ return _DType_reconstruct, (scalar_type,)
190
+
191
+
192
+ import copyreg
193
+
194
+ copyreg.pickle(ufunc, _ufunc_reduce)
195
+ copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
196
+
197
+ # Unclutter namespace (must keep _*_reconstruct for unpickling)
198
+ del copyreg, _ufunc_reduce, _DType_reduce
199
+
200
+ from numpy._pytesttester import PytestTester
201
+
202
+ test = PytestTester(__name__)
203
+ del PytestTester
python/user_packages/Python313/site-packages/numpy/_core/__init__.pyi ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # keep in sync with https://github.com/numpy/numtype/blob/main/src/numpy-stubs/_core/__init__.pyi
2
+
3
+ from ._asarray import require
4
+ from ._ufunc_config import (
5
+ errstate,
6
+ getbufsize,
7
+ geterr,
8
+ geterrcall,
9
+ setbufsize,
10
+ seterr,
11
+ seterrcall,
12
+ )
13
+ from .arrayprint import (
14
+ array2string,
15
+ array_repr,
16
+ array_str,
17
+ format_float_positional,
18
+ format_float_scientific,
19
+ get_printoptions,
20
+ printoptions,
21
+ set_printoptions,
22
+ )
23
+ from .einsumfunc import einsum, einsum_path
24
+ from .fromnumeric import (
25
+ all,
26
+ amax,
27
+ amin,
28
+ any,
29
+ argmax,
30
+ argmin,
31
+ argpartition,
32
+ argsort,
33
+ around,
34
+ choose,
35
+ clip,
36
+ compress,
37
+ cumprod,
38
+ cumsum,
39
+ cumulative_prod,
40
+ cumulative_sum,
41
+ diagonal,
42
+ matrix_transpose,
43
+ max,
44
+ mean,
45
+ min,
46
+ ndim,
47
+ nonzero,
48
+ partition,
49
+ prod,
50
+ ptp,
51
+ put,
52
+ ravel,
53
+ repeat,
54
+ reshape,
55
+ resize,
56
+ round,
57
+ searchsorted,
58
+ shape,
59
+ size,
60
+ sort,
61
+ squeeze,
62
+ std,
63
+ sum,
64
+ swapaxes,
65
+ take,
66
+ trace,
67
+ transpose,
68
+ transpose as permute_dims,
69
+ var,
70
+ )
71
+ from .function_base import geomspace, linspace, logspace
72
+ from .getlimits import finfo, iinfo
73
+ from .memmap import memmap
74
+ from .numeric import (
75
+ False_,
76
+ True_,
77
+ allclose,
78
+ arange,
79
+ argwhere,
80
+ array,
81
+ array_equal,
82
+ array_equiv,
83
+ asanyarray,
84
+ asarray,
85
+ ascontiguousarray,
86
+ asfortranarray,
87
+ astype,
88
+ base_repr,
89
+ binary_repr,
90
+ bitwise_not,
91
+ broadcast,
92
+ can_cast,
93
+ concatenate,
94
+ concatenate as concat,
95
+ convolve,
96
+ copyto,
97
+ correlate,
98
+ count_nonzero,
99
+ cross,
100
+ dot,
101
+ dtype,
102
+ empty,
103
+ empty_like,
104
+ flatiter,
105
+ flatnonzero,
106
+ from_dlpack,
107
+ frombuffer,
108
+ fromfile,
109
+ fromfunction,
110
+ fromiter,
111
+ fromstring,
112
+ full,
113
+ full_like,
114
+ identity,
115
+ indices,
116
+ inf,
117
+ inner,
118
+ isclose,
119
+ isfortran,
120
+ isscalar,
121
+ lexsort,
122
+ little_endian,
123
+ matmul,
124
+ may_share_memory,
125
+ min_scalar_type,
126
+ moveaxis,
127
+ nan,
128
+ ndarray,
129
+ nditer,
130
+ nested_iters,
131
+ newaxis,
132
+ ones,
133
+ ones_like,
134
+ outer,
135
+ promote_types,
136
+ putmask,
137
+ result_type,
138
+ roll,
139
+ rollaxis,
140
+ shares_memory,
141
+ tensordot,
142
+ ufunc,
143
+ vdot,
144
+ vecdot,
145
+ where,
146
+ zeros,
147
+ zeros_like,
148
+ )
149
+ from .numerictypes import (
150
+ ScalarType,
151
+ bool,
152
+ bool_,
153
+ busday_count,
154
+ busday_offset,
155
+ busdaycalendar,
156
+ byte,
157
+ bytes_,
158
+ cdouble,
159
+ character,
160
+ clongdouble,
161
+ complex64,
162
+ complex128,
163
+ complex192,
164
+ complex256,
165
+ complexfloating,
166
+ csingle,
167
+ datetime64,
168
+ datetime_as_string,
169
+ datetime_data,
170
+ double,
171
+ flexible,
172
+ float16,
173
+ float32,
174
+ float64,
175
+ float96,
176
+ float128,
177
+ floating,
178
+ generic,
179
+ half,
180
+ inexact,
181
+ int8,
182
+ int16,
183
+ int32,
184
+ int64,
185
+ int_,
186
+ intc,
187
+ integer,
188
+ intp,
189
+ is_busday,
190
+ isdtype,
191
+ issubdtype,
192
+ long,
193
+ longdouble,
194
+ longlong,
195
+ number,
196
+ object_,
197
+ sctypeDict,
198
+ short,
199
+ signedinteger,
200
+ single,
201
+ str_,
202
+ timedelta64,
203
+ typecodes,
204
+ ubyte,
205
+ uint,
206
+ uint8,
207
+ uint16,
208
+ uint32,
209
+ uint64,
210
+ uintc,
211
+ uintp,
212
+ ulong,
213
+ ulonglong,
214
+ unsignedinteger,
215
+ ushort,
216
+ void,
217
+ )
218
+ from .records import recarray, record
219
+ from .shape_base import (
220
+ atleast_1d,
221
+ atleast_2d,
222
+ atleast_3d,
223
+ block,
224
+ hstack,
225
+ stack,
226
+ unstack,
227
+ vstack,
228
+ )
229
+ from .umath import (
230
+ absolute,
231
+ absolute as abs,
232
+ add,
233
+ arccos,
234
+ arccos as acos,
235
+ arccosh,
236
+ arccosh as acosh,
237
+ arcsin,
238
+ arcsin as asin,
239
+ arcsinh,
240
+ arcsinh as asinh,
241
+ arctan,
242
+ arctan as atan,
243
+ arctan2,
244
+ arctan2 as atan2,
245
+ arctanh,
246
+ arctanh as atanh,
247
+ bitwise_and,
248
+ bitwise_count,
249
+ bitwise_or,
250
+ bitwise_xor,
251
+ cbrt,
252
+ ceil,
253
+ conj,
254
+ conjugate,
255
+ copysign,
256
+ cos,
257
+ cosh,
258
+ deg2rad,
259
+ degrees,
260
+ divide,
261
+ divmod,
262
+ e,
263
+ equal,
264
+ euler_gamma,
265
+ exp,
266
+ exp2,
267
+ expm1,
268
+ fabs,
269
+ float_power,
270
+ floor,
271
+ floor_divide,
272
+ fmax,
273
+ fmin,
274
+ fmod,
275
+ frexp,
276
+ frompyfunc,
277
+ gcd,
278
+ greater,
279
+ greater_equal,
280
+ heaviside,
281
+ hypot,
282
+ invert,
283
+ invert as bitwise_invert,
284
+ isfinite,
285
+ isinf,
286
+ isnan,
287
+ isnat,
288
+ lcm,
289
+ ldexp,
290
+ left_shift,
291
+ left_shift as bitwise_left_shift,
292
+ less,
293
+ less_equal,
294
+ log,
295
+ log1p,
296
+ log2,
297
+ log10,
298
+ logaddexp,
299
+ logaddexp2,
300
+ logical_and,
301
+ logical_not,
302
+ logical_or,
303
+ logical_xor,
304
+ matvec,
305
+ maximum,
306
+ minimum,
307
+ mod,
308
+ modf,
309
+ multiply,
310
+ negative,
311
+ nextafter,
312
+ not_equal,
313
+ pi,
314
+ positive,
315
+ power,
316
+ power as pow,
317
+ rad2deg,
318
+ radians,
319
+ reciprocal,
320
+ remainder,
321
+ right_shift,
322
+ right_shift as bitwise_right_shift,
323
+ rint,
324
+ sign,
325
+ signbit,
326
+ sin,
327
+ sinh,
328
+ spacing,
329
+ sqrt,
330
+ square,
331
+ subtract,
332
+ tan,
333
+ tanh,
334
+ true_divide,
335
+ trunc,
336
+ vecmat,
337
+ )
338
+
339
+ __all__ = [
340
+ "False_",
341
+ "ScalarType",
342
+ "True_",
343
+ "abs",
344
+ "absolute",
345
+ "acos",
346
+ "acosh",
347
+ "add",
348
+ "all",
349
+ "allclose",
350
+ "amax",
351
+ "amin",
352
+ "any",
353
+ "arange",
354
+ "arccos",
355
+ "arccosh",
356
+ "arcsin",
357
+ "arcsinh",
358
+ "arctan",
359
+ "arctan2",
360
+ "arctanh",
361
+ "argmax",
362
+ "argmin",
363
+ "argpartition",
364
+ "argsort",
365
+ "argwhere",
366
+ "around",
367
+ "array",
368
+ "array2string",
369
+ "array_equal",
370
+ "array_equiv",
371
+ "array_repr",
372
+ "array_str",
373
+ "asanyarray",
374
+ "asarray",
375
+ "ascontiguousarray",
376
+ "asfortranarray",
377
+ "asin",
378
+ "asinh",
379
+ "astype",
380
+ "atan",
381
+ "atan2",
382
+ "atanh",
383
+ "atleast_1d",
384
+ "atleast_2d",
385
+ "atleast_3d",
386
+ "base_repr",
387
+ "binary_repr",
388
+ "bitwise_and",
389
+ "bitwise_count",
390
+ "bitwise_invert",
391
+ "bitwise_left_shift",
392
+ "bitwise_not",
393
+ "bitwise_or",
394
+ "bitwise_right_shift",
395
+ "bitwise_xor",
396
+ "block",
397
+ "bool",
398
+ "bool_",
399
+ "broadcast",
400
+ "busday_count",
401
+ "busday_offset",
402
+ "busdaycalendar",
403
+ "byte",
404
+ "bytes_",
405
+ "can_cast",
406
+ "cbrt",
407
+ "cdouble",
408
+ "ceil",
409
+ "character",
410
+ "choose",
411
+ "clip",
412
+ "clongdouble",
413
+ "complex64",
414
+ "complex128",
415
+ "complex192",
416
+ "complex256",
417
+ "complexfloating",
418
+ "compress",
419
+ "concat",
420
+ "concatenate",
421
+ "conj",
422
+ "conjugate",
423
+ "convolve",
424
+ "copysign",
425
+ "copyto",
426
+ "correlate",
427
+ "cos",
428
+ "cosh",
429
+ "count_nonzero",
430
+ "cross",
431
+ "csingle",
432
+ "cumprod",
433
+ "cumsum",
434
+ "cumulative_prod",
435
+ "cumulative_sum",
436
+ "datetime64",
437
+ "datetime_as_string",
438
+ "datetime_data",
439
+ "deg2rad",
440
+ "degrees",
441
+ "diagonal",
442
+ "divide",
443
+ "divmod",
444
+ "dot",
445
+ "double",
446
+ "dtype",
447
+ "e",
448
+ "einsum",
449
+ "einsum_path",
450
+ "empty",
451
+ "empty_like",
452
+ "equal",
453
+ "errstate",
454
+ "euler_gamma",
455
+ "exp",
456
+ "exp2",
457
+ "expm1",
458
+ "fabs",
459
+ "finfo",
460
+ "flatiter",
461
+ "flatnonzero",
462
+ "flexible",
463
+ "float16",
464
+ "float32",
465
+ "float64",
466
+ "float96",
467
+ "float128",
468
+ "float_power",
469
+ "floating",
470
+ "floor",
471
+ "floor_divide",
472
+ "fmax",
473
+ "fmin",
474
+ "fmod",
475
+ "format_float_positional",
476
+ "format_float_scientific",
477
+ "frexp",
478
+ "from_dlpack",
479
+ "frombuffer",
480
+ "fromfile",
481
+ "fromfunction",
482
+ "fromiter",
483
+ "frompyfunc",
484
+ "fromstring",
485
+ "full",
486
+ "full_like",
487
+ "gcd",
488
+ "generic",
489
+ "geomspace",
490
+ "get_printoptions",
491
+ "getbufsize",
492
+ "geterr",
493
+ "geterrcall",
494
+ "greater",
495
+ "greater_equal",
496
+ "half",
497
+ "heaviside",
498
+ "hstack",
499
+ "hypot",
500
+ "identity",
501
+ "iinfo",
502
+ "indices",
503
+ "inexact",
504
+ "inf",
505
+ "inner",
506
+ "int8",
507
+ "int16",
508
+ "int32",
509
+ "int64",
510
+ "int_",
511
+ "intc",
512
+ "integer",
513
+ "intp",
514
+ "invert",
515
+ "is_busday",
516
+ "isclose",
517
+ "isdtype",
518
+ "isfinite",
519
+ "isfortran",
520
+ "isinf",
521
+ "isnan",
522
+ "isnat",
523
+ "isscalar",
524
+ "issubdtype",
525
+ "lcm",
526
+ "ldexp",
527
+ "left_shift",
528
+ "less",
529
+ "less_equal",
530
+ "lexsort",
531
+ "linspace",
532
+ "little_endian",
533
+ "log",
534
+ "log1p",
535
+ "log2",
536
+ "log10",
537
+ "logaddexp",
538
+ "logaddexp2",
539
+ "logical_and",
540
+ "logical_not",
541
+ "logical_or",
542
+ "logical_xor",
543
+ "logspace",
544
+ "long",
545
+ "longdouble",
546
+ "longlong",
547
+ "matmul",
548
+ "matrix_transpose",
549
+ "matvec",
550
+ "max",
551
+ "maximum",
552
+ "may_share_memory",
553
+ "mean",
554
+ "memmap",
555
+ "min",
556
+ "min_scalar_type",
557
+ "minimum",
558
+ "mod",
559
+ "modf",
560
+ "moveaxis",
561
+ "multiply",
562
+ "nan",
563
+ "ndarray",
564
+ "ndim",
565
+ "nditer",
566
+ "negative",
567
+ "nested_iters",
568
+ "newaxis",
569
+ "nextafter",
570
+ "nonzero",
571
+ "not_equal",
572
+ "number",
573
+ "object_",
574
+ "ones",
575
+ "ones_like",
576
+ "outer",
577
+ "partition",
578
+ "permute_dims",
579
+ "pi",
580
+ "positive",
581
+ "pow",
582
+ "power",
583
+ "printoptions",
584
+ "prod",
585
+ "promote_types",
586
+ "ptp",
587
+ "put",
588
+ "putmask",
589
+ "rad2deg",
590
+ "radians",
591
+ "ravel",
592
+ "recarray",
593
+ "reciprocal",
594
+ "record",
595
+ "remainder",
596
+ "repeat",
597
+ "require",
598
+ "reshape",
599
+ "resize",
600
+ "result_type",
601
+ "right_shift",
602
+ "rint",
603
+ "roll",
604
+ "rollaxis",
605
+ "round",
606
+ "sctypeDict",
607
+ "searchsorted",
608
+ "set_printoptions",
609
+ "setbufsize",
610
+ "seterr",
611
+ "seterrcall",
612
+ "shape",
613
+ "shares_memory",
614
+ "short",
615
+ "sign",
616
+ "signbit",
617
+ "signedinteger",
618
+ "sin",
619
+ "single",
620
+ "sinh",
621
+ "size",
622
+ "sort",
623
+ "spacing",
624
+ "sqrt",
625
+ "square",
626
+ "squeeze",
627
+ "stack",
628
+ "std",
629
+ "str_",
630
+ "subtract",
631
+ "sum",
632
+ "swapaxes",
633
+ "take",
634
+ "tan",
635
+ "tanh",
636
+ "tensordot",
637
+ "timedelta64",
638
+ "trace",
639
+ "transpose",
640
+ "true_divide",
641
+ "trunc",
642
+ "typecodes",
643
+ "ubyte",
644
+ "ufunc",
645
+ "uint",
646
+ "uint8",
647
+ "uint16",
648
+ "uint32",
649
+ "uint64",
650
+ "uintc",
651
+ "uintp",
652
+ "ulong",
653
+ "ulonglong",
654
+ "unsignedinteger",
655
+ "unstack",
656
+ "ushort",
657
+ "var",
658
+ "vdot",
659
+ "vecdot",
660
+ "vecmat",
661
+ "void",
662
+ "vstack",
663
+ "where",
664
+ "zeros",
665
+ "zeros_like",
666
+ ]
python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs.py ADDED
The diff for this file is too large to render. See raw diff
 
python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs.pyi ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .function_base import add_newdoc as add_newdoc
2
+ from .overrides import get_array_function_like_doc as get_array_function_like_doc
python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs_scalars.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is separate from ``_add_newdocs.py`` so that it can be mocked out by
3
+ our sphinx ``conf.py`` during doc builds, where we want to avoid showing
4
+ platform-dependent information.
5
+ """
6
+ import os
7
+ import sys
8
+
9
+ from numpy._core import dtype, numerictypes as _numerictypes
10
+ from numpy._core.function_base import add_newdoc
11
+
12
+ ##############################################################################
13
+ #
14
+ # Documentation for concrete scalar classes
15
+ #
16
+ ##############################################################################
17
+
18
+ def numeric_type_aliases(aliases):
19
+ def type_aliases_gen():
20
+ for alias, doc in aliases:
21
+ try:
22
+ alias_type = getattr(_numerictypes, alias)
23
+ except AttributeError:
24
+ # The set of aliases that actually exist varies between platforms
25
+ pass
26
+ else:
27
+ yield (alias_type, alias, doc)
28
+ return list(type_aliases_gen())
29
+
30
+
31
+ possible_aliases = numeric_type_aliases([
32
+ ('int8', '8-bit signed integer (``-128`` to ``127``)'),
33
+ ('int16', '16-bit signed integer (``-32_768`` to ``32_767``)'),
34
+ ('int32', '32-bit signed integer (``-2_147_483_648`` to ``2_147_483_647``)'),
35
+ ('int64', '64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``)'),
36
+ ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'),
37
+ ('uint8', '8-bit unsigned integer (``0`` to ``255``)'),
38
+ ('uint16', '16-bit unsigned integer (``0`` to ``65_535``)'),
39
+ ('uint32', '32-bit unsigned integer (``0`` to ``4_294_967_295``)'),
40
+ ('uint64', '64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``)'),
41
+ ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'),
42
+ ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'),
43
+ ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'),
44
+ ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'),
45
+ ('float96', '96-bit extended-precision floating-point number type'),
46
+ ('float128', '128-bit extended-precision floating-point number type'),
47
+ ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'),
48
+ ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'),
49
+ ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'),
50
+ ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers'),
51
+ ])
52
+
53
+
54
+ def _get_platform_and_machine():
55
+ try:
56
+ system, _, _, _, machine = os.uname()
57
+ except AttributeError:
58
+ system = sys.platform
59
+ if system == 'win32':
60
+ machine = os.environ.get('PROCESSOR_ARCHITEW6432', '') \
61
+ or os.environ.get('PROCESSOR_ARCHITECTURE', '')
62
+ else:
63
+ machine = 'unknown'
64
+ return system, machine
65
+
66
+
67
+ _system, _machine = _get_platform_and_machine()
68
+ _doc_alias_string = f":Alias on this platform ({_system} {_machine}):"
69
+
70
+ # docstring prefix that cpython uses to populate `__text_signature__`
71
+ _ARGUMENT_CLINIC_TEMPLATE = """{name}{signature}
72
+ --
73
+
74
+ {docstring}"""
75
+
76
+ def add_newdoc_for_scalar_type(name: str, text_signature: str, doc: str) -> None:
77
+ # note: `:field: value` is rST syntax which renders as field lists.
78
+ cls = getattr(_numerictypes, name)
79
+ module = cls.__module__
80
+
81
+ lines_extra = [
82
+ "", # blank line after main doc
83
+ f":Character code: ``{dtype(cls).char!r}``",
84
+ ]
85
+
86
+ if name != cls.__name__:
87
+ lines_extra.append(f":Canonical name: `{module}.{name}`")
88
+
89
+ lines_extra.extend(
90
+ f"{_doc_alias_string} `{module}.{alias}`: {doc}."
91
+ for alias_type, alias, doc in possible_aliases
92
+ if alias_type is cls
93
+ )
94
+
95
+ docstring = _ARGUMENT_CLINIC_TEMPLATE.format(
96
+ name=cls.__name__, # must match the class name
97
+ signature=text_signature,
98
+ docstring="\n".join([doc.strip(), *lines_extra]),
99
+ )
100
+ add_newdoc('numpy._core.numerictypes', name, docstring)
101
+
102
+
103
+ for bool_name in ('bool', 'bool_'):
104
+ add_newdoc_for_scalar_type(bool_name, '(value=False, /)', """
105
+ Boolean type (True or False), stored as a byte.
106
+
107
+ .. warning::
108
+
109
+ The :class:`bool` type is not a subclass of the :class:`int_` type
110
+ (the :class:`bool` is not even a number type). This is different
111
+ than Python's default implementation of :class:`bool` as a
112
+ sub-class of :class:`int`.
113
+ """)
114
+
115
+ add_newdoc_for_scalar_type('byte', '(value=0, /)', """
116
+ Signed integer type, compatible with C ``char``.
117
+ """)
118
+
119
+ add_newdoc_for_scalar_type('short', '(value=0, /)', """
120
+ Signed integer type, compatible with C ``short``.
121
+ """)
122
+
123
+ add_newdoc_for_scalar_type('intc', '(value=0, /)', """
124
+ Signed integer type, compatible with C ``int``.
125
+ """)
126
+
127
+ add_newdoc_for_scalar_type('long', '(value=0, /)', """
128
+ Signed integer type, compatible with C ``long``.
129
+ """)
130
+
131
+ # TODO: These docs probably need an if to highlight the default rather than
132
+ # the C-types (and be correct).
133
+ add_newdoc_for_scalar_type('int_', '(value=0, /)', """
134
+ Default signed integer type, 64bit on 64bit systems and 32bit on 32bit systems.
135
+ """)
136
+
137
+ add_newdoc_for_scalar_type('longlong', '(value=0, /)', """
138
+ Signed integer type, compatible with C ``long long``.
139
+ """)
140
+
141
+ add_newdoc_for_scalar_type('ubyte', '(value=0, /)', """
142
+ Unsigned integer type, compatible with C ``unsigned char``.
143
+ """)
144
+
145
+ add_newdoc_for_scalar_type('ushort', '(value=0, /)', """
146
+ Unsigned integer type, compatible with C ``unsigned short``.
147
+ """)
148
+
149
+ add_newdoc_for_scalar_type('uintc', '(value=0, /)', """
150
+ Unsigned integer type, compatible with C ``unsigned int``.
151
+ """)
152
+
153
+ add_newdoc_for_scalar_type('uint', '(value=0, /)', """
154
+ Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit systems.
155
+ """)
156
+
157
+ add_newdoc_for_scalar_type('ulong', '(value=0, /)', """
158
+ Unsigned integer type, compatible with C ``unsigned long``.
159
+ """)
160
+
161
+ add_newdoc_for_scalar_type('ulonglong', '(value=0, /)', """
162
+ Unsigned integer type, compatible with C ``unsigned long long``.
163
+ """)
164
+
165
+ add_newdoc_for_scalar_type('half', '(value=0, /)', """
166
+ Half-precision floating-point number type.
167
+ """)
168
+
169
+ add_newdoc_for_scalar_type('single', '(value=0, /)', """
170
+ Single-precision floating-point number type, compatible with C ``float``.
171
+ """)
172
+
173
+ add_newdoc_for_scalar_type('double', '(value=0, /)', """
174
+ Double-precision floating-point number type, compatible with Python :class:`float` and C ``double``.
175
+ """)
176
+
177
+ add_newdoc_for_scalar_type('longdouble', '(value=0, /)', """
178
+ Extended-precision floating-point number type, compatible with C ``long double``
179
+ but not necessarily with IEEE 754 quadruple-precision.
180
+ """)
181
+
182
+ add_newdoc_for_scalar_type('csingle', '(real=0, imag=0, /)', """
183
+ Complex number type composed of two single-precision floating-point numbers.
184
+ """)
185
+
186
+ add_newdoc_for_scalar_type('cdouble', '(real=0, imag=0, /)', """
187
+ Complex number type composed of two double-precision floating-point numbers,
188
+ compatible with Python :class:`complex`.
189
+ """)
190
+
191
+ add_newdoc_for_scalar_type('clongdouble', '(real=0, imag=0, /)', """
192
+ Complex number type composed of two extended-precision floating-point numbers.
193
+ """)
194
+
195
+ add_newdoc_for_scalar_type('object_', '(value=None, /)', """
196
+ Any Python object.
197
+ """)
198
+
199
+ add_newdoc_for_scalar_type('str_', '(value="", /, *args, **kwargs)', r"""
200
+ A unicode string.
201
+
202
+ This type strips trailing null codepoints.
203
+
204
+ >>> s = np.str_("abc\x00")
205
+ >>> s
206
+ 'abc'
207
+
208
+ Unlike the builtin :class:`str`, this supports the
209
+ :ref:`python:bufferobjects`, exposing its contents as UCS4:
210
+
211
+ >>> m = memoryview(np.str_("abc"))
212
+ >>> m.format
213
+ '3w'
214
+ >>> m.tobytes()
215
+ b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
216
+ """)
217
+
218
+ add_newdoc_for_scalar_type('bytes_', '(value="", /, *args, **kwargs)', r"""
219
+ A byte string.
220
+
221
+ When used in arrays, this type strips trailing null bytes.
222
+ """)
223
+
224
+ add_newdoc_for_scalar_type('void', '(length_or_data, /, dtype=None)', r"""
225
+ np.void(length_or_data, /, dtype=None)
226
+
227
+ Create a new structured or unstructured void scalar.
228
+
229
+ Parameters
230
+ ----------
231
+ length_or_data : int, array-like, bytes-like, object
232
+ One of multiple meanings (see notes). The length or
233
+ bytes data of an unstructured void. Or alternatively,
234
+ the data to be stored in the new scalar when `dtype`
235
+ is provided.
236
+ This can be an array-like, in which case an array may
237
+ be returned.
238
+ dtype : dtype, optional
239
+ If provided the dtype of the new scalar. This dtype must
240
+ be "void" dtype (i.e. a structured or unstructured void,
241
+ see also :ref:`defining-structured-types`).
242
+
243
+ .. versionadded:: 1.24
244
+
245
+ Notes
246
+ -----
247
+ For historical reasons and because void scalars can represent both
248
+ arbitrary byte data and structured dtypes, the void constructor
249
+ has three calling conventions:
250
+
251
+ 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
252
+ ``\0`` bytes. The 5 can be a Python or NumPy integer.
253
+ 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
254
+ The dtype itemsize will match the byte string length, here ``"V10"``.
255
+ 3. When a ``dtype=`` is passed the call is roughly the same as an
256
+ array creation. However, a void scalar rather than array is returned.
257
+
258
+ Please see the examples which show all three different conventions.
259
+
260
+ Examples
261
+ --------
262
+ >>> np.void(5)
263
+ np.void(b'\x00\x00\x00\x00\x00')
264
+ >>> np.void(b'abcd')
265
+ np.void(b'\x61\x62\x63\x64')
266
+ >>> np.void((3.2, b'eggs'), dtype="d,S5")
267
+ np.void((3.2, b'eggs'), dtype=[('f0', '<f8'), ('f1', 'S5')])
268
+ >>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
269
+ np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
270
+ """)
271
+
272
+ add_newdoc_for_scalar_type('datetime64', '(value=None, /, *args)', """
273
+ If created from a 64-bit integer, it represents an offset from ``1970-01-01T00:00:00``.
274
+ If created from string, the string can be in ISO 8601 date or datetime format.
275
+
276
+ When parsing a string to create a datetime object, if the string contains
277
+ a trailing timezone (A 'Z' or a timezone offset), the timezone will be
278
+ dropped and a User Warning is given.
279
+
280
+ Datetime64 objects should be considered to be UTC and therefore have an
281
+ offset of +0000.
282
+
283
+ >>> np.datetime64(10, 'Y')
284
+ np.datetime64('1980')
285
+ >>> np.datetime64('1980', 'Y')
286
+ np.datetime64('1980')
287
+ >>> np.datetime64(10, 'D')
288
+ np.datetime64('1970-01-11')
289
+
290
+ See :ref:`arrays.datetime` for more information.
291
+ """)
292
+
293
+ add_newdoc_for_scalar_type('timedelta64', '(value=0, /, *args)', """
294
+ A timedelta stored as a 64-bit integer.
295
+
296
+ See :ref:`arrays.datetime` for more information.
297
+ """)
298
+
299
+ add_newdoc('numpy._core.numerictypes', "integer", ('is_integer',
300
+ """
301
+ is_integer($self, /)
302
+ --
303
+
304
+ integer.is_integer() -> bool
305
+
306
+ Return ``True`` if the number is finite with integral value.
307
+
308
+ .. versionadded:: 1.22
309
+
310
+ Examples
311
+ --------
312
+ >>> import numpy as np
313
+ >>> np.int64(-2).is_integer()
314
+ True
315
+ >>> np.uint32(5).is_integer()
316
+ True
317
+ """))
318
+
319
+ # TODO: work out how to put this on the base class, np.floating
320
+ for float_name in ('half', 'single', 'double', 'longdouble'):
321
+ add_newdoc('numpy._core.numerictypes', float_name, ('as_integer_ratio',
322
+ f"""
323
+ as_integer_ratio($self, /)
324
+ --
325
+
326
+ {float_name}.as_integer_ratio() -> (int, int)
327
+
328
+ Return a pair of integers, whose ratio is exactly equal to the original
329
+ floating point number, and with a positive denominator.
330
+ Raise `OverflowError` on infinities and a `ValueError` on NaNs.
331
+
332
+ >>> np.{float_name}(10.0).as_integer_ratio()
333
+ (10, 1)
334
+ >>> np.{float_name}(0.0).as_integer_ratio()
335
+ (0, 1)
336
+ >>> np.{float_name}(-.25).as_integer_ratio()
337
+ (-1, 4)
338
+ """))
339
+
340
+ add_newdoc('numpy._core.numerictypes', float_name, ('is_integer',
341
+ f"""
342
+ is_integer($self, /)
343
+ --
344
+
345
+ {float_name}.is_integer() -> bool
346
+
347
+ Return ``True`` if the floating point number is finite with integral
348
+ value, and ``False`` otherwise.
349
+
350
+ .. versionadded:: 1.22
351
+
352
+ Examples
353
+ --------
354
+ >>> np.{float_name}(-2.0).is_integer()
355
+ True
356
+ >>> np.{float_name}(3.2).is_integer()
357
+ False
358
+ """))
359
+
360
+ for int_name in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
361
+ 'int64', 'uint64', 'int64', 'uint64', 'int64', 'uint64',
362
+ 'longlong', 'ulonglong'):
363
+ # Add negative examples for signed cases by checking typecode
364
+ add_newdoc('numpy._core.numerictypes', int_name, ('bit_count',
365
+ f"""
366
+ bit_count($self, /)
367
+ --
368
+
369
+ {int_name}.bit_count() -> int
370
+
371
+ Computes the number of 1-bits in the absolute value of the input.
372
+ Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
373
+
374
+ Examples
375
+ --------
376
+ >>> np.{int_name}(127).bit_count()
377
+ 7""" +
378
+ (f"""
379
+ >>> np.{int_name}(-127).bit_count()
380
+ 7
381
+ """ if dtype(int_name).char.islower() else "")))
python/user_packages/Python313/site-packages/numpy/_core/_add_newdocs_scalars.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Final
2
+
3
+ import numpy as np
4
+
5
+ possible_aliases: Final[list[tuple[type[np.number], str, str]]] = ...
6
+ _system: Final[str] = ...
7
+ _machine: Final[str] = ...
8
+ _doc_alias_string: Final[str] = ...
9
+ _bool_docstring: Final[str] = ...
10
+ bool_name: str = ...
11
+ int_name: str = ...
12
+ float_name: str = ...
13
+
14
+ def numeric_type_aliases(aliases: list[tuple[str, str]]) -> list[tuple[type[np.number], str, str]]: ...
15
+ def add_newdoc_for_scalar_type(name: str, text_signature: str, doc: str) -> None: ...
16
+ def _get_platform_and_machine() -> tuple[str, str]: ...
python/user_packages/Python313/site-packages/numpy/_core/_asarray.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions in the ``as*array`` family that promote array-likes into arrays.
3
+
4
+ `require` fits this category despite its name not matching this pattern.
5
+ """
6
+ from .multiarray import array, asanyarray
7
+ from .overrides import array_function_dispatch, finalize_array_function_like, set_module
8
+
9
+ __all__ = ["require"]
10
+
11
+
12
+ POSSIBLE_FLAGS = {
13
+ 'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C',
14
+ 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F',
15
+ 'A': 'A', 'ALIGNED': 'A',
16
+ 'W': 'W', 'WRITEABLE': 'W',
17
+ 'O': 'O', 'OWNDATA': 'O',
18
+ 'E': 'E', 'ENSUREARRAY': 'E'
19
+ }
20
+
21
+
22
+ @finalize_array_function_like
23
+ @set_module('numpy')
24
+ def require(a, dtype=None, requirements=None, *, like=None):
25
+ """
26
+ Return an ndarray of the provided type that satisfies requirements.
27
+
28
+ This function is useful to be sure that an array with the correct flags
29
+ is returned for passing to compiled code (perhaps through ctypes).
30
+
31
+ Parameters
32
+ ----------
33
+ a : array_like
34
+ The object to be converted to a type-and-requirement-satisfying array.
35
+ dtype : data-type
36
+ The required data-type. If None preserve the current dtype. If your
37
+ application requires the data to be in native byteorder, include
38
+ a byteorder specification as a part of the dtype specification.
39
+ requirements : str or sequence of str
40
+ The requirements list can be any of the following
41
+
42
+ * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
43
+ * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
44
+ * 'ALIGNED' ('A') - ensure a data-type aligned array
45
+ * 'WRITEABLE' ('W') - ensure a writable array
46
+ * 'OWNDATA' ('O') - ensure an array that owns its own data
47
+ * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
48
+ ${ARRAY_FUNCTION_LIKE}
49
+
50
+ .. versionadded:: 1.20.0
51
+
52
+ Returns
53
+ -------
54
+ out : ndarray
55
+ Array with specified requirements and type if given.
56
+
57
+ See Also
58
+ --------
59
+ asarray : Convert input to an ndarray.
60
+ asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
61
+ ascontiguousarray : Convert input to a contiguous array.
62
+ asfortranarray : Convert input to an ndarray with column-major
63
+ memory order.
64
+ ndarray.flags : Information about the memory layout of the array.
65
+
66
+ Notes
67
+ -----
68
+ The returned array will be guaranteed to have the listed requirements
69
+ by making a copy if needed.
70
+
71
+ Examples
72
+ --------
73
+ >>> import numpy as np
74
+ >>> x = np.arange(6).reshape(2,3)
75
+ >>> x.flags
76
+ C_CONTIGUOUS : True
77
+ F_CONTIGUOUS : False
78
+ OWNDATA : False
79
+ WRITEABLE : True
80
+ ALIGNED : True
81
+ WRITEBACKIFCOPY : False
82
+
83
+ >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
84
+ >>> y.flags
85
+ C_CONTIGUOUS : False
86
+ F_CONTIGUOUS : True
87
+ OWNDATA : True
88
+ WRITEABLE : True
89
+ ALIGNED : True
90
+ WRITEBACKIFCOPY : False
91
+
92
+ """
93
+ if like is not None:
94
+ return _require_with_like(
95
+ like,
96
+ a,
97
+ dtype=dtype,
98
+ requirements=requirements,
99
+ )
100
+
101
+ if not requirements:
102
+ return asanyarray(a, dtype=dtype)
103
+
104
+ requirements = {POSSIBLE_FLAGS[x.upper()] for x in requirements}
105
+
106
+ if 'E' in requirements:
107
+ requirements.remove('E')
108
+ subok = False
109
+ else:
110
+ subok = True
111
+
112
+ order = 'A'
113
+ if requirements >= {'C', 'F'}:
114
+ raise ValueError('Cannot specify both "C" and "F" order')
115
+ elif 'F' in requirements:
116
+ order = 'F'
117
+ requirements.remove('F')
118
+ elif 'C' in requirements:
119
+ order = 'C'
120
+ requirements.remove('C')
121
+
122
+ arr = array(a, dtype=dtype, order=order, copy=None, subok=subok)
123
+
124
+ for prop in requirements:
125
+ if not arr.flags[prop]:
126
+ return arr.copy(order)
127
+ return arr
128
+
129
+
130
+ _require_with_like = array_function_dispatch()(require)
python/user_packages/Python313/site-packages/numpy/_core/_asarray.pyi ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, Literal, TypeAlias, TypeVar, overload
3
+
4
+ from numpy._typing import DTypeLike, NDArray, _SupportsArrayFunc
5
+
6
+ __all__ = ["require"]
7
+
8
+ _ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
9
+
10
+ _Requirements: TypeAlias = Literal[
11
+ "C", "C_CONTIGUOUS", "CONTIGUOUS",
12
+ "F", "F_CONTIGUOUS", "FORTRAN",
13
+ "A", "ALIGNED",
14
+ "W", "WRITEABLE",
15
+ "O", "OWNDATA"
16
+ ]
17
+ _E: TypeAlias = Literal["E", "ENSUREARRAY"]
18
+ _RequirementsWithE: TypeAlias = _Requirements | _E
19
+
20
+ @overload
21
+ def require(
22
+ a: _ArrayT,
23
+ dtype: None = None,
24
+ requirements: _Requirements | Iterable[_Requirements] | None = None,
25
+ *,
26
+ like: _SupportsArrayFunc | None = None
27
+ ) -> _ArrayT: ...
28
+ @overload
29
+ def require(
30
+ a: object,
31
+ dtype: DTypeLike | None = None,
32
+ requirements: _E | Iterable[_RequirementsWithE] | None = None,
33
+ *,
34
+ like: _SupportsArrayFunc | None = None
35
+ ) -> NDArray[Any]: ...
36
+ @overload
37
+ def require(
38
+ a: object,
39
+ dtype: DTypeLike | None = None,
40
+ requirements: _Requirements | Iterable[_Requirements] | None = None,
41
+ *,
42
+ like: _SupportsArrayFunc | None = None
43
+ ) -> NDArray[Any]: ...
python/user_packages/Python313/site-packages/numpy/_core/_dtype.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A place for code to be called from the implementation of np.dtype
3
+
4
+ String handling is much easier to do correctly in python.
5
+ """
6
+ import numpy as np
7
+
8
+ _kind_to_stem = {
9
+ 'u': 'uint',
10
+ 'i': 'int',
11
+ 'c': 'complex',
12
+ 'f': 'float',
13
+ 'b': 'bool',
14
+ 'V': 'void',
15
+ 'O': 'object',
16
+ 'M': 'datetime',
17
+ 'm': 'timedelta',
18
+ 'S': 'bytes',
19
+ 'U': 'str',
20
+ }
21
+
22
+
23
+ def _kind_name(dtype):
24
+ try:
25
+ return _kind_to_stem[dtype.kind]
26
+ except KeyError as e:
27
+ raise RuntimeError(
28
+ f"internal dtype error, unknown kind {dtype.kind!r}"
29
+ ) from None
30
+
31
+
32
+ def __str__(dtype):
33
+ if dtype.fields is not None:
34
+ return _struct_str(dtype, include_align=True)
35
+ elif dtype.subdtype:
36
+ return _subarray_str(dtype)
37
+ elif issubclass(dtype.type, np.flexible) or not dtype.isnative:
38
+ return dtype.str
39
+ else:
40
+ return dtype.name
41
+
42
+
43
+ def __repr__(dtype):
44
+ arg_str = _construction_repr(dtype, include_align=False)
45
+ if dtype.isalignedstruct:
46
+ arg_str = arg_str + ", align=True"
47
+ return f"dtype({arg_str})"
48
+
49
+
50
+ def _unpack_field(dtype, offset, title=None):
51
+ """
52
+ Helper function to normalize the items in dtype.fields.
53
+
54
+ Call as:
55
+
56
+ dtype, offset, title = _unpack_field(*dtype.fields[name])
57
+ """
58
+ return dtype, offset, title
59
+
60
+
61
+ def _isunsized(dtype):
62
+ # PyDataType_ISUNSIZED
63
+ return dtype.itemsize == 0
64
+
65
+
66
+ def _construction_repr(dtype, include_align=False, short=False):
67
+ """
68
+ Creates a string repr of the dtype, excluding the 'dtype()' part
69
+ surrounding the object. This object may be a string, a list, or
70
+ a dict depending on the nature of the dtype. This
71
+ is the object passed as the first parameter to the dtype
72
+ constructor, and if no additional constructor parameters are
73
+ given, will reproduce the exact memory layout.
74
+
75
+ Parameters
76
+ ----------
77
+ short : bool
78
+ If true, this creates a shorter repr using 'kind' and 'itemsize',
79
+ instead of the longer type name.
80
+
81
+ include_align : bool
82
+ If true, this includes the 'align=True' parameter
83
+ inside the struct dtype construction dict when needed. Use this flag
84
+ if you want a proper repr string without the 'dtype()' part around it.
85
+
86
+ If false, this does not preserve the
87
+ 'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for
88
+ struct arrays like the regular repr does, because the 'align'
89
+ flag is not part of first dtype constructor parameter. This
90
+ mode is intended for a full 'repr', where the 'align=True' is
91
+ provided as the second parameter.
92
+ """
93
+ if dtype.fields is not None:
94
+ return _struct_str(dtype, include_align=include_align)
95
+ elif dtype.subdtype:
96
+ return _subarray_str(dtype)
97
+ else:
98
+ return _scalar_str(dtype, short=short)
99
+
100
+
101
+ def _scalar_str(dtype, short):
102
+ byteorder = _byte_order_str(dtype)
103
+
104
+ if dtype.type == np.bool:
105
+ if short:
106
+ return "'?'"
107
+ else:
108
+ return "'bool'"
109
+
110
+ elif dtype.type == np.object_:
111
+ # The object reference may be different sizes on different
112
+ # platforms, so it should never include the itemsize here.
113
+ return "'O'"
114
+
115
+ elif dtype.type == np.bytes_:
116
+ if _isunsized(dtype):
117
+ return "'S'"
118
+ else:
119
+ return "'S%d'" % dtype.itemsize
120
+
121
+ elif dtype.type == np.str_:
122
+ if _isunsized(dtype):
123
+ return f"'{byteorder}U'"
124
+ else:
125
+ return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
126
+
127
+ elif dtype.type == str:
128
+ return "'T'"
129
+
130
+ elif not type(dtype)._legacy:
131
+ return f"'{byteorder}{type(dtype).__name__}{dtype.itemsize * 8}'"
132
+
133
+ # unlike the other types, subclasses of void are preserved - but
134
+ # historically the repr does not actually reveal the subclass
135
+ elif issubclass(dtype.type, np.void):
136
+ if _isunsized(dtype):
137
+ return "'V'"
138
+ else:
139
+ return "'V%d'" % dtype.itemsize
140
+
141
+ elif dtype.type == np.datetime64:
142
+ return f"'{byteorder}M8{_datetime_metadata_str(dtype)}'"
143
+
144
+ elif dtype.type == np.timedelta64:
145
+ return f"'{byteorder}m8{_datetime_metadata_str(dtype)}'"
146
+
147
+ elif dtype.isbuiltin == 2:
148
+ return dtype.type.__name__
149
+
150
+ elif np.issubdtype(dtype, np.number):
151
+ # Short repr with endianness, like '<f8'
152
+ if short or dtype.byteorder not in ('=', '|'):
153
+ return "'%s%c%d'" % (byteorder, dtype.kind, dtype.itemsize)
154
+
155
+ # Longer repr, like 'float64'
156
+ else:
157
+ return "'%s%d'" % (_kind_name(dtype), 8 * dtype.itemsize)
158
+
159
+ else:
160
+ raise RuntimeError(
161
+ "Internal error: NumPy dtype unrecognized type number")
162
+
163
+
164
+ def _byte_order_str(dtype):
165
+ """ Normalize byteorder to '<' or '>' """
166
+ # hack to obtain the native and swapped byte order characters
167
+ swapped = np.dtype(int).newbyteorder('S')
168
+ native = swapped.newbyteorder('S')
169
+
170
+ byteorder = dtype.byteorder
171
+ if byteorder == '=':
172
+ return native.byteorder
173
+ if byteorder == 'S':
174
+ # TODO: this path can never be reached
175
+ return swapped.byteorder
176
+ elif byteorder == '|':
177
+ return ''
178
+ else:
179
+ return byteorder
180
+
181
+
182
+ def _datetime_metadata_str(dtype):
183
+ # TODO: this duplicates the C metastr_to_unicode functionality
184
+ unit, count = np.datetime_data(dtype)
185
+ if unit == 'generic':
186
+ return ''
187
+ elif count == 1:
188
+ return f'[{unit}]'
189
+ else:
190
+ return f'[{count}{unit}]'
191
+
192
+
193
+ def _struct_dict_str(dtype, includealignedflag):
194
+ # unpack the fields dictionary into ls
195
+ names = dtype.names
196
+ fld_dtypes = []
197
+ offsets = []
198
+ titles = []
199
+ for name in names:
200
+ fld_dtype, offset, title = _unpack_field(*dtype.fields[name])
201
+ fld_dtypes.append(fld_dtype)
202
+ offsets.append(offset)
203
+ titles.append(title)
204
+
205
+ # Build up a string to make the dictionary
206
+
207
+ if np._core.arrayprint._get_legacy_print_mode() <= 121:
208
+ colon = ":"
209
+ fieldsep = ","
210
+ else:
211
+ colon = ": "
212
+ fieldsep = ", "
213
+
214
+ # First, the names
215
+ ret = "{'names'%s[" % colon
216
+ ret += fieldsep.join(repr(name) for name in names)
217
+
218
+ # Second, the formats
219
+ ret += f"], 'formats'{colon}["
220
+ ret += fieldsep.join(
221
+ _construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
222
+
223
+ # Third, the offsets
224
+ ret += f"], 'offsets'{colon}["
225
+ ret += fieldsep.join("%d" % offset for offset in offsets)
226
+
227
+ # Fourth, the titles
228
+ if any(title is not None for title in titles):
229
+ ret += f"], 'titles'{colon}["
230
+ ret += fieldsep.join(repr(title) for title in titles)
231
+
232
+ # Fifth, the itemsize
233
+ ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize)
234
+
235
+ if (includealignedflag and dtype.isalignedstruct):
236
+ # Finally, the aligned flag
237
+ ret += ", 'aligned'%sTrue}" % colon
238
+ else:
239
+ ret += "}"
240
+
241
+ return ret
242
+
243
+
244
+ def _aligned_offset(offset, alignment):
245
+ # round up offset:
246
+ return - (-offset // alignment) * alignment
247
+
248
+
249
+ def _is_packed(dtype):
250
+ """
251
+ Checks whether the structured data type in 'dtype'
252
+ has a simple layout, where all the fields are in order,
253
+ and follow each other with no alignment padding.
254
+
255
+ When this returns true, the dtype can be reconstructed
256
+ from a list of the field names and dtypes with no additional
257
+ dtype parameters.
258
+
259
+ Duplicates the C `is_dtype_struct_simple_unaligned_layout` function.
260
+ """
261
+ align = dtype.isalignedstruct
262
+ max_alignment = 1
263
+ total_offset = 0
264
+ for name in dtype.names:
265
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
266
+
267
+ if align:
268
+ total_offset = _aligned_offset(total_offset, fld_dtype.alignment)
269
+ max_alignment = max(max_alignment, fld_dtype.alignment)
270
+
271
+ if fld_offset != total_offset:
272
+ return False
273
+ total_offset += fld_dtype.itemsize
274
+
275
+ if align:
276
+ total_offset = _aligned_offset(total_offset, max_alignment)
277
+
278
+ return total_offset == dtype.itemsize
279
+
280
+
281
+ def _struct_list_str(dtype):
282
+ items = []
283
+ for name in dtype.names:
284
+ fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
285
+
286
+ item = "("
287
+ if title is not None:
288
+ item += f"({title!r}, {name!r}), "
289
+ else:
290
+ item += f"{name!r}, "
291
+ # Special case subarray handling here
292
+ if fld_dtype.subdtype is not None:
293
+ base, shape = fld_dtype.subdtype
294
+ item += f"{_construction_repr(base, short=True)}, {shape}"
295
+ else:
296
+ item += _construction_repr(fld_dtype, short=True)
297
+
298
+ item += ")"
299
+ items.append(item)
300
+
301
+ return "[" + ", ".join(items) + "]"
302
+
303
+
304
+ def _struct_str(dtype, include_align):
305
+ # The list str representation can't include the 'align=' flag,
306
+ # so if it is requested and the struct has the aligned flag set,
307
+ # we must use the dict str instead.
308
+ if not (include_align and dtype.isalignedstruct) and _is_packed(dtype):
309
+ sub = _struct_list_str(dtype)
310
+
311
+ else:
312
+ sub = _struct_dict_str(dtype, include_align)
313
+
314
+ # If the data type isn't the default, void, show it
315
+ if dtype.type != np.void:
316
+ return f"({dtype.type.__module__}.{dtype.type.__name__}, {sub})"
317
+ else:
318
+ return sub
319
+
320
+
321
+ def _subarray_str(dtype):
322
+ base, shape = dtype.subdtype
323
+ return f"({_construction_repr(base, short=True)}, {shape})"
324
+
325
+
326
+ def _name_includes_bit_suffix(dtype):
327
+ if dtype.type == np.object_:
328
+ # pointer size varies by system, best to omit it
329
+ return False
330
+ elif dtype.type == np.bool:
331
+ # implied
332
+ return False
333
+ elif dtype.type is None:
334
+ return True
335
+ elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
336
+ # unspecified
337
+ return False
338
+ else:
339
+ return True
340
+
341
+
342
+ def _name_get(dtype):
343
+ # provides dtype.name.__get__, documented as returning a "bit name"
344
+
345
+ if dtype.isbuiltin == 2:
346
+ # user dtypes don't promise to do anything special
347
+ return dtype.type.__name__
348
+
349
+ if not type(dtype)._legacy:
350
+ name = type(dtype).__name__
351
+
352
+ elif issubclass(dtype.type, np.void):
353
+ # historically, void subclasses preserve their name, eg `record64`
354
+ name = dtype.type.__name__
355
+ else:
356
+ name = _kind_name(dtype)
357
+
358
+ # append bit counts
359
+ if _name_includes_bit_suffix(dtype):
360
+ name += f"{dtype.itemsize * 8}"
361
+
362
+ # append metadata to datetimes
363
+ if dtype.type in (np.datetime64, np.timedelta64):
364
+ name += _datetime_metadata_str(dtype)
365
+
366
+ return name
python/user_packages/Python313/site-packages/numpy/_core/_dtype.pyi ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Final, Literal as L, TypeAlias, TypedDict, overload, type_check_only
2
+ from typing_extensions import ReadOnly, TypeVar
3
+
4
+ import numpy as np
5
+
6
+ ###
7
+
8
+ _T = TypeVar("_T")
9
+
10
+ _Name: TypeAlias = L["uint", "int", "complex", "float", "bool", "void", "object", "datetime", "timedelta", "bytes", "str"]
11
+
12
+ @type_check_only
13
+ class _KindToStemType(TypedDict):
14
+ u: ReadOnly[L["uint"]]
15
+ i: ReadOnly[L["int"]]
16
+ c: ReadOnly[L["complex"]]
17
+ f: ReadOnly[L["float"]]
18
+ b: ReadOnly[L["bool"]]
19
+ V: ReadOnly[L["void"]]
20
+ O: ReadOnly[L["object"]]
21
+ M: ReadOnly[L["datetime"]]
22
+ m: ReadOnly[L["timedelta"]]
23
+ S: ReadOnly[L["bytes"]]
24
+ U: ReadOnly[L["str"]]
25
+
26
+ ###
27
+
28
+ _kind_to_stem: Final[_KindToStemType] = ...
29
+
30
+ #
31
+ def _kind_name(dtype: np.dtype) -> _Name: ...
32
+ def __str__(dtype: np.dtype) -> str: ...
33
+ def __repr__(dtype: np.dtype) -> str: ...
34
+
35
+ #
36
+ def _isunsized(dtype: np.dtype) -> bool: ...
37
+ def _is_packed(dtype: np.dtype) -> bool: ...
38
+ def _name_includes_bit_suffix(dtype: np.dtype) -> bool: ...
39
+
40
+ #
41
+ def _construction_repr(dtype: np.dtype, include_align: bool = False, short: bool = False) -> str: ...
42
+ def _scalar_str(dtype: np.dtype, short: bool) -> str: ...
43
+ def _byte_order_str(dtype: np.dtype) -> str: ...
44
+ def _datetime_metadata_str(dtype: np.dtype) -> str: ...
45
+ def _struct_dict_str(dtype: np.dtype, includealignedflag: bool) -> str: ...
46
+ def _struct_list_str(dtype: np.dtype) -> str: ...
47
+ def _struct_str(dtype: np.dtype, include_align: bool) -> str: ...
48
+ def _subarray_str(dtype: np.dtype) -> str: ...
49
+ def _name_get(dtype: np.dtype) -> str: ...
50
+
51
+ #
52
+ @overload
53
+ def _unpack_field(dtype: np.dtype, offset: int, title: _T) -> tuple[np.dtype, int, _T]: ...
54
+ @overload
55
+ def _unpack_field(dtype: np.dtype, offset: int, title: None = None) -> tuple[np.dtype, int, None]: ...
56
+ def _aligned_offset(offset: int, alignment: int) -> int: ...
python/user_packages/Python313/site-packages/numpy/_core/_dtype_ctypes.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversion from ctypes to dtype.
3
+
4
+ In an ideal world, we could achieve this through the PEP3118 buffer protocol,
5
+ something like::
6
+
7
+ def dtype_from_ctypes_type(t):
8
+ # needed to ensure that the shape of `t` is within memoryview.format
9
+ class DummyStruct(ctypes.Structure):
10
+ _fields_ = [('a', t)]
11
+
12
+ # empty to avoid memory allocation
13
+ ctype_0 = (DummyStruct * 0)()
14
+ mv = memoryview(ctype_0)
15
+
16
+ # convert the struct, and slice back out the field
17
+ return _dtype_from_pep3118(mv.format)['a']
18
+
19
+ Unfortunately, this fails because:
20
+
21
+ * ctypes cannot handle length-0 arrays with PEP3118 (bpo-32782)
22
+ * PEP3118 cannot represent unions, but both numpy and ctypes can
23
+ * ctypes cannot handle big-endian structs with PEP3118 (bpo-32780)
24
+ """
25
+
26
+ # We delay-import ctypes for distributions that do not include it.
27
+ # While this module is not used unless the user passes in ctypes
28
+ # members, it is eagerly imported from numpy/_core/__init__.py.
29
+ import numpy as np
30
+
31
+
32
+ def _from_ctypes_array(t):
33
+ return np.dtype((dtype_from_ctypes_type(t._type_), (t._length_,)))
34
+
35
+
36
+ def _from_ctypes_structure(t):
37
+ for item in t._fields_:
38
+ if len(item) > 2:
39
+ raise TypeError(
40
+ "ctypes bitfields have no dtype equivalent")
41
+
42
+ if hasattr(t, "_pack_"):
43
+ import ctypes
44
+ formats = []
45
+ offsets = []
46
+ names = []
47
+ current_offset = 0
48
+ for fname, ftyp in t._fields_:
49
+ names.append(fname)
50
+ formats.append(dtype_from_ctypes_type(ftyp))
51
+ # Each type has a default offset, this is platform dependent
52
+ # for some types.
53
+ effective_pack = min(t._pack_, ctypes.alignment(ftyp))
54
+ current_offset = (
55
+ (current_offset + effective_pack - 1) // effective_pack
56
+ ) * effective_pack
57
+ offsets.append(current_offset)
58
+ current_offset += ctypes.sizeof(ftyp)
59
+
60
+ return np.dtype({
61
+ "formats": formats,
62
+ "offsets": offsets,
63
+ "names": names,
64
+ "itemsize": ctypes.sizeof(t)})
65
+ else:
66
+ fields = []
67
+ for fname, ftyp in t._fields_:
68
+ fields.append((fname, dtype_from_ctypes_type(ftyp)))
69
+
70
+ # by default, ctypes structs are aligned
71
+ return np.dtype(fields, align=True)
72
+
73
+
74
+ def _from_ctypes_scalar(t):
75
+ """
76
+ Return the dtype type with endianness included if it's the case
77
+ """
78
+ if getattr(t, '__ctype_be__', None) is t:
79
+ return np.dtype('>' + t._type_)
80
+ elif getattr(t, '__ctype_le__', None) is t:
81
+ return np.dtype('<' + t._type_)
82
+ else:
83
+ return np.dtype(t._type_)
84
+
85
+
86
+ def _from_ctypes_union(t):
87
+ import ctypes
88
+ formats = []
89
+ offsets = []
90
+ names = []
91
+ for fname, ftyp in t._fields_:
92
+ names.append(fname)
93
+ formats.append(dtype_from_ctypes_type(ftyp))
94
+ offsets.append(0) # Union fields are offset to 0
95
+
96
+ return np.dtype({
97
+ "formats": formats,
98
+ "offsets": offsets,
99
+ "names": names,
100
+ "itemsize": ctypes.sizeof(t)})
101
+
102
+
103
+ def dtype_from_ctypes_type(t):
104
+ """
105
+ Construct a dtype object from a ctypes type
106
+ """
107
+ import _ctypes
108
+ if issubclass(t, _ctypes.Array):
109
+ return _from_ctypes_array(t)
110
+ elif issubclass(t, _ctypes._Pointer):
111
+ raise TypeError("ctypes pointers have no dtype equivalent")
112
+ elif issubclass(t, _ctypes.Structure):
113
+ return _from_ctypes_structure(t)
114
+ elif issubclass(t, _ctypes.Union):
115
+ return _from_ctypes_union(t)
116
+ elif isinstance(getattr(t, '_type_', None), str):
117
+ return _from_ctypes_scalar(t)
118
+ else:
119
+ raise NotImplementedError(
120
+ f"Unknown ctypes type {t.__name__}")
python/user_packages/Python313/site-packages/numpy/_core/_dtype_ctypes.pyi ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ctypes
2
+ import ctypes as ct
3
+ from typing import Any, overload
4
+
5
+ import numpy as np
6
+
7
+ #
8
+ @overload
9
+ def dtype_from_ctypes_type(t: type[_ctypes.Array[Any] | _ctypes.Structure]) -> np.dtype[np.void]: ...
10
+ @overload
11
+ def dtype_from_ctypes_type(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
12
+ @overload
13
+ def dtype_from_ctypes_type(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
14
+ @overload
15
+ def dtype_from_ctypes_type(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
16
+ @overload
17
+ def dtype_from_ctypes_type(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
18
+ @overload
19
+ def dtype_from_ctypes_type(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
20
+ @overload
21
+ def dtype_from_ctypes_type(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
22
+ @overload
23
+ def dtype_from_ctypes_type(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
24
+ @overload
25
+ def dtype_from_ctypes_type(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
26
+ @overload
27
+ def dtype_from_ctypes_type(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
28
+ @overload
29
+ def dtype_from_ctypes_type(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
30
+ @overload
31
+ def dtype_from_ctypes_type(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
32
+ @overload
33
+ def dtype_from_ctypes_type(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
34
+ @overload
35
+ def dtype_from_ctypes_type(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
36
+ @overload
37
+ def dtype_from_ctypes_type(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
38
+ @overload
39
+ def dtype_from_ctypes_type(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
40
+ @overload
41
+ def dtype_from_ctypes_type(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
42
+
43
+ # NOTE: the complex ctypes on python>=3.14 are not yet supported at runtim, see
44
+ # https://github.com/numpy/numpy/issues/28360
45
+
46
+ #
47
+ def _from_ctypes_array(t: type[_ctypes.Array[Any]]) -> np.dtype[np.void]: ...
48
+ def _from_ctypes_structure(t: type[_ctypes.Structure]) -> np.dtype[np.void]: ...
49
+ def _from_ctypes_union(t: type[_ctypes.Union]) -> np.dtype[np.void]: ...
50
+
51
+ # keep in sync with `dtype_from_ctypes_type` (minus the first overload)
52
+ @overload
53
+ def _from_ctypes_scalar(t: type[ct.c_bool]) -> np.dtype[np.bool]: ...
54
+ @overload
55
+ def _from_ctypes_scalar(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ...
56
+ @overload
57
+ def _from_ctypes_scalar(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ...
58
+ @overload
59
+ def _from_ctypes_scalar(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ...
60
+ @overload
61
+ def _from_ctypes_scalar(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ...
62
+ @overload
63
+ def _from_ctypes_scalar(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ...
64
+ @overload
65
+ def _from_ctypes_scalar(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ...
66
+ @overload
67
+ def _from_ctypes_scalar(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ...
68
+ @overload
69
+ def _from_ctypes_scalar(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ...
70
+ @overload
71
+ def _from_ctypes_scalar(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ...
72
+ @overload
73
+ def _from_ctypes_scalar(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ...
74
+ @overload
75
+ def _from_ctypes_scalar(t: type[ct.c_float]) -> np.dtype[np.float32]: ...
76
+ @overload
77
+ def _from_ctypes_scalar(t: type[ct.c_double]) -> np.dtype[np.float64]: ...
78
+ @overload
79
+ def _from_ctypes_scalar(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ...
80
+ @overload
81
+ def _from_ctypes_scalar(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ...
82
+ @overload
83
+ def _from_ctypes_scalar(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ...
python/user_packages/Python313/site-packages/numpy/_core/_exceptions.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various richly-typed exceptions, that also help us deal with string formatting
3
+ in python where it's easier.
4
+
5
+ By putting the formatting in `__str__`, we also avoid paying the cost for
6
+ users who silence the exceptions.
7
+ """
8
+
9
+ def _unpack_tuple(tup):
10
+ if len(tup) == 1:
11
+ return tup[0]
12
+ else:
13
+ return tup
14
+
15
+
16
+ def _display_as_base(cls):
17
+ """
18
+ A decorator that makes an exception class look like its base.
19
+
20
+ We use this to hide subclasses that are implementation details - the user
21
+ should catch the base type, which is what the traceback will show them.
22
+
23
+ Classes decorated with this decorator are subject to removal without a
24
+ deprecation warning.
25
+ """
26
+ assert issubclass(cls, Exception)
27
+ cls.__name__ = cls.__base__.__name__
28
+ return cls
29
+
30
+
31
+ class UFuncTypeError(TypeError):
32
+ """ Base class for all ufunc exceptions """
33
+ def __init__(self, ufunc):
34
+ self.ufunc = ufunc
35
+
36
+
37
+ @_display_as_base
38
+ class _UFuncNoLoopError(UFuncTypeError):
39
+ """ Thrown when a ufunc loop cannot be found """
40
+ def __init__(self, ufunc, dtypes):
41
+ super().__init__(ufunc)
42
+ self.dtypes = tuple(dtypes)
43
+
44
+ def __str__(self):
45
+ return (
46
+ f"ufunc {self.ufunc.__name__!r} did not contain a loop with signature "
47
+ f"matching types {_unpack_tuple(self.dtypes[:self.ufunc.nin])!r} "
48
+ f"-> {_unpack_tuple(self.dtypes[self.ufunc.nin:])!r}"
49
+ )
50
+
51
+
52
+ @_display_as_base
53
+ class _UFuncBinaryResolutionError(_UFuncNoLoopError):
54
+ """ Thrown when a binary resolution fails """
55
+ def __init__(self, ufunc, dtypes):
56
+ super().__init__(ufunc, dtypes)
57
+ assert len(self.dtypes) == 2
58
+
59
+ def __str__(self):
60
+ return (
61
+ "ufunc {!r} cannot use operands with types {!r} and {!r}"
62
+ ).format(
63
+ self.ufunc.__name__, *self.dtypes
64
+ )
65
+
66
+
67
+ @_display_as_base
68
+ class _UFuncCastingError(UFuncTypeError):
69
+ def __init__(self, ufunc, casting, from_, to):
70
+ super().__init__(ufunc)
71
+ self.casting = casting
72
+ self.from_ = from_
73
+ self.to = to
74
+
75
+
76
+ @_display_as_base
77
+ class _UFuncInputCastingError(_UFuncCastingError):
78
+ """ Thrown when a ufunc input cannot be casted """
79
+ def __init__(self, ufunc, casting, from_, to, i):
80
+ super().__init__(ufunc, casting, from_, to)
81
+ self.in_i = i
82
+
83
+ def __str__(self):
84
+ # only show the number if more than one input exists
85
+ i_str = f"{self.in_i} " if self.ufunc.nin != 1 else ""
86
+ return (
87
+ f"Cannot cast ufunc {self.ufunc.__name__!r} input {i_str}from "
88
+ f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
89
+ )
90
+
91
+
92
+ @_display_as_base
93
+ class _UFuncOutputCastingError(_UFuncCastingError):
94
+ """ Thrown when a ufunc output cannot be casted """
95
+ def __init__(self, ufunc, casting, from_, to, i):
96
+ super().__init__(ufunc, casting, from_, to)
97
+ self.out_i = i
98
+
99
+ def __str__(self):
100
+ # only show the number if more than one output exists
101
+ i_str = f"{self.out_i} " if self.ufunc.nout != 1 else ""
102
+ return (
103
+ f"Cannot cast ufunc {self.ufunc.__name__!r} output {i_str}from "
104
+ f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
105
+ )
106
+
107
+
108
+ @_display_as_base
109
+ class _ArrayMemoryError(MemoryError):
110
+ """ Thrown when an array cannot be allocated"""
111
+ def __init__(self, shape, dtype):
112
+ self.shape = shape
113
+ self.dtype = dtype
114
+
115
+ @property
116
+ def _total_size(self):
117
+ num_bytes = self.dtype.itemsize
118
+ for dim in self.shape:
119
+ num_bytes *= dim
120
+ return num_bytes
121
+
122
+ @staticmethod
123
+ def _size_to_string(num_bytes):
124
+ """ Convert a number of bytes into a binary size string """
125
+
126
+ # https://en.wikipedia.org/wiki/Binary_prefix
127
+ LOG2_STEP = 10
128
+ STEP = 1024
129
+ units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
130
+
131
+ unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP
132
+ unit_val = 1 << (unit_i * LOG2_STEP)
133
+ n_units = num_bytes / unit_val
134
+ del unit_val
135
+
136
+ # ensure we pick a unit that is correct after rounding
137
+ if round(n_units) == STEP:
138
+ unit_i += 1
139
+ n_units /= STEP
140
+
141
+ # deal with sizes so large that we don't have units for them
142
+ if unit_i >= len(units):
143
+ new_unit_i = len(units) - 1
144
+ n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP)
145
+ unit_i = new_unit_i
146
+
147
+ unit_name = units[unit_i]
148
+ # format with a sensible number of digits
149
+ if unit_i == 0:
150
+ # no decimal point on bytes
151
+ return f'{n_units:.0f} {unit_name}'
152
+ elif round(n_units) < 1000:
153
+ # 3 significant figures, if none are dropped to the left of the .
154
+ return f'{n_units:#.3g} {unit_name}'
155
+ else:
156
+ # just give all the digits otherwise
157
+ return f'{n_units:#.0f} {unit_name}'
158
+
159
+ def __str__(self):
160
+ size_str = self._size_to_string(self._total_size)
161
+ return (f"Unable to allocate {size_str} for an array with shape "
162
+ f"{self.shape} and data type {self.dtype}")
python/user_packages/Python313/site-packages/numpy/_core/_exceptions.pyi ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, Final, TypeVar, overload
3
+
4
+ import numpy as np
5
+ from numpy import _CastingKind
6
+
7
+ ###
8
+
9
+ _T = TypeVar("_T")
10
+ _TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, *tuple[Any, ...]])
11
+ _ExceptionT = TypeVar("_ExceptionT", bound=Exception)
12
+
13
+ ###
14
+
15
+ class UFuncTypeError(TypeError):
16
+ ufunc: Final[np.ufunc]
17
+ def __init__(self, /, ufunc: np.ufunc) -> None: ...
18
+
19
+ class _UFuncNoLoopError(UFuncTypeError):
20
+ dtypes: tuple[np.dtype, ...]
21
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
22
+
23
+ class _UFuncBinaryResolutionError(_UFuncNoLoopError):
24
+ dtypes: tuple[np.dtype, np.dtype]
25
+ def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
26
+
27
+ class _UFuncCastingError(UFuncTypeError):
28
+ casting: Final[_CastingKind]
29
+ from_: Final[np.dtype]
30
+ to: Final[np.dtype]
31
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype) -> None: ...
32
+
33
+ class _UFuncInputCastingError(_UFuncCastingError):
34
+ in_i: Final[int]
35
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
36
+
37
+ class _UFuncOutputCastingError(_UFuncCastingError):
38
+ out_i: Final[int]
39
+ def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
40
+
41
+ class _ArrayMemoryError(MemoryError):
42
+ shape: tuple[int, ...]
43
+ dtype: np.dtype
44
+ def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype) -> None: ...
45
+ @property
46
+ def _total_size(self) -> int: ...
47
+ @staticmethod
48
+ def _size_to_string(num_bytes: int) -> str: ...
49
+
50
+ @overload
51
+ def _unpack_tuple(tup: tuple[_T]) -> _T: ...
52
+ @overload
53
+ def _unpack_tuple(tup: _TupleT) -> _TupleT: ...
54
+ def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ...
python/user_packages/Python313/site-packages/numpy/_core/_internal.py ADDED
@@ -0,0 +1,968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A place for internal code
3
+
4
+ Some things are more easily handled Python.
5
+
6
+ """
7
+ import ast
8
+ import math
9
+ import re
10
+ import sys
11
+ import warnings
12
+
13
+ from numpy import _NoValue
14
+ from numpy.exceptions import DTypePromotionError
15
+
16
+ from .multiarray import StringDType, array, dtype, promote_types
17
+
18
+ try:
19
+ import ctypes
20
+ except ImportError:
21
+ ctypes = None
22
+
23
+ IS_PYPY = sys.implementation.name == 'pypy'
24
+
25
+ if sys.byteorder == 'little':
26
+ _nbo = '<'
27
+ else:
28
+ _nbo = '>'
29
+
30
+ def _makenames_list(adict, align):
31
+ allfields = []
32
+
33
+ for fname, obj in adict.items():
34
+ n = len(obj)
35
+ if not isinstance(obj, tuple) or n not in (2, 3):
36
+ raise ValueError("entry not a 2- or 3- tuple")
37
+ if n > 2 and obj[2] == fname:
38
+ continue
39
+ num = int(obj[1])
40
+ if num < 0:
41
+ raise ValueError("invalid offset.")
42
+ format = dtype(obj[0], align=align)
43
+ if n > 2:
44
+ title = obj[2]
45
+ else:
46
+ title = None
47
+ allfields.append((fname, format, num, title))
48
+ # sort by offsets
49
+ allfields.sort(key=lambda x: x[2])
50
+ names = [x[0] for x in allfields]
51
+ formats = [x[1] for x in allfields]
52
+ offsets = [x[2] for x in allfields]
53
+ titles = [x[3] for x in allfields]
54
+
55
+ return names, formats, offsets, titles
56
+
57
+ # Called in PyArray_DescrConverter function when
58
+ # a dictionary without "names" and "formats"
59
+ # fields is used as a data-type descriptor.
60
+ def _usefields(adict, align):
61
+ try:
62
+ names = adict[-1]
63
+ except KeyError:
64
+ names = None
65
+ if names is None:
66
+ names, formats, offsets, titles = _makenames_list(adict, align)
67
+ else:
68
+ formats = []
69
+ offsets = []
70
+ titles = []
71
+ for name in names:
72
+ res = adict[name]
73
+ formats.append(res[0])
74
+ offsets.append(res[1])
75
+ if len(res) > 2:
76
+ titles.append(res[2])
77
+ else:
78
+ titles.append(None)
79
+
80
+ return dtype({"names": names,
81
+ "formats": formats,
82
+ "offsets": offsets,
83
+ "titles": titles}, align)
84
+
85
+
86
+ # construct an array_protocol descriptor list
87
+ # from the fields attribute of a descriptor
88
+ # This calls itself recursively but should eventually hit
89
+ # a descriptor that has no fields and then return
90
+ # a simple typestring
91
+
92
+ def _array_descr(descriptor):
93
+ fields = descriptor.fields
94
+ if fields is None:
95
+ subdtype = descriptor.subdtype
96
+ if subdtype is None:
97
+ if descriptor.metadata is None:
98
+ return descriptor.str
99
+ else:
100
+ new = descriptor.metadata.copy()
101
+ if new:
102
+ return (descriptor.str, new)
103
+ else:
104
+ return descriptor.str
105
+ else:
106
+ return (_array_descr(subdtype[0]), subdtype[1])
107
+
108
+ names = descriptor.names
109
+ ordered_fields = [fields[x] + (x,) for x in names]
110
+ result = []
111
+ offset = 0
112
+ for field in ordered_fields:
113
+ if field[1] > offset:
114
+ num = field[1] - offset
115
+ result.append(('', f'|V{num}'))
116
+ offset += num
117
+ elif field[1] < offset:
118
+ raise ValueError(
119
+ "dtype.descr is not defined for types with overlapping or "
120
+ "out-of-order fields")
121
+ if len(field) > 3:
122
+ name = (field[2], field[3])
123
+ else:
124
+ name = field[2]
125
+ if field[0].subdtype:
126
+ tup = (name, _array_descr(field[0].subdtype[0]),
127
+ field[0].subdtype[1])
128
+ else:
129
+ tup = (name, _array_descr(field[0]))
130
+ offset += field[0].itemsize
131
+ result.append(tup)
132
+
133
+ if descriptor.itemsize > offset:
134
+ num = descriptor.itemsize - offset
135
+ result.append(('', f'|V{num}'))
136
+
137
+ return result
138
+
139
+
140
+ # format_re was originally from numarray by J. Todd Miller
141
+
142
+ format_re = re.compile(r'(?P<order1>[<>|=]?)'
143
+ r'(?P<repeats> *[(]?[ ,0-9]*[)]? *)'
144
+ r'(?P<order2>[<>|=]?)'
145
+ r'(?P<dtype>[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)')
146
+ sep_re = re.compile(r'\s*,\s*')
147
+ space_re = re.compile(r'\s+$')
148
+
149
+ # astr is a string (perhaps comma separated)
150
+
151
+ _convorder = {'=': _nbo}
152
+
153
+ def _commastring(astr):
154
+ startindex = 0
155
+ result = []
156
+ islist = False
157
+ while startindex < len(astr):
158
+ mo = format_re.match(astr, pos=startindex)
159
+ try:
160
+ (order1, repeats, order2, dtype) = mo.groups()
161
+ except (TypeError, AttributeError):
162
+ raise ValueError(
163
+ f'format number {len(result) + 1} of "{astr}" is not recognized'
164
+ ) from None
165
+ startindex = mo.end()
166
+ # Separator or ending padding
167
+ if startindex < len(astr):
168
+ if space_re.match(astr, pos=startindex):
169
+ startindex = len(astr)
170
+ else:
171
+ mo = sep_re.match(astr, pos=startindex)
172
+ if not mo:
173
+ raise ValueError(
174
+ 'format number %d of "%s" is not recognized' %
175
+ (len(result) + 1, astr))
176
+ startindex = mo.end()
177
+ islist = True
178
+
179
+ if order2 == '':
180
+ order = order1
181
+ elif order1 == '':
182
+ order = order2
183
+ else:
184
+ order1 = _convorder.get(order1, order1)
185
+ order2 = _convorder.get(order2, order2)
186
+ if (order1 != order2):
187
+ raise ValueError(
188
+ f'inconsistent byte-order specification {order1} and {order2}')
189
+ order = order1
190
+
191
+ if order in ('|', '=', _nbo):
192
+ order = ''
193
+ dtype = order + dtype
194
+ if repeats == '':
195
+ newitem = dtype
196
+ else:
197
+ if (repeats[0] == "(" and repeats[-1] == ")"
198
+ and repeats[1:-1].strip() != ""
199
+ and "," not in repeats):
200
+ warnings.warn(
201
+ 'Passing in a parenthesized single number for repeats '
202
+ 'is deprecated; pass either a single number or indicate '
203
+ 'a tuple with a comma, like "(2,)".', DeprecationWarning,
204
+ stacklevel=2)
205
+ newitem = (dtype, ast.literal_eval(repeats))
206
+
207
+ result.append(newitem)
208
+
209
+ return result if islist else result[0]
210
+
211
+ class dummy_ctype:
212
+
213
+ def __init__(self, cls):
214
+ self._cls = cls
215
+
216
+ def __mul__(self, other):
217
+ return self
218
+
219
+ def __call__(self, *other):
220
+ return self._cls(other)
221
+
222
+ def __eq__(self, other):
223
+ return self._cls == other._cls
224
+
225
+ def __ne__(self, other):
226
+ return self._cls != other._cls
227
+
228
+ def _getintp_ctype():
229
+ val = _getintp_ctype.cache
230
+ if val is not None:
231
+ return val
232
+ if ctypes is None:
233
+ import numpy as np
234
+ val = dummy_ctype(np.intp)
235
+ else:
236
+ char = dtype('n').char
237
+ if char == 'i':
238
+ val = ctypes.c_int
239
+ elif char == 'l':
240
+ val = ctypes.c_long
241
+ elif char == 'q':
242
+ val = ctypes.c_longlong
243
+ else:
244
+ val = ctypes.c_long
245
+ _getintp_ctype.cache = val
246
+ return val
247
+
248
+
249
+ _getintp_ctype.cache = None
250
+
251
+ # Used for .ctypes attribute of ndarray
252
+
253
+ class _missing_ctypes:
254
+ def cast(self, num, obj):
255
+ return num.value
256
+
257
+ class c_void_p:
258
+ def __init__(self, ptr):
259
+ self.value = ptr
260
+
261
+
262
+ class _ctypes:
263
+ def __init__(self, array, ptr=None):
264
+ self._arr = array
265
+
266
+ if ctypes:
267
+ self._ctypes = ctypes
268
+ self._data = self._ctypes.c_void_p(ptr)
269
+ else:
270
+ # fake a pointer-like object that holds onto the reference
271
+ self._ctypes = _missing_ctypes()
272
+ self._data = self._ctypes.c_void_p(ptr)
273
+ self._data._objects = array
274
+
275
+ if self._arr.ndim == 0:
276
+ self._zerod = True
277
+ else:
278
+ self._zerod = False
279
+
280
+ def data_as(self, obj):
281
+ """
282
+ Return the data pointer cast to a particular c-types object.
283
+ For example, calling ``self._as_parameter_`` is equivalent to
284
+ ``self.data_as(ctypes.c_void_p)``. Perhaps you want to use
285
+ the data as a pointer to a ctypes array of floating-point data:
286
+ ``self.data_as(ctypes.POINTER(ctypes.c_double))``.
287
+
288
+ The returned pointer will keep a reference to the array.
289
+ """
290
+ # _ctypes.cast function causes a circular reference of self._data in
291
+ # self._data._objects. Attributes of self._data cannot be released
292
+ # until gc.collect is called. Make a copy of the pointer first then
293
+ # let it hold the array reference. This is a workaround to circumvent
294
+ # the CPython bug https://bugs.python.org/issue12836.
295
+ ptr = self._ctypes.cast(self._data, obj)
296
+ ptr._arr = self._arr
297
+ return ptr
298
+
299
+ def shape_as(self, obj):
300
+ """
301
+ Return the shape tuple as an array of some other c-types
302
+ type. For example: ``self.shape_as(ctypes.c_short)``.
303
+ """
304
+ if self._zerod:
305
+ return None
306
+ return (obj * self._arr.ndim)(*self._arr.shape)
307
+
308
+ def strides_as(self, obj):
309
+ """
310
+ Return the strides tuple as an array of some other
311
+ c-types type. For example: ``self.strides_as(ctypes.c_longlong)``.
312
+ """
313
+ if self._zerod:
314
+ return None
315
+ return (obj * self._arr.ndim)(*self._arr.strides)
316
+
317
+ @property
318
+ def data(self):
319
+ """
320
+ A pointer to the memory area of the array as a Python integer.
321
+ This memory area may contain data that is not aligned, or not in
322
+ correct byte-order. The memory area may not even be writeable.
323
+ The array flags and data-type of this array should be respected
324
+ when passing this attribute to arbitrary C-code to avoid trouble
325
+ that can include Python crashing. User Beware! The value of this
326
+ attribute is exactly the same as:
327
+ ``self._array_interface_['data'][0]``.
328
+
329
+ Note that unlike ``data_as``, a reference won't be kept to the array:
330
+ code like ``ctypes.c_void_p((a + b).ctypes.data)`` will result in a
331
+ pointer to a deallocated array, and should be spelt
332
+ ``(a + b).ctypes.data_as(ctypes.c_void_p)``
333
+ """
334
+ return self._data.value
335
+
336
+ @property
337
+ def shape(self):
338
+ """
339
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
340
+ the basetype is the C-integer corresponding to ``dtype('p')`` on this
341
+ platform (see `~numpy.ctypeslib.c_intp`). This base-type could be
342
+ `ctypes.c_int`, `ctypes.c_long`, or `ctypes.c_longlong` depending on
343
+ the platform. The ctypes array contains the shape of
344
+ the underlying array.
345
+ """
346
+ return self.shape_as(_getintp_ctype())
347
+
348
+ @property
349
+ def strides(self):
350
+ """
351
+ (c_intp*self.ndim): A ctypes array of length self.ndim where
352
+ the basetype is the same as for the shape attribute. This ctypes
353
+ array contains the strides information from the underlying array.
354
+ This strides information is important for showing how many bytes
355
+ must be jumped to get to the next element in the array.
356
+ """
357
+ return self.strides_as(_getintp_ctype())
358
+
359
+ @property
360
+ def _as_parameter_(self):
361
+ """
362
+ Overrides the ctypes semi-magic method
363
+
364
+ Enables `c_func(some_array.ctypes)`
365
+ """
366
+ return self.data_as(ctypes.c_void_p)
367
+
368
+
369
+ def _newnames(datatype, order):
370
+ """
371
+ Given a datatype and an order object, return a new names tuple, with the
372
+ order indicated
373
+ """
374
+ oldnames = datatype.names
375
+ nameslist = list(oldnames)
376
+ if isinstance(order, str):
377
+ order = [order]
378
+ seen = set()
379
+ if isinstance(order, (list, tuple)):
380
+ for name in order:
381
+ try:
382
+ nameslist.remove(name)
383
+ except ValueError:
384
+ if name in seen:
385
+ raise ValueError(f"duplicate field name: {name}") from None
386
+ else:
387
+ raise ValueError(f"unknown field name: {name}") from None
388
+ seen.add(name)
389
+ return tuple(list(order) + nameslist)
390
+ raise ValueError(f"unsupported order value: {order}")
391
+
392
+ def _copy_fields(ary):
393
+ """Return copy of structured array with padding between fields removed.
394
+
395
+ Parameters
396
+ ----------
397
+ ary : ndarray
398
+ Structured array from which to remove padding bytes
399
+
400
+ Returns
401
+ -------
402
+ ary_copy : ndarray
403
+ Copy of ary with padding bytes removed
404
+ """
405
+ dt = ary.dtype
406
+ copy_dtype = {'names': dt.names,
407
+ 'formats': [dt.fields[name][0] for name in dt.names]}
408
+ return array(ary, dtype=copy_dtype, copy=True)
409
+
410
+ def _promote_fields(dt1, dt2):
411
+ """ Perform type promotion for two structured dtypes.
412
+
413
+ Parameters
414
+ ----------
415
+ dt1 : structured dtype
416
+ First dtype.
417
+ dt2 : structured dtype
418
+ Second dtype.
419
+
420
+ Returns
421
+ -------
422
+ out : dtype
423
+ The promoted dtype
424
+
425
+ Notes
426
+ -----
427
+ If one of the inputs is aligned, the result will be. The titles of
428
+ both descriptors must match (point to the same field).
429
+ """
430
+ # Both must be structured and have the same names in the same order
431
+ if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names:
432
+ raise DTypePromotionError(
433
+ f"field names `{dt1.names}` and `{dt2.names}` mismatch.")
434
+
435
+ # if both are identical, we can (maybe!) just return the same dtype.
436
+ identical = dt1 is dt2
437
+ new_fields = []
438
+ for name in dt1.names:
439
+ field1 = dt1.fields[name]
440
+ field2 = dt2.fields[name]
441
+ new_descr = promote_types(field1[0], field2[0])
442
+ identical = identical and new_descr is field1[0]
443
+
444
+ # Check that the titles match (if given):
445
+ if field1[2:] != field2[2:]:
446
+ raise DTypePromotionError(
447
+ f"field titles of field '{name}' mismatch")
448
+ if len(field1) == 2:
449
+ new_fields.append((name, new_descr))
450
+ else:
451
+ new_fields.append(((field1[2], name), new_descr))
452
+
453
+ res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct)
454
+
455
+ # Might as well preserve identity (and metadata) if the dtype is identical
456
+ # and the itemsize, offsets are also unmodified. This could probably be
457
+ # sped up, but also probably just be removed entirely.
458
+ if identical and res.itemsize == dt1.itemsize:
459
+ for name in dt1.names:
460
+ if dt1.fields[name][1] != res.fields[name][1]:
461
+ return res # the dtype changed.
462
+ return dt1
463
+
464
+ return res
465
+
466
+
467
+ def _getfield_is_safe(oldtype, newtype, offset):
468
+ """ Checks safety of getfield for object arrays.
469
+
470
+ As in _view_is_safe, we need to check that memory containing objects is not
471
+ reinterpreted as a non-object datatype and vice versa.
472
+
473
+ Parameters
474
+ ----------
475
+ oldtype : data-type
476
+ Data type of the original ndarray.
477
+ newtype : data-type
478
+ Data type of the field being accessed by ndarray.getfield
479
+ offset : int
480
+ Offset of the field being accessed by ndarray.getfield
481
+
482
+ Raises
483
+ ------
484
+ TypeError
485
+ If the field access is invalid
486
+
487
+ """
488
+ if newtype.hasobject or oldtype.hasobject:
489
+ if offset == 0 and newtype == oldtype:
490
+ return
491
+ if oldtype.names is not None:
492
+ for name in oldtype.names:
493
+ if (oldtype.fields[name][1] == offset and
494
+ oldtype.fields[name][0] == newtype):
495
+ return
496
+ raise TypeError("Cannot get/set field of an object array")
497
+ return
498
+
499
+ def _view_is_safe(oldtype, newtype):
500
+ """ Checks safety of a view involving object arrays, for example when
501
+ doing::
502
+
503
+ np.zeros(10, dtype=oldtype).view(newtype)
504
+
505
+ Parameters
506
+ ----------
507
+ oldtype : data-type
508
+ Data type of original ndarray
509
+ newtype : data-type
510
+ Data type of the view
511
+
512
+ Raises
513
+ ------
514
+ TypeError
515
+ If the new type is incompatible with the old type.
516
+
517
+ """
518
+
519
+ # if the types are equivalent, there is no problem.
520
+ # for example: dtype((np.record, 'i4,i4')) == dtype((np.void, 'i4,i4'))
521
+ if oldtype == newtype:
522
+ return
523
+
524
+ if newtype.hasobject or oldtype.hasobject:
525
+ raise TypeError("Cannot change data-type for array of references.")
526
+ return
527
+
528
+
529
+ # Given a string containing a PEP 3118 format specifier,
530
+ # construct a NumPy dtype
531
+
532
+ _pep3118_native_map = {
533
+ '?': '?',
534
+ 'c': 'S1',
535
+ 'b': 'b',
536
+ 'B': 'B',
537
+ 'h': 'h',
538
+ 'H': 'H',
539
+ 'i': 'i',
540
+ 'I': 'I',
541
+ 'l': 'l',
542
+ 'L': 'L',
543
+ 'q': 'q',
544
+ 'Q': 'Q',
545
+ 'e': 'e',
546
+ 'f': 'f',
547
+ 'd': 'd',
548
+ 'g': 'g',
549
+ 'Zf': 'F',
550
+ 'Zd': 'D',
551
+ 'Zg': 'G',
552
+ 's': 'S',
553
+ 'w': 'U',
554
+ 'O': 'O',
555
+ 'x': 'V', # padding
556
+ }
557
+ _pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
558
+
559
+ _pep3118_standard_map = {
560
+ '?': '?',
561
+ 'c': 'S1',
562
+ 'b': 'b',
563
+ 'B': 'B',
564
+ 'h': 'i2',
565
+ 'H': 'u2',
566
+ 'i': 'i4',
567
+ 'I': 'u4',
568
+ 'l': 'i4',
569
+ 'L': 'u4',
570
+ 'q': 'i8',
571
+ 'Q': 'u8',
572
+ 'e': 'f2',
573
+ 'f': 'f',
574
+ 'd': 'd',
575
+ 'Zf': 'F',
576
+ 'Zd': 'D',
577
+ 's': 'S',
578
+ 'w': 'U',
579
+ 'O': 'O',
580
+ 'x': 'V', # padding
581
+ }
582
+ _pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
583
+
584
+ _pep3118_unsupported_map = {
585
+ 'u': 'UCS-2 strings',
586
+ '&': 'pointers',
587
+ 't': 'bitfields',
588
+ 'X': 'function pointers',
589
+ }
590
+
591
+ class _Stream:
592
+ def __init__(self, s):
593
+ self.s = s
594
+ self.byteorder = '@'
595
+
596
+ def advance(self, n):
597
+ res = self.s[:n]
598
+ self.s = self.s[n:]
599
+ return res
600
+
601
+ def consume(self, c):
602
+ if self.s[:len(c)] == c:
603
+ self.advance(len(c))
604
+ return True
605
+ return False
606
+
607
+ def consume_until(self, c):
608
+ if callable(c):
609
+ i = 0
610
+ while i < len(self.s) and not c(self.s[i]):
611
+ i = i + 1
612
+ return self.advance(i)
613
+ else:
614
+ i = self.s.index(c)
615
+ res = self.advance(i)
616
+ self.advance(len(c))
617
+ return res
618
+
619
+ @property
620
+ def next(self):
621
+ return self.s[0]
622
+
623
+ def __bool__(self):
624
+ return bool(self.s)
625
+
626
+
627
+ def _dtype_from_pep3118(spec):
628
+ stream = _Stream(spec)
629
+ dtype, align = __dtype_from_pep3118(stream, is_subdtype=False)
630
+ return dtype
631
+
632
+ def __dtype_from_pep3118(stream, is_subdtype):
633
+ field_spec = {
634
+ 'names': [],
635
+ 'formats': [],
636
+ 'offsets': [],
637
+ 'itemsize': 0
638
+ }
639
+ offset = 0
640
+ common_alignment = 1
641
+ is_padding = False
642
+
643
+ # Parse spec
644
+ while stream:
645
+ value = None
646
+
647
+ # End of structure, bail out to upper level
648
+ if stream.consume('}'):
649
+ break
650
+
651
+ # Sub-arrays (1)
652
+ shape = None
653
+ if stream.consume('('):
654
+ shape = stream.consume_until(')')
655
+ shape = tuple(map(int, shape.split(',')))
656
+
657
+ # Byte order
658
+ if stream.next in ('@', '=', '<', '>', '^', '!'):
659
+ byteorder = stream.advance(1)
660
+ if byteorder == '!':
661
+ byteorder = '>'
662
+ stream.byteorder = byteorder
663
+
664
+ # Byte order characters also control native vs. standard type sizes
665
+ if stream.byteorder in ('@', '^'):
666
+ type_map = _pep3118_native_map
667
+ type_map_chars = _pep3118_native_typechars
668
+ else:
669
+ type_map = _pep3118_standard_map
670
+ type_map_chars = _pep3118_standard_typechars
671
+
672
+ # Item sizes
673
+ itemsize_str = stream.consume_until(lambda c: not c.isdigit())
674
+ if itemsize_str:
675
+ itemsize = int(itemsize_str)
676
+ else:
677
+ itemsize = 1
678
+
679
+ # Data types
680
+ is_padding = False
681
+
682
+ if stream.consume('T{'):
683
+ value, align = __dtype_from_pep3118(
684
+ stream, is_subdtype=True)
685
+ elif stream.next in type_map_chars:
686
+ if stream.next == 'Z':
687
+ typechar = stream.advance(2)
688
+ else:
689
+ typechar = stream.advance(1)
690
+
691
+ is_padding = (typechar == 'x')
692
+ dtypechar = type_map[typechar]
693
+ if dtypechar in 'USV':
694
+ dtypechar += '%d' % itemsize
695
+ itemsize = 1
696
+ numpy_byteorder = {'@': '=', '^': '='}.get(
697
+ stream.byteorder, stream.byteorder)
698
+ value = dtype(numpy_byteorder + dtypechar)
699
+ align = value.alignment
700
+ elif stream.next in _pep3118_unsupported_map:
701
+ desc = _pep3118_unsupported_map[stream.next]
702
+ raise NotImplementedError(
703
+ f"Unrepresentable PEP 3118 data type {stream.next!r} ({desc})")
704
+ else:
705
+ raise ValueError(
706
+ f"Unknown PEP 3118 data type specifier {stream.s!r}"
707
+ )
708
+
709
+ #
710
+ # Native alignment may require padding
711
+ #
712
+ # Here we assume that the presence of a '@' character implicitly
713
+ # implies that the start of the array is *already* aligned.
714
+ #
715
+ extra_offset = 0
716
+ if stream.byteorder == '@':
717
+ start_padding = (-offset) % align
718
+ intra_padding = (-value.itemsize) % align
719
+
720
+ offset += start_padding
721
+
722
+ if intra_padding != 0:
723
+ if itemsize > 1 or (shape is not None and _prod(shape) > 1):
724
+ # Inject internal padding to the end of the sub-item
725
+ value = _add_trailing_padding(value, intra_padding)
726
+ else:
727
+ # We can postpone the injection of internal padding,
728
+ # as the item appears at most once
729
+ extra_offset += intra_padding
730
+
731
+ # Update common alignment
732
+ common_alignment = _lcm(align, common_alignment)
733
+
734
+ # Convert itemsize to sub-array
735
+ if itemsize != 1:
736
+ value = dtype((value, (itemsize,)))
737
+
738
+ # Sub-arrays (2)
739
+ if shape is not None:
740
+ value = dtype((value, shape))
741
+
742
+ # Field name
743
+ if stream.consume(':'):
744
+ name = stream.consume_until(':')
745
+ else:
746
+ name = None
747
+
748
+ if not (is_padding and name is None):
749
+ if name is not None and name in field_spec['names']:
750
+ raise RuntimeError(
751
+ f"Duplicate field name '{name}' in PEP3118 format"
752
+ )
753
+ field_spec['names'].append(name)
754
+ field_spec['formats'].append(value)
755
+ field_spec['offsets'].append(offset)
756
+
757
+ offset += value.itemsize
758
+ offset += extra_offset
759
+
760
+ field_spec['itemsize'] = offset
761
+
762
+ # extra final padding for aligned types
763
+ if stream.byteorder == '@':
764
+ field_spec['itemsize'] += (-offset) % common_alignment
765
+
766
+ # Check if this was a simple 1-item type, and unwrap it
767
+ if (field_spec['names'] == [None]
768
+ and field_spec['offsets'][0] == 0
769
+ and field_spec['itemsize'] == field_spec['formats'][0].itemsize
770
+ and not is_subdtype):
771
+ ret = field_spec['formats'][0]
772
+ else:
773
+ _fix_names(field_spec)
774
+ ret = dtype(field_spec)
775
+
776
+ # Finished
777
+ return ret, common_alignment
778
+
779
+ def _fix_names(field_spec):
780
+ """ Replace names which are None with the next unused f%d name """
781
+ names = field_spec['names']
782
+ for i, name in enumerate(names):
783
+ if name is not None:
784
+ continue
785
+
786
+ j = 0
787
+ while True:
788
+ name = f'f{j}'
789
+ if name not in names:
790
+ break
791
+ j = j + 1
792
+ names[i] = name
793
+
794
+ def _add_trailing_padding(value, padding):
795
+ """Inject the specified number of padding bytes at the end of a dtype"""
796
+ if value.fields is None:
797
+ field_spec = {
798
+ 'names': ['f0'],
799
+ 'formats': [value],
800
+ 'offsets': [0],
801
+ 'itemsize': value.itemsize
802
+ }
803
+ else:
804
+ fields = value.fields
805
+ names = value.names
806
+ field_spec = {
807
+ 'names': names,
808
+ 'formats': [fields[name][0] for name in names],
809
+ 'offsets': [fields[name][1] for name in names],
810
+ 'itemsize': value.itemsize
811
+ }
812
+
813
+ field_spec['itemsize'] += padding
814
+ return dtype(field_spec)
815
+
816
+ def _prod(a):
817
+ p = 1
818
+ for x in a:
819
+ p *= x
820
+ return p
821
+
822
+ def _gcd(a, b):
823
+ """Calculate the greatest common divisor of a and b"""
824
+ if not (math.isfinite(a) and math.isfinite(b)):
825
+ raise ValueError('Can only find greatest common divisor of '
826
+ f'finite arguments, found "{a}" and "{b}"')
827
+ while b:
828
+ a, b = b, a % b
829
+ return a
830
+
831
+ def _lcm(a, b):
832
+ return a // _gcd(a, b) * b
833
+
834
+ def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
835
+ """ Format the error message for when __array_ufunc__ gives up. """
836
+ args_string = ', '.join([f'{arg!r}' for arg in inputs] +
837
+ [f'{k}={v!r}'
838
+ for k, v in kwargs.items()])
839
+ args = inputs + kwargs.get('out', ())
840
+ types_string = ', '.join(repr(type(arg).__name__) for arg in args)
841
+ return ('operand type(s) all returned NotImplemented from '
842
+ f'__array_ufunc__({ufunc!r}, {method!r}, {args_string}): {types_string}'
843
+ )
844
+
845
+
846
+ def array_function_errmsg_formatter(public_api, types):
847
+ """ Format the error message for when __array_ufunc__ gives up. """
848
+ func_name = f'{public_api.__module__}.{public_api.__name__}'
849
+ return (f"no implementation found for '{func_name}' on types that implement "
850
+ f'__array_function__: {list(types)}')
851
+
852
+
853
+ def _ufunc_doc_signature_formatter(ufunc):
854
+ """
855
+ Builds a signature string which resembles PEP 457
856
+
857
+ This is used to construct the first line of the docstring
858
+
859
+ Keep in sync with `_ufunc_inspect_signature_builder`.
860
+ """
861
+
862
+ # input arguments are simple
863
+ if ufunc.nin == 1:
864
+ in_args = 'x'
865
+ else:
866
+ in_args = ', '.join(f'x{i + 1}' for i in range(ufunc.nin))
867
+
868
+ # output arguments are both keyword or positional
869
+ if ufunc.nout == 0:
870
+ out_args = ', /, out=()'
871
+ elif ufunc.nout == 1:
872
+ out_args = ', /, out=None'
873
+ else:
874
+ out_args = '[, {positional}], / [, out={default}]'.format(
875
+ positional=', '.join(
876
+ f'out{i + 1}' for i in range(ufunc.nout)),
877
+ default=repr((None,) * ufunc.nout)
878
+ )
879
+
880
+ # keyword only args depend on whether this is a gufunc
881
+ kwargs = (
882
+ ", casting='same_kind'"
883
+ ", order='K'"
884
+ ", dtype=None"
885
+ ", subok=True"
886
+ )
887
+
888
+ # NOTE: gufuncs may or may not support the `axis` parameter
889
+ if ufunc.signature is None:
890
+ kwargs = f", where=True{kwargs}[, signature]"
891
+ else:
892
+ kwargs += "[, signature, axes, axis]"
893
+
894
+ # join all the parts together
895
+ return f'{ufunc.__name__}({in_args}{out_args}, *{kwargs})'
896
+
897
+
898
+ def _ufunc_inspect_signature_builder(ufunc):
899
+ """
900
+ Builds a ``__signature__`` string.
901
+
902
+ Should be kept in sync with `_ufunc_doc_signature_formatter`.
903
+ """
904
+
905
+ from inspect import Parameter, Signature
906
+
907
+ params = []
908
+
909
+ # positional-only input parameters
910
+ if ufunc.nin == 1:
911
+ params.append(Parameter("x", Parameter.POSITIONAL_ONLY))
912
+ else:
913
+ params.extend(
914
+ Parameter(f"x{i}", Parameter.POSITIONAL_ONLY)
915
+ for i in range(1, ufunc.nin + 1)
916
+ )
917
+
918
+ # for the sake of simplicity, we only consider a single output parameter
919
+ if ufunc.nout == 1:
920
+ out_default = None
921
+ else:
922
+ out_default = (None,) * ufunc.nout
923
+ params.append(
924
+ Parameter("out", Parameter.POSITIONAL_OR_KEYWORD, default=out_default),
925
+ )
926
+
927
+ if ufunc.signature is None:
928
+ params.append(Parameter("where", Parameter.KEYWORD_ONLY, default=True))
929
+ else:
930
+ # NOTE: not all gufuncs support the `axis` parameters
931
+ params.append(Parameter("axes", Parameter.KEYWORD_ONLY, default=_NoValue))
932
+ params.append(Parameter("axis", Parameter.KEYWORD_ONLY, default=_NoValue))
933
+ params.append(Parameter("keepdims", Parameter.KEYWORD_ONLY, default=False))
934
+
935
+ params.extend((
936
+ Parameter("casting", Parameter.KEYWORD_ONLY, default='same_kind'),
937
+ Parameter("order", Parameter.KEYWORD_ONLY, default='K'),
938
+ Parameter("dtype", Parameter.KEYWORD_ONLY, default=None),
939
+ Parameter("subok", Parameter.KEYWORD_ONLY, default=True),
940
+ Parameter("signature", Parameter.KEYWORD_ONLY, default=None),
941
+ ))
942
+
943
+ return Signature(params)
944
+
945
+
946
+ def npy_ctypes_check(cls):
947
+ # determine if a class comes from ctypes, in order to work around
948
+ # a bug in the buffer protocol for those objects, bpo-10746
949
+ try:
950
+ # ctypes class are new-style, so have an __mro__. This probably fails
951
+ # for ctypes classes with multiple inheritance.
952
+ if IS_PYPY:
953
+ # (..., _ctypes.basics._CData, Bufferable, object)
954
+ ctype_base = cls.__mro__[-3]
955
+ else:
956
+ # # (..., _ctypes._CData, object)
957
+ ctype_base = cls.__mro__[-2]
958
+ # right now, they're part of the _ctypes module
959
+ return '_ctypes' in ctype_base.__module__
960
+ except Exception:
961
+ return False
962
+
963
+ # used to handle the _NoValue default argument for na_object
964
+ # in the C implementation of the __reduce__ method for stringdtype
965
+ def _convert_to_stringdtype_kwargs(coerce, na_object=_NoValue):
966
+ if na_object is _NoValue:
967
+ return StringDType(coerce=coerce)
968
+ return StringDType(coerce=coerce, na_object=na_object)
python/user_packages/Python313/site-packages/numpy/_core/_internal.pyi ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes as ct
2
+ import re
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any, Final, Generic, Self, overload
5
+ from typing_extensions import TypeVar
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+ from numpy.ctypeslib import c_intp
10
+
11
+ _CastT = TypeVar("_CastT", bound=ct._CanCastTo)
12
+ _T_co = TypeVar("_T_co", covariant=True)
13
+ _CT = TypeVar("_CT", bound=ct._CData)
14
+ _PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)
15
+
16
+ ###
17
+
18
+ IS_PYPY: Final[bool] = ...
19
+
20
+ format_re: Final[re.Pattern[str]] = ...
21
+ sep_re: Final[re.Pattern[str]] = ...
22
+ space_re: Final[re.Pattern[str]] = ...
23
+
24
+ ###
25
+
26
+ # TODO: Let the likes of `shape_as` and `strides_as` return `None`
27
+ # for 0D arrays once we've got shape-support
28
+
29
+ class _ctypes(Generic[_PT_co]):
30
+ @overload
31
+ def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
32
+ @overload
33
+ def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...
34
+
35
+ #
36
+ @property
37
+ def data(self) -> _PT_co: ...
38
+ @property
39
+ def shape(self) -> ct.Array[c_intp]: ...
40
+ @property
41
+ def strides(self) -> ct.Array[c_intp]: ...
42
+ @property
43
+ def _as_parameter_(self) -> ct.c_void_p: ...
44
+
45
+ #
46
+ def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
47
+ def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
48
+ def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
49
+
50
+ class dummy_ctype(Generic[_T_co]):
51
+ _cls: type[_T_co]
52
+
53
+ def __init__(self, /, cls: type[_T_co]) -> None: ...
54
+ def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
55
+ def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
56
+ def __mul__(self, other: object, /) -> Self: ...
57
+ def __call__(self, /, *other: object) -> _T_co: ...
58
+
59
+ def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
60
+ def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
61
+ def npy_ctypes_check(cls: type) -> bool: ...
python/user_packages/Python313/site-packages/numpy/_core/_methods.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Array methods which are called by both the C-code for the method
3
+ and the Python code for the NumPy-namespace function
4
+
5
+ """
6
+ import os
7
+ import pickle
8
+ import warnings
9
+ from contextlib import nullcontext
10
+
11
+ import numpy as np
12
+ from numpy._core import multiarray as mu, numerictypes as nt, umath as um
13
+ from numpy._core.multiarray import asanyarray
14
+ from numpy._globals import _NoValue
15
+
16
+ # save those O(100) nanoseconds!
17
+ bool_dt = mu.dtype("bool")
18
+ umr_maximum = um.maximum.reduce
19
+ umr_minimum = um.minimum.reduce
20
+ umr_sum = um.add.reduce
21
+ umr_prod = um.multiply.reduce
22
+ umr_bitwise_count = um.bitwise_count
23
+ umr_any = um.logical_or.reduce
24
+ umr_all = um.logical_and.reduce
25
+
26
+ # Complex types to -> (2,)float view for fast-path computation in _var()
27
+ _complex_to_float = {
28
+ nt.dtype(nt.csingle): nt.dtype(nt.single),
29
+ nt.dtype(nt.cdouble): nt.dtype(nt.double),
30
+ }
31
+ # Special case for windows: ensure double takes precedence
32
+ if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
33
+ _complex_to_float.update({
34
+ nt.dtype(nt.clongdouble): nt.dtype(nt.longdouble),
35
+ })
36
+
37
+ # avoid keyword arguments to speed up parsing, saves about 15%-20% for very
38
+ # small reductions
39
+ def _amax(a, axis=None, out=None, keepdims=False,
40
+ initial=_NoValue, where=True):
41
+ return umr_maximum(a, axis, None, out, keepdims, initial, where)
42
+
43
+ def _amin(a, axis=None, out=None, keepdims=False,
44
+ initial=_NoValue, where=True):
45
+ return umr_minimum(a, axis, None, out, keepdims, initial, where)
46
+
47
+ def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
48
+ initial=_NoValue, where=True):
49
+ return umr_sum(a, axis, dtype, out, keepdims, initial, where)
50
+
51
+ def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
52
+ initial=_NoValue, where=True):
53
+ return umr_prod(a, axis, dtype, out, keepdims, initial, where)
54
+
55
+ def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
56
+ # By default, return a boolean for any and all
57
+ if dtype is None:
58
+ dtype = bool_dt
59
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
60
+ if where is True:
61
+ return umr_any(a, axis, dtype, out, keepdims)
62
+ return umr_any(a, axis, dtype, out, keepdims, where=where)
63
+
64
+ def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
65
+ # By default, return a boolean for any and all
66
+ if dtype is None:
67
+ dtype = bool_dt
68
+ # Parsing keyword arguments is currently fairly slow, so avoid it for now
69
+ if where is True:
70
+ return umr_all(a, axis, dtype, out, keepdims)
71
+ return umr_all(a, axis, dtype, out, keepdims, where=where)
72
+
73
+ def _count_reduce_items(arr, axis, keepdims=False, where=True):
74
+ # fast-path for the default case
75
+ if where is True:
76
+ # no boolean mask given, calculate items according to axis
77
+ if axis is None:
78
+ axis = tuple(range(arr.ndim))
79
+ elif not isinstance(axis, tuple):
80
+ axis = (axis,)
81
+ items = 1
82
+ for ax in axis:
83
+ items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
84
+ items = nt.intp(items)
85
+ else:
86
+ # TODO: Optimize case when `where` is broadcast along a non-reduction
87
+ # axis and full sum is more excessive than needed.
88
+
89
+ # guarded to protect circular imports
90
+ from numpy.lib._stride_tricks_impl import broadcast_to
91
+ # count True values in (potentially broadcasted) boolean mask
92
+ items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
93
+ keepdims)
94
+ return items
95
+
96
+ def _clip(a, min=None, max=None, out=None, **kwargs):
97
+ if a.dtype.kind in "iu":
98
+ # If min/max is a Python integer, deal with out-of-bound values here.
99
+ # (This enforces NEP 50 rules as no value based promotion is done.)
100
+ if type(min) is int and min <= np.iinfo(a.dtype).min:
101
+ min = None
102
+ if type(max) is int and max >= np.iinfo(a.dtype).max:
103
+ max = None
104
+
105
+ if min is None and max is None:
106
+ # return identity
107
+ return um.positive(a, out=out, **kwargs)
108
+ elif min is None:
109
+ return um.minimum(a, max, out=out, **kwargs)
110
+ elif max is None:
111
+ return um.maximum(a, min, out=out, **kwargs)
112
+ else:
113
+ return um.clip(a, min, max, out=out, **kwargs)
114
+
115
+ def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
116
+ arr = asanyarray(a)
117
+
118
+ is_float16_result = False
119
+
120
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
121
+ if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
122
+ warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=2)
123
+
124
+ # Cast bool, unsigned int, and int to float64 by default
125
+ if dtype is None:
126
+ if issubclass(arr.dtype.type, (nt.integer, nt.bool)):
127
+ dtype = mu.dtype('f8')
128
+ elif issubclass(arr.dtype.type, nt.float16):
129
+ dtype = mu.dtype('f4')
130
+ is_float16_result = True
131
+
132
+ ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
133
+ if isinstance(ret, mu.ndarray):
134
+ ret = um.true_divide(
135
+ ret, rcount, out=ret, casting='unsafe', subok=False)
136
+ if is_float16_result and out is None:
137
+ ret = arr.dtype.type(ret)
138
+ elif hasattr(ret, 'dtype'):
139
+ if is_float16_result:
140
+ ret = arr.dtype.type(ret / rcount)
141
+ else:
142
+ ret = ret.dtype.type(ret / rcount)
143
+ else:
144
+ ret = ret / rcount
145
+
146
+ return ret
147
+
148
+ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
149
+ where=True, mean=None):
150
+ arr = asanyarray(a)
151
+
152
+ rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
153
+ # Make this warning show up on top.
154
+ if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
155
+ warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
156
+ stacklevel=2)
157
+
158
+ # Cast bool, unsigned int, and int to float64 by default
159
+ if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool)):
160
+ dtype = mu.dtype('f8')
161
+
162
+ if mean is not None:
163
+ arrmean = mean
164
+ else:
165
+ # Compute the mean.
166
+ # Note that if dtype is not of inexact type then arraymean will
167
+ # not be either.
168
+ arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
169
+ # The shape of rcount has to match arrmean to not change the shape of
170
+ # out in broadcasting. Otherwise, it cannot be stored back to arrmean.
171
+ if rcount.ndim == 0:
172
+ # fast-path for default case when where is True
173
+ div = rcount
174
+ else:
175
+ # matching rcount to arrmean when where is specified as array
176
+ div = rcount.reshape(arrmean.shape)
177
+ if isinstance(arrmean, mu.ndarray):
178
+ arrmean = um.true_divide(arrmean, div, out=arrmean,
179
+ casting='unsafe', subok=False)
180
+ elif hasattr(arrmean, "dtype"):
181
+ arrmean = arrmean.dtype.type(arrmean / rcount)
182
+ else:
183
+ arrmean = arrmean / rcount
184
+
185
+ # Compute sum of squared deviations from mean
186
+ # Note that x may not be inexact and that we need it to be an array,
187
+ # not a scalar.
188
+ x = um.subtract(arr, arrmean, out=...)
189
+ if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
190
+ x = um.square(x, out=x)
191
+ # Fast-paths for built-in complex types
192
+ elif (_float_dtype := _complex_to_float.get(x.dtype)) is not None:
193
+ xv = x.view(dtype=(_float_dtype, (2,)))
194
+ um.square(xv, out=xv)
195
+ x = um.add(xv[..., 0], xv[..., 1], out=x.real)
196
+ # Most general case; includes handling object arrays containing imaginary
197
+ # numbers and complex types with non-native byteorder
198
+ else:
199
+ x = um.multiply(x, um.conjugate(x), out=x).real
200
+
201
+ ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
202
+
203
+ # Compute degrees of freedom and make sure it is not negative.
204
+ rcount = um.maximum(rcount - ddof, 0)
205
+
206
+ # divide by degrees of freedom
207
+ if isinstance(ret, mu.ndarray):
208
+ ret = um.true_divide(
209
+ ret, rcount, out=ret, casting='unsafe', subok=False)
210
+ elif hasattr(ret, 'dtype'):
211
+ ret = ret.dtype.type(ret / rcount)
212
+ else:
213
+ ret = ret / rcount
214
+
215
+ return ret
216
+
217
+ def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
218
+ where=True, mean=None):
219
+ ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
220
+ keepdims=keepdims, where=where, mean=mean)
221
+
222
+ if isinstance(ret, mu.ndarray):
223
+ ret = um.sqrt(ret, out=ret)
224
+ elif hasattr(ret, 'dtype'):
225
+ ret = ret.dtype.type(um.sqrt(ret))
226
+ else:
227
+ ret = um.sqrt(ret)
228
+
229
+ return ret
230
+
231
+ def _ptp(a, axis=None, out=None, keepdims=False):
232
+ return um.subtract(
233
+ umr_maximum(a, axis, None, out, keepdims),
234
+ umr_minimum(a, axis, None, None, keepdims),
235
+ out
236
+ )
237
+
238
+ def _dump(self, file, protocol=2):
239
+ if hasattr(file, 'write'):
240
+ ctx = nullcontext(file)
241
+ else:
242
+ ctx = open(os.fspath(file), "wb")
243
+ with ctx as f:
244
+ pickle.dump(self, f, protocol=protocol)
245
+
246
+ def _dumps(self, protocol=2):
247
+ return pickle.dumps(self, protocol=protocol)
248
+
249
+ def _bitwise_count(a, out=None, *, where=True, casting='same_kind',
250
+ order='K', dtype=None, subok=True):
251
+ return umr_bitwise_count(a, out, where=where, casting=casting,
252
+ order=order, dtype=dtype, subok=subok)
python/user_packages/Python313/site-packages/numpy/_core/_methods.pyi ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, Concatenate, TypeAlias
3
+
4
+ import numpy as np
5
+
6
+ from . import _exceptions as _exceptions
7
+
8
+ ###
9
+
10
+ _Reduce2: TypeAlias = Callable[Concatenate[object, ...], Any]
11
+
12
+ ###
13
+
14
+ bool_dt: np.dtype[np.bool] = ...
15
+ umr_maximum: _Reduce2 = ...
16
+ umr_minimum: _Reduce2 = ...
17
+ umr_sum: _Reduce2 = ...
18
+ umr_prod: _Reduce2 = ...
19
+ umr_bitwise_count = np.bitwise_count
20
+ umr_any: _Reduce2 = ...
21
+ umr_all: _Reduce2 = ...
22
+ _complex_to_float: dict[np.dtype[np.complexfloating], np.dtype[np.floating]] = ...
python/user_packages/Python313/site-packages/numpy/_core/_multiarray_tests.cp313-win_amd64.lib ADDED
Binary file (2.42 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_multiarray_tests.cp313-win_amd64.pyd ADDED
Binary file (64.5 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_multiarray_umath.cp313-win_amd64.lib ADDED
Binary file (2.19 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_operand_flag_tests.cp313-win_amd64.lib ADDED
Binary file (2.23 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_operand_flag_tests.cp313-win_amd64.pyd ADDED
Binary file (12.3 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_rational_tests.cp313-win_amd64.lib ADDED
Binary file (2.16 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_rational_tests.cp313-win_amd64.pyd ADDED
Binary file (39.9 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_simd.cp313-win_amd64.lib ADDED
Binary file (1.98 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_simd.pyi ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import ModuleType
2
+ from typing import TypedDict, type_check_only
3
+
4
+ # NOTE: these 5 are only defined on systems with an intel processor
5
+ SSE42: ModuleType | None = ...
6
+ FMA3: ModuleType | None = ...
7
+ AVX2: ModuleType | None = ...
8
+ AVX512F: ModuleType | None = ...
9
+ AVX512_SKX: ModuleType | None = ...
10
+
11
+ # NOTE: these 2 are only defined on systems with an arm processor
12
+ ASIMD: ModuleType | None = ...
13
+ NEON: ModuleType | None = ...
14
+
15
+ # NOTE: This is only defined on systems with an riscv64 processor.
16
+ RVV: ModuleType | None = ...
17
+
18
+ baseline: ModuleType | None = ...
19
+
20
+ @type_check_only
21
+ class SimdTargets(TypedDict):
22
+ SSE42: ModuleType | None
23
+ AVX2: ModuleType | None
24
+ FMA3: ModuleType | None
25
+ AVX512F: ModuleType | None
26
+ AVX512_SKX: ModuleType | None
27
+ ASIMD: ModuleType | None
28
+ NEON: ModuleType | None
29
+ RVV: ModuleType | None
30
+ baseline: ModuleType | None
31
+
32
+ targets: SimdTargets = ...
33
+
34
+ def clear_floatstatus() -> None: ...
35
+ def get_floatstatus() -> int: ...
python/user_packages/Python313/site-packages/numpy/_core/_string_helpers.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ String-handling utilities to avoid locale-dependence.
3
+
4
+ Used primarily to generate type name aliases.
5
+ """
6
+ # "import string" is costly to import!
7
+ # Construct the translation tables directly
8
+ # "A" = chr(65), "a" = chr(97)
9
+ _all_chars = tuple(map(chr, range(256)))
10
+ _ascii_upper = _all_chars[65:65 + 26]
11
+ _ascii_lower = _all_chars[97:97 + 26]
12
+ LOWER_TABLE = _all_chars[:65] + _ascii_lower + _all_chars[65 + 26:]
13
+ UPPER_TABLE = _all_chars[:97] + _ascii_upper + _all_chars[97 + 26:]
14
+
15
+
16
+ def english_lower(s):
17
+ """ Apply English case rules to convert ASCII strings to all lower case.
18
+
19
+ This is an internal utility function to replace calls to str.lower() such
20
+ that we can avoid changing behavior with changing locales. In particular,
21
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
22
+ both lowercase and uppercase. Thus, "I".lower() != "i" in a "tr" locale.
23
+
24
+ Parameters
25
+ ----------
26
+ s : str
27
+
28
+ Returns
29
+ -------
30
+ lowered : str
31
+
32
+ Examples
33
+ --------
34
+ >>> from numpy._core.numerictypes import english_lower
35
+ >>> english_lower('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
36
+ 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789_'
37
+ >>> english_lower('')
38
+ ''
39
+ """
40
+ lowered = s.translate(LOWER_TABLE)
41
+ return lowered
42
+
43
+
44
+ def english_upper(s):
45
+ """ Apply English case rules to convert ASCII strings to all upper case.
46
+
47
+ This is an internal utility function to replace calls to str.upper() such
48
+ that we can avoid changing behavior with changing locales. In particular,
49
+ Turkish has distinct dotted and dotless variants of the Latin letter "I" in
50
+ both lowercase and uppercase. Thus, "i".upper() != "I" in a "tr" locale.
51
+
52
+ Parameters
53
+ ----------
54
+ s : str
55
+
56
+ Returns
57
+ -------
58
+ uppered : str
59
+
60
+ Examples
61
+ --------
62
+ >>> from numpy._core.numerictypes import english_upper
63
+ >>> english_upper('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
64
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
65
+ >>> english_upper('')
66
+ ''
67
+ """
68
+ uppered = s.translate(UPPER_TABLE)
69
+ return uppered
70
+
71
+
72
+ def english_capitalize(s):
73
+ """ Apply English case rules to convert the first character of an ASCII
74
+ string to upper case.
75
+
76
+ This is an internal utility function to replace calls to str.capitalize()
77
+ such that we can avoid changing behavior with changing locales.
78
+
79
+ Parameters
80
+ ----------
81
+ s : str
82
+
83
+ Returns
84
+ -------
85
+ capitalized : str
86
+
87
+ Examples
88
+ --------
89
+ >>> from numpy._core.numerictypes import english_capitalize
90
+ >>> english_capitalize('int8')
91
+ 'Int8'
92
+ >>> english_capitalize('Int8')
93
+ 'Int8'
94
+ >>> english_capitalize('')
95
+ ''
96
+ """
97
+ if s:
98
+ return english_upper(s[0]) + s[1:]
99
+ else:
100
+ return s
python/user_packages/Python313/site-packages/numpy/_core/_string_helpers.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Final
2
+
3
+ _all_chars: Final[tuple[str, ...]] = ...
4
+ _ascii_upper: Final[tuple[str, ...]] = ...
5
+ _ascii_lower: Final[tuple[str, ...]] = ...
6
+
7
+ LOWER_TABLE: Final[tuple[str, ...]] = ...
8
+ UPPER_TABLE: Final[tuple[str, ...]] = ...
9
+
10
+ def english_lower(s: str) -> str: ...
11
+ def english_upper(s: str) -> str: ...
12
+ def english_capitalize(s: str) -> str: ...
python/user_packages/Python313/site-packages/numpy/_core/_struct_ufunc_tests.cp313-win_amd64.lib ADDED
Binary file (2.23 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_struct_ufunc_tests.cp313-win_amd64.pyd ADDED
Binary file (14.3 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_type_aliases.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Due to compatibility, numpy has a very large number of different naming
3
+ conventions for the scalar types (those subclassing from `numpy.generic`).
4
+ This file produces a convoluted set of dictionaries mapping names to types,
5
+ and sometimes other mappings too.
6
+
7
+ .. data:: allTypes
8
+ A dictionary of names to types that will be exposed as attributes through
9
+ ``np._core.numerictypes.*``
10
+
11
+ .. data:: sctypeDict
12
+ Similar to `allTypes`, but maps a broader set of aliases to their types.
13
+
14
+ .. data:: sctypes
15
+ A dictionary keyed by a "type group" string, providing a list of types
16
+ under that group.
17
+
18
+ """
19
+
20
+ import numpy._core.multiarray as ma
21
+ from numpy._core.multiarray import dtype, typeinfo
22
+
23
+ ######################################
24
+ # Building `sctypeDict` and `allTypes`
25
+ ######################################
26
+
27
+ sctypeDict = {}
28
+ allTypes = {}
29
+ c_names_dict = {}
30
+
31
+ _abstract_type_names = {
32
+ "generic", "integer", "inexact", "floating", "number",
33
+ "flexible", "character", "complexfloating", "unsignedinteger",
34
+ "signedinteger"
35
+ }
36
+
37
+ for _abstract_type_name in _abstract_type_names:
38
+ allTypes[_abstract_type_name] = getattr(ma, _abstract_type_name)
39
+ del _abstract_type_name
40
+
41
+ for k, v in typeinfo.items():
42
+ if k.startswith("NPY_") and v not in c_names_dict:
43
+ c_names_dict[k[4:]] = v
44
+ else:
45
+ concrete_type = v.type
46
+ allTypes[k] = concrete_type
47
+ sctypeDict[k] = concrete_type
48
+ del concrete_type
49
+ del k, v
50
+
51
+ _aliases = {
52
+ "double": "float64",
53
+ "cdouble": "complex128",
54
+ "single": "float32",
55
+ "csingle": "complex64",
56
+ "half": "float16",
57
+ "bool_": "bool",
58
+ # Default integer:
59
+ "int_": "intp",
60
+ "uint": "uintp",
61
+ }
62
+
63
+ for k, v in _aliases.items():
64
+ sctypeDict[k] = allTypes[v]
65
+ allTypes[k] = allTypes[v]
66
+ del k, v
67
+
68
+ # extra aliases are added only to `sctypeDict`
69
+ # to support dtype name access, such as`np.dtype("float")`
70
+ _extra_aliases = {
71
+ "float": "float64",
72
+ "complex": "complex128",
73
+ "object": "object_",
74
+ "bytes": "bytes_",
75
+ "a": "bytes_",
76
+ "int": "int_",
77
+ "str": "str_",
78
+ "unicode": "str_",
79
+ }
80
+
81
+ for k, v in _extra_aliases.items():
82
+ sctypeDict[k] = allTypes[v]
83
+ del k, v
84
+
85
+ # include extended precision sized aliases
86
+ for is_complex, full_name in [(False, "longdouble"), (True, "clongdouble")]:
87
+ longdouble_type = allTypes[full_name]
88
+
89
+ bits = dtype(longdouble_type).itemsize * 8
90
+ base_name = "complex" if is_complex else "float"
91
+ extended_prec_name = f"{base_name}{bits}"
92
+ if extended_prec_name not in allTypes:
93
+ sctypeDict[extended_prec_name] = longdouble_type
94
+ allTypes[extended_prec_name] = longdouble_type
95
+
96
+ del is_complex, full_name, longdouble_type, bits, base_name, extended_prec_name
97
+
98
+
99
+ ####################
100
+ # Building `sctypes`
101
+ ####################
102
+
103
+ sctypes = {"int": set(), "uint": set(), "float": set(),
104
+ "complex": set(), "others": set()}
105
+
106
+ for type_info in typeinfo.values():
107
+ if type_info.kind in ["M", "m"]: # exclude timedelta and datetime
108
+ continue
109
+
110
+ concrete_type = type_info.type
111
+
112
+ # find proper group for each concrete type
113
+ for type_group, abstract_type in [
114
+ ("int", ma.signedinteger), ("uint", ma.unsignedinteger),
115
+ ("float", ma.floating), ("complex", ma.complexfloating),
116
+ ("others", ma.generic)
117
+ ]:
118
+ if issubclass(concrete_type, abstract_type):
119
+ sctypes[type_group].add(concrete_type)
120
+ del type_group, abstract_type
121
+ break
122
+
123
+ del type_info, concrete_type
124
+
125
+ # sort sctype groups by bitsize
126
+ for sctype_key in sctypes.keys():
127
+ sctype_list = list(sctypes[sctype_key])
128
+ sctype_list.sort(key=lambda x: dtype(x).itemsize)
129
+ sctypes[sctype_key] = sctype_list
130
+
131
+ del sctype_key, sctype_list
python/user_packages/Python313/site-packages/numpy/_core/_type_aliases.pyi ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Collection
2
+ from typing import Final, Literal as L, TypeAlias, TypedDict, type_check_only
3
+
4
+ import numpy as np
5
+
6
+ sctypeDict: Final[dict[str, type[np.generic]]]
7
+ allTypes: Final[dict[str, type[np.generic]]]
8
+
9
+ @type_check_only
10
+ class _CNamesDict(TypedDict):
11
+ BOOL: np.dtype[np.bool]
12
+ HALF: np.dtype[np.half]
13
+ FLOAT: np.dtype[np.single]
14
+ DOUBLE: np.dtype[np.double]
15
+ LONGDOUBLE: np.dtype[np.longdouble]
16
+ CFLOAT: np.dtype[np.csingle]
17
+ CDOUBLE: np.dtype[np.cdouble]
18
+ CLONGDOUBLE: np.dtype[np.clongdouble]
19
+ STRING: np.dtype[np.bytes_]
20
+ UNICODE: np.dtype[np.str_]
21
+ VOID: np.dtype[np.void]
22
+ OBJECT: np.dtype[np.object_]
23
+ DATETIME: np.dtype[np.datetime64]
24
+ TIMEDELTA: np.dtype[np.timedelta64]
25
+ BYTE: np.dtype[np.byte]
26
+ UBYTE: np.dtype[np.ubyte]
27
+ SHORT: np.dtype[np.short]
28
+ USHORT: np.dtype[np.ushort]
29
+ INT: np.dtype[np.intc]
30
+ UINT: np.dtype[np.uintc]
31
+ LONG: np.dtype[np.long]
32
+ ULONG: np.dtype[np.ulong]
33
+ LONGLONG: np.dtype[np.longlong]
34
+ ULONGLONG: np.dtype[np.ulonglong]
35
+
36
+ c_names_dict: Final[_CNamesDict]
37
+
38
+ _AbstractTypeName: TypeAlias = L[
39
+ "generic",
40
+ "flexible",
41
+ "character",
42
+ "number",
43
+ "integer",
44
+ "inexact",
45
+ "unsignedinteger",
46
+ "signedinteger",
47
+ "floating",
48
+ "complexfloating",
49
+ ]
50
+ _abstract_type_names: Final[set[_AbstractTypeName]]
51
+
52
+ @type_check_only
53
+ class _AliasesType(TypedDict):
54
+ double: L["float64"]
55
+ cdouble: L["complex128"]
56
+ single: L["float32"]
57
+ csingle: L["complex64"]
58
+ half: L["float16"]
59
+ bool_: L["bool"]
60
+ int_: L["intp"]
61
+ uint: L["intp"]
62
+
63
+ _aliases: Final[_AliasesType]
64
+
65
+ @type_check_only
66
+ class _ExtraAliasesType(TypedDict):
67
+ float: L["float64"]
68
+ complex: L["complex128"]
69
+ object: L["object_"]
70
+ bytes: L["bytes_"]
71
+ a: L["bytes_"]
72
+ int: L["int_"]
73
+ str: L["str_"]
74
+ unicode: L["str_"]
75
+
76
+ _extra_aliases: Final[_ExtraAliasesType]
77
+
78
+ @type_check_only
79
+ class _SCTypes(TypedDict):
80
+ int: Collection[type[np.signedinteger]]
81
+ uint: Collection[type[np.unsignedinteger]]
82
+ float: Collection[type[np.floating]]
83
+ complex: Collection[type[np.complexfloating]]
84
+ others: Collection[type[np.flexible | np.bool | np.object_]]
85
+
86
+ sctypes: Final[_SCTypes]
python/user_packages/Python313/site-packages/numpy/_core/_ufunc_config.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions for changing global ufunc configuration
3
+
4
+ This provides helpers which wrap `_get_extobj_dict` and `_make_extobj`, and
5
+ `_extobj_contextvar` from umath.
6
+ """
7
+ import functools
8
+
9
+ from numpy._utils import set_module
10
+
11
+ from .umath import _extobj_contextvar, _get_extobj_dict, _make_extobj
12
+
13
+ __all__ = [
14
+ "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
15
+ "errstate"
16
+ ]
17
+
18
+
19
+ @set_module('numpy')
20
+ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
21
+ """
22
+ Set how floating-point errors are handled.
23
+
24
+ Note that operations on integer scalar types (such as `int16`) are
25
+ handled like floating point, and are affected by these settings.
26
+
27
+ Parameters
28
+ ----------
29
+ all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
30
+ Set treatment for all types of floating-point errors at once:
31
+
32
+ - ignore: Take no action when the exception occurs.
33
+ - warn: Print a :exc:`RuntimeWarning` (via the Python `warnings`
34
+ module).
35
+ - raise: Raise a :exc:`FloatingPointError`.
36
+ - call: Call a function specified using the `seterrcall` function.
37
+ - print: Print a warning directly to ``stdout``.
38
+ - log: Record error in a Log object specified by `seterrcall`.
39
+
40
+ The default is not to change the current behavior.
41
+ divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
42
+ Treatment for division by zero.
43
+ over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
44
+ Treatment for floating-point overflow.
45
+ under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
46
+ Treatment for floating-point underflow.
47
+ invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
48
+ Treatment for invalid floating-point operation.
49
+
50
+ Returns
51
+ -------
52
+ old_settings : dict
53
+ Dictionary containing the old settings.
54
+
55
+ See also
56
+ --------
57
+ seterrcall : Set a callback function for the 'call' mode.
58
+ geterr, geterrcall, errstate
59
+
60
+
61
+ Notes
62
+ -----
63
+ The floating-point exceptions are defined in the IEEE 754 standard [1]_:
64
+
65
+ - Division by zero: infinite result obtained from finite numbers.
66
+ - Overflow: result too large to be expressed.
67
+ - Underflow: result so close to zero that some precision
68
+ was lost.
69
+ - Invalid operation: result is not an expressible number, typically
70
+ indicates that a NaN was produced.
71
+
72
+ **Concurrency note:** see :ref:`fp_error_handling`
73
+
74
+ .. [1] https://en.wikipedia.org/wiki/IEEE_754
75
+
76
+ Examples
77
+ --------
78
+ >>> import numpy as np
79
+ >>> orig_settings = np.seterr(all='ignore') # seterr to known value
80
+ >>> np.int16(32000) * np.int16(3)
81
+ np.int16(30464)
82
+ >>> np.seterr(over='raise')
83
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
84
+ >>> old_settings = np.seterr(all='warn', over='raise')
85
+ >>> np.int16(32000) * np.int16(3)
86
+ Traceback (most recent call last):
87
+ File "<stdin>", line 1, in <module>
88
+ FloatingPointError: overflow encountered in scalar multiply
89
+
90
+ >>> old_settings = np.seterr(all='print')
91
+ >>> np.geterr()
92
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
93
+ >>> np.int16(32000) * np.int16(3)
94
+ np.int16(30464)
95
+ >>> np.seterr(**orig_settings) # restore original
96
+ {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
97
+
98
+ """
99
+
100
+ old = _get_extobj_dict()
101
+ # The errstate doesn't include call and bufsize, so pop them:
102
+ old.pop("call", None)
103
+ old.pop("bufsize", None)
104
+
105
+ extobj = _make_extobj(
106
+ all=all, divide=divide, over=over, under=under, invalid=invalid)
107
+ _extobj_contextvar.set(extobj)
108
+ return old
109
+
110
+
111
+ @set_module('numpy')
112
+ def geterr():
113
+ """
114
+ Get the current way of handling floating-point errors.
115
+
116
+ Returns
117
+ -------
118
+ res : dict
119
+ A dictionary with keys "divide", "over", "under", and "invalid",
120
+ whose values are from the strings "ignore", "print", "log", "warn",
121
+ "raise", and "call". The keys represent possible floating-point
122
+ exceptions, and the values define how these exceptions are handled.
123
+
124
+ See Also
125
+ --------
126
+ geterrcall, seterr, seterrcall
127
+
128
+ Notes
129
+ -----
130
+ For complete documentation of the types of floating-point exceptions and
131
+ treatment options, see `seterr`.
132
+
133
+ **Concurrency note:** see :doc:`/reference/routines.err`
134
+
135
+ Examples
136
+ --------
137
+ >>> import numpy as np
138
+ >>> np.geterr()
139
+ {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
140
+ >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP
141
+ array([nan, 1., 1.])
142
+ RuntimeWarning: invalid value encountered in divide
143
+
144
+ >>> oldsettings = np.seterr(all='warn', invalid='raise')
145
+ >>> np.geterr()
146
+ {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'}
147
+ >>> np.arange(3.) / np.arange(3.)
148
+ Traceback (most recent call last):
149
+ ...
150
+ FloatingPointError: invalid value encountered in divide
151
+ >>> oldsettings = np.seterr(**oldsettings) # restore original
152
+
153
+ """
154
+ res = _get_extobj_dict()
155
+ # The "geterr" doesn't include call and bufsize,:
156
+ res.pop("call", None)
157
+ res.pop("bufsize", None)
158
+ return res
159
+
160
+
161
+ @set_module('numpy')
162
+ def setbufsize(size):
163
+ """
164
+ Set the size of the buffer used in ufuncs.
165
+
166
+ .. versionchanged:: 2.0
167
+ The scope of setting the buffer is tied to the `numpy.errstate`
168
+ context. Exiting a ``with errstate():`` will also restore the bufsize.
169
+
170
+ Parameters
171
+ ----------
172
+ size : int
173
+ Size of buffer.
174
+
175
+ Returns
176
+ -------
177
+ bufsize : int
178
+ Previous size of ufunc buffer in bytes.
179
+
180
+ Notes
181
+ -----
182
+ **Concurrency note:** see :doc:`/reference/routines.err`
183
+
184
+ Examples
185
+ --------
186
+ When exiting a `numpy.errstate` context manager the bufsize is restored:
187
+
188
+ >>> import numpy as np
189
+ >>> with np.errstate():
190
+ ... np.setbufsize(4096)
191
+ ... print(np.getbufsize())
192
+ ...
193
+ 8192
194
+ 4096
195
+ >>> np.getbufsize()
196
+ 8192
197
+
198
+ """
199
+ if size < 0:
200
+ raise ValueError("buffer size must be non-negative")
201
+ old = _get_extobj_dict()["bufsize"]
202
+ extobj = _make_extobj(bufsize=size)
203
+ _extobj_contextvar.set(extobj)
204
+ return old
205
+
206
+
207
+ @set_module('numpy')
208
+ def getbufsize():
209
+ """
210
+ Return the size of the buffer used in ufuncs.
211
+
212
+ Returns
213
+ -------
214
+ getbufsize : int
215
+ Size of ufunc buffer in bytes.
216
+
217
+ Notes
218
+ -----
219
+
220
+ **Concurrency note:** see :doc:`/reference/routines.err`
221
+
222
+
223
+ Examples
224
+ --------
225
+ >>> import numpy as np
226
+ >>> np.getbufsize()
227
+ 8192
228
+
229
+ """
230
+ return _get_extobj_dict()["bufsize"]
231
+
232
+
233
+ @set_module('numpy')
234
+ def seterrcall(func):
235
+ """
236
+ Set the floating-point error callback function or log object.
237
+
238
+ There are two ways to capture floating-point error messages. The first
239
+ is to set the error-handler to 'call', using `seterr`. Then, set
240
+ the function to call using this function.
241
+
242
+ The second is to set the error-handler to 'log', using `seterr`.
243
+ Floating-point errors then trigger a call to the 'write' method of
244
+ the provided object.
245
+
246
+ Parameters
247
+ ----------
248
+ func : callable f(err, flag) or object with write method
249
+ Function to call upon floating-point errors ('call'-mode) or
250
+ object whose 'write' method is used to log such message ('log'-mode).
251
+
252
+ The call function takes two arguments. The first is a string describing
253
+ the type of error (such as "divide by zero", "overflow", "underflow",
254
+ or "invalid value"), and the second is the status flag. The flag is a
255
+ byte, whose four least-significant bits indicate the type of error, one
256
+ of "divide", "over", "under", "invalid"::
257
+
258
+ [0 0 0 0 divide over under invalid]
259
+
260
+ In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
261
+
262
+ If an object is provided, its write method should take one argument,
263
+ a string.
264
+
265
+ Returns
266
+ -------
267
+ h : callable, log instance or None
268
+ The old error handler.
269
+
270
+ See Also
271
+ --------
272
+ seterr, geterr, geterrcall
273
+
274
+ Notes
275
+ -----
276
+
277
+ **Concurrency note:** see :doc:`/reference/routines.err`
278
+
279
+ Examples
280
+ --------
281
+ Callback upon error:
282
+
283
+ >>> def err_handler(type, flag):
284
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
285
+ ...
286
+
287
+ >>> import numpy as np
288
+
289
+ >>> orig_handler = np.seterrcall(err_handler)
290
+ >>> orig_err = np.seterr(all='call')
291
+
292
+ >>> np.array([1, 2, 3]) / 0.0
293
+ Floating point error (divide by zero), with flag 1
294
+ array([inf, inf, inf])
295
+
296
+ >>> np.seterrcall(orig_handler)
297
+ <function err_handler at 0x...>
298
+ >>> np.seterr(**orig_err)
299
+ {'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
300
+
301
+ Log error message:
302
+
303
+ >>> class Log:
304
+ ... def write(self, msg):
305
+ ... print("LOG: %s" % msg)
306
+ ...
307
+
308
+ >>> log = Log()
309
+ >>> saved_handler = np.seterrcall(log)
310
+ >>> save_err = np.seterr(all='log')
311
+
312
+ >>> np.array([1, 2, 3]) / 0.0
313
+ LOG: Warning: divide by zero encountered in divide
314
+ array([inf, inf, inf])
315
+
316
+ >>> np.seterrcall(orig_handler)
317
+ <numpy.Log object at 0x...>
318
+ >>> np.seterr(**orig_err)
319
+ {'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
320
+
321
+ """
322
+ old = _get_extobj_dict()["call"]
323
+ extobj = _make_extobj(call=func)
324
+ _extobj_contextvar.set(extobj)
325
+ return old
326
+
327
+
328
+ @set_module('numpy')
329
+ def geterrcall():
330
+ """
331
+ Return the current callback function used on floating-point errors.
332
+
333
+ When the error handling for a floating-point error (one of "divide",
334
+ "over", "under", or "invalid") is set to 'call' or 'log', the function
335
+ that is called or the log instance that is written to is returned by
336
+ `geterrcall`. This function or log instance has been set with
337
+ `seterrcall`.
338
+
339
+ Returns
340
+ -------
341
+ errobj : callable, log instance or None
342
+ The current error handler. If no handler was set through `seterrcall`,
343
+ ``None`` is returned.
344
+
345
+ See Also
346
+ --------
347
+ seterrcall, seterr, geterr
348
+
349
+ Notes
350
+ -----
351
+ For complete documentation of the types of floating-point exceptions and
352
+ treatment options, see `seterr`.
353
+
354
+ **Concurrency note:** see :ref:`fp_error_handling`
355
+
356
+ Examples
357
+ --------
358
+ >>> import numpy as np
359
+ >>> np.geterrcall() # we did not yet set a handler, returns None
360
+
361
+ >>> orig_settings = np.seterr(all='call')
362
+ >>> def err_handler(type, flag):
363
+ ... print("Floating point error (%s), with flag %s" % (type, flag))
364
+ >>> old_handler = np.seterrcall(err_handler)
365
+ >>> np.array([1, 2, 3]) / 0.0
366
+ Floating point error (divide by zero), with flag 1
367
+ array([inf, inf, inf])
368
+
369
+ >>> cur_handler = np.geterrcall()
370
+ >>> cur_handler is err_handler
371
+ True
372
+ >>> old_settings = np.seterr(**orig_settings) # restore original
373
+ >>> old_handler = np.seterrcall(None) # restore original
374
+
375
+ """
376
+ return _get_extobj_dict()["call"]
377
+
378
+
379
+ class _unspecified:
380
+ pass
381
+
382
+
383
+ _Unspecified = _unspecified()
384
+
385
+
386
+ @set_module('numpy')
387
+ class errstate:
388
+ """
389
+ errstate(**kwargs)
390
+
391
+ Context manager for floating-point error handling.
392
+
393
+ Using an instance of `errstate` as a context manager allows statements in
394
+ that context to execute with a known error handling behavior. Upon entering
395
+ the context the error handling is set with `seterr` and `seterrcall`, and
396
+ upon exiting it is reset to what it was before.
397
+
398
+ .. versionchanged:: 1.17.0
399
+ `errstate` is also usable as a function decorator, saving
400
+ a level of indentation if an entire function is wrapped.
401
+
402
+ .. versionchanged:: 2.0
403
+ `errstate` is now fully thread and asyncio safe, but may not be
404
+ entered more than once.
405
+ It is not safe to decorate async functions using ``errstate``.
406
+
407
+ Parameters
408
+ ----------
409
+ kwargs : {divide, over, under, invalid}
410
+ Keyword arguments. The valid keywords are the possible floating-point
411
+ exceptions. Each keyword should have a string value that defines the
412
+ treatment for the particular error. Possible values are
413
+ {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
414
+
415
+ See Also
416
+ --------
417
+ seterr, geterr, seterrcall, geterrcall
418
+
419
+ Notes
420
+ -----
421
+ For complete documentation of the types of floating-point exceptions and
422
+ treatment options, see `seterr`.
423
+
424
+ **Concurrency note:** see :ref:`fp_error_handling`
425
+
426
+ Examples
427
+ --------
428
+ >>> import numpy as np
429
+ >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
430
+
431
+ >>> np.arange(3) / 0.
432
+ array([nan, inf, inf])
433
+ >>> with np.errstate(divide='ignore'):
434
+ ... np.arange(3) / 0.
435
+ array([nan, inf, inf])
436
+
437
+ >>> np.sqrt(-1)
438
+ np.float64(nan)
439
+ >>> with np.errstate(invalid='raise'):
440
+ ... np.sqrt(-1)
441
+ Traceback (most recent call last):
442
+ File "<stdin>", line 2, in <module>
443
+ FloatingPointError: invalid value encountered in sqrt
444
+
445
+ Outside the context the error handling behavior has not changed:
446
+
447
+ >>> np.geterr()
448
+ {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
449
+ >>> olderr = np.seterr(**olderr) # restore original state
450
+
451
+ """
452
+ __slots__ = (
453
+ "_all",
454
+ "_call",
455
+ "_divide",
456
+ "_invalid",
457
+ "_over",
458
+ "_token",
459
+ "_under",
460
+ )
461
+
462
+ def __init__(self, *, call=_Unspecified,
463
+ all=None, divide=None, over=None, under=None, invalid=None):
464
+ self._token = None
465
+ self._call = call
466
+ self._all = all
467
+ self._divide = divide
468
+ self._over = over
469
+ self._under = under
470
+ self._invalid = invalid
471
+
472
+ def __enter__(self):
473
+ # Note that __call__ duplicates much of this logic
474
+ if self._token is not None:
475
+ raise TypeError("Cannot enter `np.errstate` twice.")
476
+ if self._call is _Unspecified:
477
+ extobj = _make_extobj(
478
+ all=self._all, divide=self._divide, over=self._over,
479
+ under=self._under, invalid=self._invalid)
480
+ else:
481
+ extobj = _make_extobj(
482
+ call=self._call,
483
+ all=self._all, divide=self._divide, over=self._over,
484
+ under=self._under, invalid=self._invalid)
485
+
486
+ self._token = _extobj_contextvar.set(extobj)
487
+
488
+ def __exit__(self, *exc_info):
489
+ _extobj_contextvar.reset(self._token)
490
+
491
+ def __call__(self, func):
492
+ # We need to customize `__call__` compared to `ContextDecorator`
493
+ # because we must store the token per-thread so cannot store it on
494
+ # the instance (we could create a new instance for this).
495
+ # This duplicates the code from `__enter__`.
496
+ @functools.wraps(func)
497
+ def inner(*args, **kwargs):
498
+ if self._call is _Unspecified:
499
+ extobj = _make_extobj(
500
+ all=self._all, divide=self._divide, over=self._over,
501
+ under=self._under, invalid=self._invalid)
502
+ else:
503
+ extobj = _make_extobj(
504
+ call=self._call,
505
+ all=self._all, divide=self._divide, over=self._over,
506
+ under=self._under, invalid=self._invalid)
507
+
508
+ _token = _extobj_contextvar.set(extobj)
509
+ try:
510
+ # Call the original, decorated, function:
511
+ return func(*args, **kwargs)
512
+ finally:
513
+ _extobj_contextvar.reset(_token)
514
+
515
+ return inner
python/user_packages/Python313/site-packages/numpy/_core/_ufunc_config.pyi ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import SupportsWrite
2
+ from collections.abc import Callable
3
+ from types import TracebackType
4
+ from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, type_check_only
5
+
6
+ __all__ = [
7
+ "seterr",
8
+ "geterr",
9
+ "setbufsize",
10
+ "getbufsize",
11
+ "seterrcall",
12
+ "geterrcall",
13
+ "errstate",
14
+ ]
15
+
16
+ _ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
17
+ _ErrCall: TypeAlias = Callable[[str, int], Any] | SupportsWrite[str]
18
+
19
+ _CallableT = TypeVar("_CallableT", bound=Callable[..., object])
20
+
21
+ @type_check_only
22
+ class _ErrDict(TypedDict):
23
+ divide: _ErrKind
24
+ over: _ErrKind
25
+ under: _ErrKind
26
+ invalid: _ErrKind
27
+
28
+ ###
29
+
30
+ class _unspecified: ...
31
+
32
+ _Unspecified: Final[_unspecified]
33
+
34
+ class errstate:
35
+ __slots__ = "_all", "_call", "_divide", "_invalid", "_over", "_token", "_under"
36
+
37
+ def __init__(
38
+ self,
39
+ /,
40
+ *,
41
+ call: _ErrCall | _unspecified = ..., # = _Unspecified
42
+ all: _ErrKind | None = None,
43
+ divide: _ErrKind | None = None,
44
+ over: _ErrKind | None = None,
45
+ under: _ErrKind | None = None,
46
+ invalid: _ErrKind | None = None,
47
+ ) -> None: ...
48
+ def __call__(self, /, func: _CallableT) -> _CallableT: ...
49
+ def __enter__(self) -> None: ...
50
+ def __exit__(
51
+ self,
52
+ exc_type: type[BaseException] | None,
53
+ exc_value: BaseException | None,
54
+ traceback: TracebackType | None,
55
+ /,
56
+ ) -> None: ...
57
+
58
+ def seterr(
59
+ all: _ErrKind | None = None,
60
+ divide: _ErrKind | None = None,
61
+ over: _ErrKind | None = None,
62
+ under: _ErrKind | None = None,
63
+ invalid: _ErrKind | None = None,
64
+ ) -> _ErrDict: ...
65
+ def geterr() -> _ErrDict: ...
66
+ def setbufsize(size: int) -> int: ...
67
+ def getbufsize() -> int: ...
68
+ def seterrcall(func: _ErrCall | None) -> _ErrCall | None: ...
69
+ def geterrcall() -> _ErrCall | None: ...
python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.cp313-win_amd64.lib ADDED
Binary file (2.1 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.cp313-win_amd64.pyd ADDED
Binary file (33.3 kB). View file
 
python/user_packages/Python313/site-packages/numpy/_core/_umath_tests.pyi ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # undocumented internal testing module for ufunc features, defined in
2
+ # numpy/_core/src/umath/_umath_tests.c.src
3
+
4
+ from typing import Final, Literal as L, TypedDict, type_check_only
5
+
6
+ import numpy as np
7
+ from numpy._typing import _GUFunc_Nin2_Nout1, _UFunc_Nin1_Nout1, _UFunc_Nin2_Nout1
8
+
9
+ @type_check_only
10
+ class _TestDispatchResult(TypedDict):
11
+ func: str # e.g. 'func_AVX2'
12
+ var: str # e.g. 'var_AVX2'
13
+ func_xb: str # e.g. 'func_AVX2'
14
+ var_xb: str # e.g. 'var_AVX2'
15
+ all: list[str] # e.g. ['func_AVX2', 'func_SSE41', 'func']
16
+
17
+ ###
18
+
19
+ # undocumented
20
+ def test_signature(
21
+ nin: int, nout: int, signature: str, /
22
+ ) -> tuple[
23
+ L[0, 1], # core_enabled (0 for scalar ufunc; 1 for generalized ufunc)
24
+ tuple[int, ...] | None, # core_num_dims
25
+ tuple[int, ...] | None, # core_dim_ixs
26
+ tuple[int, ...] | None, # core_dim_flags
27
+ tuple[int, ...] | None, # core_dim_sizes
28
+ ]: ...
29
+
30
+ # undocumented
31
+ def test_dispatch() -> _TestDispatchResult: ...
32
+
33
+ # undocumented ufuncs and gufuncs
34
+ always_error: Final[_UFunc_Nin2_Nout1[L["always_error"], L[1], None]] = ...
35
+ always_error_unary: Final[_UFunc_Nin1_Nout1[L["always_error_unary"], L[1], None]] = ...
36
+ always_error_gufunc: Final[_GUFunc_Nin2_Nout1[L["always_error_gufunc"], L[1], None, L["(i),()->()"]]] = ...
37
+ inner1d: Final[_GUFunc_Nin2_Nout1[L["inner1d"], L[2], None, L["(i),(i)->()"]]] = ...
38
+ innerwt: Final[np.ufunc] = ... # we have no specialized type for 3->1 gufuncs
39
+ matrix_multiply: Final[_GUFunc_Nin2_Nout1[L["matrix_multiply"], L[3], None, L["(m,n),(n,p)->(m,p)"]]] = ...
40
+ matmul: Final[_GUFunc_Nin2_Nout1[L["matmul"], L[3], None, L["(m?,n),(n,p?)->(m?,p?)"]]] = ...
41
+ euclidean_pdist: Final[_GUFunc_Nin2_Nout1[L["euclidean_pdist"], L[2], None, L["(n,d)->(p)"]]] = ...
42
+ cumsum: Final[np.ufunc] = ... # we have no specialized type for 1->1 gufuncs
43
+ inner1d_no_doc: Final[_GUFunc_Nin2_Nout1[L["inner1d_no_doc"], L[2], None, L["(i),(i)->()"]]] = ...
44
+ cross1d: Final[_GUFunc_Nin2_Nout1[L["cross1d"], L[2], None, L["(3),(3)->(3)"]]] = ...
45
+ _pickleable_module_global_ufunc: Final[np.ufunc] = ... # 0->0 ufunc; segfaults if called
46
+ indexed_negative: Final[_UFunc_Nin1_Nout1[L["indexed_negative"], L[0], L[0]]] = ... # ntypes=0; can't be called
47
+ conv1d_full: Final[_GUFunc_Nin2_Nout1[L["conv1d_full"], L[1], None, L["(m),(n)->(p)"]]] = ...
python/user_packages/Python313/site-packages/numpy/_core/arrayprint.py ADDED
@@ -0,0 +1,1779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Array printing function
2
+
3
+ $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
4
+
5
+ """
6
+ __all__ = ["array2string", "array_str", "array_repr",
7
+ "set_printoptions", "get_printoptions", "printoptions",
8
+ "format_float_positional", "format_float_scientific"]
9
+ __docformat__ = 'restructuredtext'
10
+
11
+ #
12
+ # Written by Konrad Hinsen <hinsenk@ere.umontreal.ca>
13
+ # last revision: 1996-3-13
14
+ # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
15
+ # and by Perry Greenfield 2000-4-1 for numarray
16
+ # and by Travis Oliphant 2005-8-22 for numpy
17
+
18
+
19
+ # Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy
20
+ # scalars but for different purposes. scalartypes.c.src has str/reprs for when
21
+ # the scalar is printed on its own, while arrayprint.py has strs for when
22
+ # scalars are printed inside an ndarray. Only the latter strs are currently
23
+ # user-customizable.
24
+
25
+ import functools
26
+ import numbers
27
+ import sys
28
+
29
+ try:
30
+ from _thread import get_ident
31
+ except ImportError:
32
+ from _dummy_thread import get_ident
33
+
34
+ import contextlib
35
+ import operator
36
+ import warnings
37
+
38
+ import numpy as np
39
+
40
+ from . import numerictypes as _nt
41
+ from .fromnumeric import any
42
+ from .multiarray import (
43
+ array,
44
+ datetime_as_string,
45
+ datetime_data,
46
+ dragon4_positional,
47
+ dragon4_scientific,
48
+ ndarray,
49
+ )
50
+ from .numeric import asarray, concatenate, errstate
51
+ from .numerictypes import complex128, flexible, float64, int_
52
+ from .overrides import array_function_dispatch, set_module
53
+ from .printoptions import format_options
54
+ from .umath import absolute, isfinite, isinf, isnat
55
+
56
+
57
+ def _make_options_dict(precision=None, threshold=None, edgeitems=None,
58
+ linewidth=None, suppress=None, nanstr=None, infstr=None,
59
+ sign=None, formatter=None, floatmode=None, legacy=None,
60
+ override_repr=None):
61
+ """
62
+ Make a dictionary out of the non-None arguments, plus conversion of
63
+ *legacy* and sanity checks.
64
+ """
65
+
66
+ options = {k: v for k, v in list(locals().items()) if v is not None}
67
+
68
+ if suppress is not None:
69
+ options['suppress'] = bool(suppress)
70
+
71
+ modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
72
+ if floatmode not in modes + [None]:
73
+ raise ValueError("floatmode option must be one of " +
74
+ ", ".join(f'"{m}"' for m in modes))
75
+
76
+ if sign not in [None, '-', '+', ' ']:
77
+ raise ValueError("sign option must be one of ' ', '+', or '-'")
78
+
79
+ if legacy is False:
80
+ options['legacy'] = sys.maxsize
81
+ elif legacy == False: # noqa: E712
82
+ warnings.warn(
83
+ f"Passing `legacy={legacy!r}` is deprecated.",
84
+ FutureWarning, stacklevel=3
85
+ )
86
+ options['legacy'] = sys.maxsize
87
+ elif legacy == '1.13':
88
+ options['legacy'] = 113
89
+ elif legacy == '1.21':
90
+ options['legacy'] = 121
91
+ elif legacy == '1.25':
92
+ options['legacy'] = 125
93
+ elif legacy == '2.1':
94
+ options['legacy'] = 201
95
+ elif legacy == '2.2':
96
+ options['legacy'] = 202
97
+ elif legacy is None:
98
+ pass # OK, do nothing.
99
+ else:
100
+ warnings.warn(
101
+ "legacy printing option can currently only be '1.13', '1.21', "
102
+ "'1.25', '2.1', '2.2' or `False`", stacklevel=3)
103
+
104
+ if threshold is not None:
105
+ # forbid the bad threshold arg suggested by stack overflow, gh-12351
106
+ if not isinstance(threshold, numbers.Number):
107
+ raise TypeError("threshold must be numeric")
108
+ if np.isnan(threshold):
109
+ raise ValueError("threshold must be non-NAN, try "
110
+ "sys.maxsize for untruncated representation")
111
+
112
+ if precision is not None:
113
+ # forbid the bad precision arg as suggested by issue #18254
114
+ try:
115
+ options['precision'] = operator.index(precision)
116
+ except TypeError as e:
117
+ raise TypeError('precision must be an integer') from e
118
+
119
+ return options
120
+
121
+
122
+ @set_module('numpy')
123
+ def set_printoptions(precision=None, threshold=None, edgeitems=None,
124
+ linewidth=None, suppress=None, nanstr=None,
125
+ infstr=None, formatter=None, sign=None, floatmode=None,
126
+ *, legacy=None, override_repr=None):
127
+ """
128
+ Set printing options.
129
+
130
+ These options determine the way floating point numbers, arrays and
131
+ other NumPy objects are displayed.
132
+
133
+ Parameters
134
+ ----------
135
+ precision : int or None, optional
136
+ Number of digits of precision for floating point output (default 8).
137
+ May be None if `floatmode` is not `fixed`, to print as many digits as
138
+ necessary to uniquely specify the value.
139
+ threshold : int, optional
140
+ Total number of array elements which trigger summarization
141
+ rather than full repr (default 1000).
142
+ To always use the full repr without summarization, pass `sys.maxsize`.
143
+ edgeitems : int, optional
144
+ Number of array items in summary at beginning and end of
145
+ each dimension (default 3).
146
+ linewidth : int, optional
147
+ The number of characters per line for the purpose of inserting
148
+ line breaks (default 75).
149
+ suppress : bool, optional
150
+ If True, always print floating point numbers using fixed point
151
+ notation, in which case numbers equal to zero in the current precision
152
+ will print as zero. If False, then scientific notation is used when
153
+ absolute value of the smallest number is < 1e-4 or the ratio of the
154
+ maximum absolute value to the minimum is > 1e3. The default is False.
155
+ nanstr : str, optional
156
+ String representation of floating point not-a-number (default nan).
157
+ infstr : str, optional
158
+ String representation of floating point infinity (default inf).
159
+ sign : string, either '-', '+', or ' ', optional
160
+ Controls printing of the sign of floating-point types. If '+', always
161
+ print the sign of positive values. If ' ', always prints a space
162
+ (whitespace character) in the sign position of positive values. If
163
+ '-', omit the sign character of positive values. (default '-')
164
+
165
+ .. versionchanged:: 2.0
166
+ The sign parameter can now be an integer type, previously
167
+ types were floating-point types.
168
+
169
+ formatter : dict of callables, optional
170
+ If not None, the keys should indicate the type(s) that the respective
171
+ formatting function applies to. Callables should return a string.
172
+ Types that are not specified (by their corresponding keys) are handled
173
+ by the default formatters. Individual types for which a formatter
174
+ can be set are:
175
+
176
+ - 'bool'
177
+ - 'int'
178
+ - 'timedelta' : a `numpy.timedelta64`
179
+ - 'datetime' : a `numpy.datetime64`
180
+ - 'float'
181
+ - 'longfloat' : 128-bit floats
182
+ - 'complexfloat'
183
+ - 'longcomplexfloat' : composed of two 128-bit floats
184
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
185
+ - 'object' : `np.object_` arrays
186
+
187
+ Other keys that can be used to set a group of types at once are:
188
+
189
+ - 'all' : sets all types
190
+ - 'int_kind' : sets 'int'
191
+ - 'float_kind' : sets 'float' and 'longfloat'
192
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
193
+ - 'str_kind' : sets 'numpystr'
194
+ floatmode : str, optional
195
+ Controls the interpretation of the `precision` option for
196
+ floating-point types. Can take the following values
197
+ (default maxprec_equal):
198
+
199
+ * 'fixed': Always print exactly `precision` fractional digits,
200
+ even if this would print more or fewer digits than
201
+ necessary to specify the value uniquely.
202
+ * 'unique': Print the minimum number of fractional digits necessary
203
+ to represent each value uniquely. Different elements may
204
+ have a different number of digits. The value of the
205
+ `precision` option is ignored.
206
+ * 'maxprec': Print at most `precision` fractional digits, but if
207
+ an element can be uniquely represented with fewer digits
208
+ only print it with that many.
209
+ * 'maxprec_equal': Print at most `precision` fractional digits,
210
+ but if every element in the array can be uniquely
211
+ represented with an equal number of fewer digits, use that
212
+ many digits for all elements.
213
+ legacy : string or `False`, optional
214
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
215
+ approximates numpy 1.13 print output by including a space in the sign
216
+ position of floats and different behavior for 0d arrays. This also
217
+ enables 1.21 legacy printing mode (described below).
218
+
219
+ If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
220
+ approximates numpy 1.21 print output of complex structured dtypes
221
+ by not inserting spaces after commas that separate fields and after
222
+ colons.
223
+
224
+ If set to ``'1.25'`` approximates printing of 1.25 which mainly means
225
+ that numeric scalars are printed without their type information, e.g.
226
+ as ``3.0`` rather than ``np.float64(3.0)``.
227
+
228
+ If set to ``'2.1'``, shape information is not given when arrays are
229
+ summarized (i.e., multiple elements replaced with ``...``).
230
+
231
+ If set to ``'2.2'``, the transition to use scientific notation for
232
+ printing ``np.float16`` and ``np.float32`` types may happen later or
233
+ not at all for larger values.
234
+
235
+ If set to `False`, disables legacy mode.
236
+
237
+ Unrecognized strings will be ignored with a warning for forward
238
+ compatibility.
239
+
240
+ .. versionchanged:: 1.22.0
241
+ .. versionchanged:: 2.2
242
+
243
+ override_repr: callable, optional
244
+ If set a passed function will be used for generating arrays' repr.
245
+ Other options will be ignored.
246
+
247
+ See Also
248
+ --------
249
+ get_printoptions, printoptions, array2string
250
+
251
+
252
+ Notes
253
+ -----
254
+
255
+ * ``formatter`` is always reset with a call to `set_printoptions`.
256
+ * Use `printoptions` as a context manager to set the values temporarily.
257
+ * These print options apply only to NumPy ndarrays, not to scalars.
258
+
259
+ **Concurrency note:** see :ref:`text_formatting_options`
260
+
261
+ Examples
262
+ --------
263
+ Floating point precision can be set:
264
+
265
+ >>> import numpy as np
266
+ >>> np.set_printoptions(precision=4)
267
+ >>> np.array([1.123456789])
268
+ [1.1235]
269
+
270
+ Long arrays can be summarised:
271
+
272
+ >>> np.set_printoptions(threshold=5)
273
+ >>> np.arange(10)
274
+ array([0, 1, 2, ..., 7, 8, 9], shape=(10,))
275
+
276
+ Small results can be suppressed:
277
+
278
+ >>> eps = np.finfo(float).eps
279
+ >>> x = np.arange(4.)
280
+ >>> x**2 - (x + eps)**2
281
+ array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
282
+ >>> np.set_printoptions(suppress=True)
283
+ >>> x**2 - (x + eps)**2
284
+ array([-0., -0., 0., 0.])
285
+
286
+ A custom formatter can be used to display array elements as desired:
287
+
288
+ >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
289
+ >>> x = np.arange(3)
290
+ >>> x
291
+ array([int: 0, int: -1, int: -2])
292
+ >>> np.set_printoptions() # formatter gets reset
293
+ >>> x
294
+ array([0, 1, 2])
295
+
296
+ To put back the default options, you can use:
297
+
298
+ >>> np.set_printoptions(edgeitems=3, infstr='inf',
299
+ ... linewidth=75, nanstr='nan', precision=8,
300
+ ... suppress=False, threshold=1000, formatter=None)
301
+
302
+ Also to temporarily override options, use `printoptions`
303
+ as a context manager:
304
+
305
+ >>> with np.printoptions(precision=2, suppress=True, threshold=5):
306
+ ... np.linspace(0, 10, 10)
307
+ array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ], shape=(10,))
308
+
309
+ """
310
+ _set_printoptions(precision, threshold, edgeitems, linewidth, suppress,
311
+ nanstr, infstr, formatter, sign, floatmode,
312
+ legacy=legacy, override_repr=override_repr)
313
+
314
+
315
+ def _set_printoptions(precision=None, threshold=None, edgeitems=None,
316
+ linewidth=None, suppress=None, nanstr=None,
317
+ infstr=None, formatter=None, sign=None, floatmode=None,
318
+ *, legacy=None, override_repr=None):
319
+ new_opt = _make_options_dict(precision, threshold, edgeitems, linewidth,
320
+ suppress, nanstr, infstr, sign, formatter,
321
+ floatmode, legacy)
322
+ # formatter and override_repr are always reset
323
+ new_opt['formatter'] = formatter
324
+ new_opt['override_repr'] = override_repr
325
+
326
+ updated_opt = format_options.get() | new_opt
327
+ updated_opt.update(new_opt)
328
+
329
+ if updated_opt['legacy'] == 113:
330
+ updated_opt['sign'] = '-'
331
+
332
+ return format_options.set(updated_opt)
333
+
334
+
335
+ @set_module('numpy')
336
+ def get_printoptions():
337
+ """
338
+ Return the current print options.
339
+
340
+ Returns
341
+ -------
342
+ print_opts : dict
343
+ Dictionary of current print options with keys
344
+
345
+ - precision : int
346
+ - threshold : int
347
+ - edgeitems : int
348
+ - linewidth : int
349
+ - suppress : bool
350
+ - nanstr : str
351
+ - infstr : str
352
+ - sign : str
353
+ - formatter : dict of callables
354
+ - floatmode : str
355
+ - legacy : str or False
356
+
357
+ For a full description of these options, see `set_printoptions`.
358
+
359
+ Notes
360
+ -----
361
+ These print options apply only to NumPy ndarrays, not to scalars.
362
+
363
+ **Concurrency note:** see :ref:`text_formatting_options`
364
+
365
+ See Also
366
+ --------
367
+ set_printoptions, printoptions
368
+
369
+ Examples
370
+ --------
371
+ >>> import numpy as np
372
+
373
+ >>> np.get_printoptions()
374
+ {'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
375
+
376
+ >>> np.get_printoptions()['linewidth']
377
+ 75
378
+ >>> np.set_printoptions(linewidth=100)
379
+ >>> np.get_printoptions()['linewidth']
380
+ 100
381
+
382
+ """
383
+ opts = format_options.get().copy()
384
+ opts['legacy'] = {
385
+ 113: '1.13', 121: '1.21', 125: '1.25', 201: '2.1',
386
+ 202: '2.2', sys.maxsize: False,
387
+ }[opts['legacy']]
388
+ return opts
389
+
390
+
391
+ def _get_legacy_print_mode():
392
+ """Return the legacy print mode as an int."""
393
+ return format_options.get()['legacy']
394
+
395
+
396
+ @set_module('numpy')
397
+ @contextlib.contextmanager
398
+ def printoptions(*args, **kwargs):
399
+ """Context manager for setting print options.
400
+
401
+ Set print options for the scope of the `with` block, and restore the old
402
+ options at the end. See `set_printoptions` for the full description of
403
+ available options.
404
+
405
+ Examples
406
+ --------
407
+ >>> import numpy as np
408
+
409
+ >>> from numpy.testing import assert_equal
410
+ >>> with np.printoptions(precision=2):
411
+ ... np.array([2.0]) / 3
412
+ array([0.67])
413
+
414
+ The `as`-clause of the `with`-statement gives the current print options:
415
+
416
+ >>> with np.printoptions(precision=2) as opts:
417
+ ... assert_equal(opts, np.get_printoptions())
418
+
419
+ See Also
420
+ --------
421
+ set_printoptions, get_printoptions
422
+
423
+ Notes
424
+ -----
425
+ These print options apply only to NumPy ndarrays, not to scalars.
426
+
427
+ **Concurrency note:** see :ref:`text_formatting_options`
428
+
429
+ """
430
+ token = _set_printoptions(*args, **kwargs)
431
+
432
+ try:
433
+ yield get_printoptions()
434
+ finally:
435
+ format_options.reset(token)
436
+
437
+
438
+ def _leading_trailing(a, edgeitems, index=()):
439
+ """
440
+ Keep only the N-D corners (leading and trailing edges) of an array.
441
+
442
+ Should be passed a base-class ndarray, since it makes no guarantees about
443
+ preserving subclasses.
444
+ """
445
+ axis = len(index)
446
+ if axis == a.ndim:
447
+ return a[index]
448
+
449
+ if a.shape[axis] > 2 * edgeitems:
450
+ return concatenate((
451
+ _leading_trailing(a, edgeitems, index + np.index_exp[:edgeitems]),
452
+ _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:])
453
+ ), axis=axis)
454
+ else:
455
+ return _leading_trailing(a, edgeitems, index + np.index_exp[:])
456
+
457
+
458
+ def _object_format(o):
459
+ """ Object arrays containing lists should be printed unambiguously """
460
+ if type(o) is list:
461
+ fmt = 'list({!r})'
462
+ else:
463
+ fmt = '{!r}'
464
+ return fmt.format(o)
465
+
466
+ def repr_format(x):
467
+ if isinstance(x, (np.str_, np.bytes_)):
468
+ return repr(x.item())
469
+ return repr(x)
470
+
471
+ def str_format(x):
472
+ if isinstance(x, (np.str_, np.bytes_)):
473
+ return str(x.item())
474
+ return str(x)
475
+
476
+ def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy,
477
+ formatter, **kwargs):
478
+ # note: extra arguments in kwargs are ignored
479
+
480
+ # wrapped in lambdas to avoid taking a code path
481
+ # with the wrong type of data
482
+ formatdict = {
483
+ 'bool': lambda: BoolFormat(data),
484
+ 'int': lambda: IntegerFormat(data, sign),
485
+ 'float': lambda: FloatingFormat(
486
+ data, precision, floatmode, suppress, sign, legacy=legacy),
487
+ 'longfloat': lambda: FloatingFormat(
488
+ data, precision, floatmode, suppress, sign, legacy=legacy),
489
+ 'complexfloat': lambda: ComplexFloatingFormat(
490
+ data, precision, floatmode, suppress, sign, legacy=legacy),
491
+ 'longcomplexfloat': lambda: ComplexFloatingFormat(
492
+ data, precision, floatmode, suppress, sign, legacy=legacy),
493
+ 'datetime': lambda: DatetimeFormat(data, legacy=legacy),
494
+ 'timedelta': lambda: TimedeltaFormat(data),
495
+ 'object': lambda: _object_format,
496
+ 'void': lambda: str_format,
497
+ 'numpystr': lambda: repr_format}
498
+
499
+ # we need to wrap values in `formatter` in a lambda, so that the interface
500
+ # is the same as the above values.
501
+ def indirect(x):
502
+ return lambda: x
503
+
504
+ if formatter is not None:
505
+ fkeys = [k for k in formatter.keys() if formatter[k] is not None]
506
+ if 'all' in fkeys:
507
+ for key in formatdict.keys():
508
+ formatdict[key] = indirect(formatter['all'])
509
+ if 'int_kind' in fkeys:
510
+ for key in ['int']:
511
+ formatdict[key] = indirect(formatter['int_kind'])
512
+ if 'float_kind' in fkeys:
513
+ for key in ['float', 'longfloat']:
514
+ formatdict[key] = indirect(formatter['float_kind'])
515
+ if 'complex_kind' in fkeys:
516
+ for key in ['complexfloat', 'longcomplexfloat']:
517
+ formatdict[key] = indirect(formatter['complex_kind'])
518
+ if 'str_kind' in fkeys:
519
+ formatdict['numpystr'] = indirect(formatter['str_kind'])
520
+ for key in formatdict.keys():
521
+ if key in fkeys:
522
+ formatdict[key] = indirect(formatter[key])
523
+
524
+ return formatdict
525
+
526
+ def _get_format_function(data, **options):
527
+ """
528
+ find the right formatting function for the dtype_
529
+ """
530
+ dtype_ = data.dtype
531
+ dtypeobj = dtype_.type
532
+ formatdict = _get_formatdict(data, **options)
533
+ if dtypeobj is None:
534
+ return formatdict["numpystr"]()
535
+ elif issubclass(dtypeobj, _nt.bool):
536
+ return formatdict['bool']()
537
+ elif issubclass(dtypeobj, _nt.integer):
538
+ if issubclass(dtypeobj, _nt.timedelta64):
539
+ return formatdict['timedelta']()
540
+ else:
541
+ return formatdict['int']()
542
+ elif issubclass(dtypeobj, _nt.floating):
543
+ if issubclass(dtypeobj, _nt.longdouble):
544
+ return formatdict['longfloat']()
545
+ else:
546
+ return formatdict['float']()
547
+ elif issubclass(dtypeobj, _nt.complexfloating):
548
+ if issubclass(dtypeobj, _nt.clongdouble):
549
+ return formatdict['longcomplexfloat']()
550
+ else:
551
+ return formatdict['complexfloat']()
552
+ elif issubclass(dtypeobj, (_nt.str_, _nt.bytes_)):
553
+ return formatdict['numpystr']()
554
+ elif issubclass(dtypeobj, _nt.datetime64):
555
+ return formatdict['datetime']()
556
+ elif issubclass(dtypeobj, _nt.object_):
557
+ return formatdict['object']()
558
+ elif issubclass(dtypeobj, _nt.void):
559
+ if dtype_.names is not None:
560
+ return StructuredVoidFormat.from_data(data, **options)
561
+ else:
562
+ return formatdict['void']()
563
+ else:
564
+ return formatdict['numpystr']()
565
+
566
+
567
+ def _recursive_guard(fillvalue='...'):
568
+ """
569
+ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
570
+
571
+ Decorates a function such that if it calls itself with the same first
572
+ argument, it returns `fillvalue` instead of recursing.
573
+
574
+ Largely copied from reprlib.recursive_repr
575
+ """
576
+
577
+ def decorating_function(f):
578
+ repr_running = set()
579
+
580
+ @functools.wraps(f)
581
+ def wrapper(self, *args, **kwargs):
582
+ key = id(self), get_ident()
583
+ if key in repr_running:
584
+ return fillvalue
585
+ repr_running.add(key)
586
+ try:
587
+ return f(self, *args, **kwargs)
588
+ finally:
589
+ repr_running.discard(key)
590
+
591
+ return wrapper
592
+
593
+ return decorating_function
594
+
595
+
596
+ # gracefully handle recursive calls, when object arrays contain themselves
597
+ @_recursive_guard()
598
+ def _array2string(a, options, separator=' ', prefix=""):
599
+ # The formatter __init__s in _get_format_function cannot deal with
600
+ # subclasses yet, and we also need to avoid recursion issues in
601
+ # _formatArray with subclasses which return 0d arrays in place of scalars
602
+ data = asarray(a)
603
+ if a.shape == ():
604
+ a = data
605
+
606
+ if a.size > options['threshold']:
607
+ summary_insert = "..."
608
+ data = _leading_trailing(data, options['edgeitems'])
609
+ else:
610
+ summary_insert = ""
611
+
612
+ # find the right formatting function for the array
613
+ format_function = _get_format_function(data, **options)
614
+
615
+ # skip over "["
616
+ next_line_prefix = " "
617
+ # skip over array(
618
+ next_line_prefix += " " * len(prefix)
619
+
620
+ lst = _formatArray(a, format_function, options['linewidth'],
621
+ next_line_prefix, separator, options['edgeitems'],
622
+ summary_insert, options['legacy'])
623
+ return lst
624
+
625
+
626
+ def _array2string_dispatcher(
627
+ a, max_line_width=None, precision=None,
628
+ suppress_small=None, separator=None, prefix=None,
629
+ *, formatter=None, threshold=None,
630
+ edgeitems=None, sign=None, floatmode=None, suffix=None,
631
+ legacy=None):
632
+ return (a,)
633
+
634
+
635
+ @array_function_dispatch(_array2string_dispatcher, module='numpy')
636
+ def array2string(a, max_line_width=None, precision=None,
637
+ suppress_small=None, separator=' ', prefix="",
638
+ *, formatter=None, threshold=None,
639
+ edgeitems=None, sign=None, floatmode=None, suffix="",
640
+ legacy=None):
641
+ """
642
+ Return a string representation of an array.
643
+
644
+ Parameters
645
+ ----------
646
+ a : ndarray
647
+ Input array.
648
+ max_line_width : int, optional
649
+ Inserts newlines if text is longer than `max_line_width`.
650
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
651
+ precision : int or None, optional
652
+ Floating point precision.
653
+ Defaults to ``numpy.get_printoptions()['precision']``.
654
+ suppress_small : bool, optional
655
+ Represent numbers "very close" to zero as zero; default is False.
656
+ Very close is defined by precision: if the precision is 8, e.g.,
657
+ numbers smaller (in absolute value) than 5e-9 are represented as
658
+ zero.
659
+ Defaults to ``numpy.get_printoptions()['suppress']``.
660
+ separator : str, optional
661
+ Inserted between elements.
662
+ prefix : str, optional
663
+ suffix : str, optional
664
+ The length of the prefix and suffix strings are used to respectively
665
+ align and wrap the output. An array is typically printed as::
666
+
667
+ prefix + array2string(a) + suffix
668
+
669
+ The output is left-padded by the length of the prefix string, and
670
+ wrapping is forced at the column ``max_line_width - len(suffix)``.
671
+ It should be noted that the content of prefix and suffix strings are
672
+ not included in the output.
673
+ formatter : dict of callables, optional
674
+ If not None, the keys should indicate the type(s) that the respective
675
+ formatting function applies to. Callables should return a string.
676
+ Types that are not specified (by their corresponding keys) are handled
677
+ by the default formatters. Individual types for which a formatter
678
+ can be set are:
679
+
680
+ - 'bool'
681
+ - 'int'
682
+ - 'timedelta' : a `numpy.timedelta64`
683
+ - 'datetime' : a `numpy.datetime64`
684
+ - 'float'
685
+ - 'longfloat' : 128-bit floats
686
+ - 'complexfloat'
687
+ - 'longcomplexfloat' : composed of two 128-bit floats
688
+ - 'void' : type `numpy.void`
689
+ - 'numpystr' : types `numpy.bytes_` and `numpy.str_`
690
+
691
+ Other keys that can be used to set a group of types at once are:
692
+
693
+ - 'all' : sets all types
694
+ - 'int_kind' : sets 'int'
695
+ - 'float_kind' : sets 'float' and 'longfloat'
696
+ - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
697
+ - 'str_kind' : sets 'numpystr'
698
+ threshold : int, optional
699
+ Total number of array elements which trigger summarization
700
+ rather than full repr.
701
+ Defaults to ``numpy.get_printoptions()['threshold']``.
702
+ edgeitems : int, optional
703
+ Number of array items in summary at beginning and end of
704
+ each dimension.
705
+ Defaults to ``numpy.get_printoptions()['edgeitems']``.
706
+ sign : string, either '-', '+', or ' ', optional
707
+ Controls printing of the sign of floating-point types. If '+', always
708
+ print the sign of positive values. If ' ', always prints a space
709
+ (whitespace character) in the sign position of positive values. If
710
+ '-', omit the sign character of positive values.
711
+ Defaults to ``numpy.get_printoptions()['sign']``.
712
+
713
+ .. versionchanged:: 2.0
714
+ The sign parameter can now be an integer type, previously
715
+ types were floating-point types.
716
+
717
+ floatmode : str, optional
718
+ Controls the interpretation of the `precision` option for
719
+ floating-point types.
720
+ Defaults to ``numpy.get_printoptions()['floatmode']``.
721
+ Can take the following values:
722
+
723
+ - 'fixed': Always print exactly `precision` fractional digits,
724
+ even if this would print more or fewer digits than
725
+ necessary to specify the value uniquely.
726
+ - 'unique': Print the minimum number of fractional digits necessary
727
+ to represent each value uniquely. Different elements may
728
+ have a different number of digits. The value of the
729
+ `precision` option is ignored.
730
+ - 'maxprec': Print at most `precision` fractional digits, but if
731
+ an element can be uniquely represented with fewer digits
732
+ only print it with that many.
733
+ - 'maxprec_equal': Print at most `precision` fractional digits,
734
+ but if every element in the array can be uniquely
735
+ represented with an equal number of fewer digits, use that
736
+ many digits for all elements.
737
+ legacy : string or `False`, optional
738
+ If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
739
+ approximates numpy 1.13 print output by including a space in the sign
740
+ position of floats and different behavior for 0d arrays. If set to
741
+ `False`, disables legacy mode. Unrecognized strings will be ignored
742
+ with a warning for forward compatibility.
743
+
744
+ Returns
745
+ -------
746
+ array_str : str
747
+ String representation of the array.
748
+
749
+ Raises
750
+ ------
751
+ TypeError
752
+ if a callable in `formatter` does not return a string.
753
+
754
+ See Also
755
+ --------
756
+ array_str, array_repr, set_printoptions, get_printoptions
757
+
758
+ Notes
759
+ -----
760
+ If a formatter is specified for a certain type, the `precision` keyword is
761
+ ignored for that type.
762
+
763
+ This is a very flexible function; `array_repr` and `array_str` are using
764
+ `array2string` internally so keywords with the same name should work
765
+ identically in all three functions.
766
+
767
+ Examples
768
+ --------
769
+ >>> import numpy as np
770
+ >>> x = np.array([1e-16,1,2,3])
771
+ >>> np.array2string(x, precision=2, separator=',',
772
+ ... suppress_small=True)
773
+ '[0.,1.,2.,3.]'
774
+
775
+ >>> x = np.arange(3.)
776
+ >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
777
+ '[0.00 1.00 2.00]'
778
+
779
+ >>> x = np.arange(3)
780
+ >>> np.array2string(x, formatter={'int':lambda x: hex(x)})
781
+ '[0x0 0x1 0x2]'
782
+
783
+ """
784
+
785
+ overrides = _make_options_dict(precision, threshold, edgeitems,
786
+ max_line_width, suppress_small, None, None,
787
+ sign, formatter, floatmode, legacy)
788
+ options = format_options.get().copy()
789
+ options.update(overrides)
790
+
791
+ if options['legacy'] <= 113:
792
+ if a.shape == () and a.dtype.names is None:
793
+ return repr(a.item())
794
+
795
+ if options['legacy'] > 113:
796
+ options['linewidth'] -= len(suffix)
797
+
798
+ # treat as a null array if any of shape elements == 0
799
+ if a.size == 0:
800
+ return "[]"
801
+
802
+ return _array2string(a, options, separator, prefix)
803
+
804
+
805
+ def _extendLine(s, line, word, line_width, next_line_prefix, legacy):
806
+ needs_wrap = len(line) + len(word) > line_width
807
+ if legacy > 113:
808
+ # don't wrap lines if it won't help
809
+ if len(line) <= len(next_line_prefix):
810
+ needs_wrap = False
811
+
812
+ if needs_wrap:
813
+ s += line.rstrip() + "\n"
814
+ line = next_line_prefix
815
+ line += word
816
+ return s, line
817
+
818
+
819
+ def _extendLine_pretty(s, line, word, line_width, next_line_prefix, legacy):
820
+ """
821
+ Extends line with nicely formatted (possibly multi-line) string ``word``.
822
+ """
823
+ words = word.splitlines()
824
+ if len(words) == 1 or legacy <= 113:
825
+ return _extendLine(s, line, word, line_width, next_line_prefix, legacy)
826
+
827
+ max_word_length = max(len(word) for word in words)
828
+ if (len(line) + max_word_length > line_width and
829
+ len(line) > len(next_line_prefix)):
830
+ s += line.rstrip() + '\n'
831
+ line = next_line_prefix + words[0]
832
+ indent = next_line_prefix
833
+ else:
834
+ indent = len(line) * ' '
835
+ line += words[0]
836
+
837
+ for word in words[1::]:
838
+ s += line.rstrip() + '\n'
839
+ line = indent + word
840
+
841
+ suffix_length = max_word_length - len(words[-1])
842
+ line += suffix_length * ' '
843
+
844
+ return s, line
845
+
846
+ def _formatArray(a, format_function, line_width, next_line_prefix,
847
+ separator, edge_items, summary_insert, legacy):
848
+ """formatArray is designed for two modes of operation:
849
+
850
+ 1. Full output
851
+
852
+ 2. Summarized output
853
+
854
+ """
855
+ def recurser(index, hanging_indent, curr_width):
856
+ """
857
+ By using this local function, we don't need to recurse with all the
858
+ arguments. Since this function is not created recursively, the cost is
859
+ not significant
860
+ """
861
+ axis = len(index)
862
+ axes_left = a.ndim - axis
863
+
864
+ if axes_left == 0:
865
+ return format_function(a[index])
866
+
867
+ # when recursing, add a space to align with the [ added, and reduce the
868
+ # length of the line by 1
869
+ next_hanging_indent = hanging_indent + ' '
870
+ if legacy <= 113:
871
+ next_width = curr_width
872
+ else:
873
+ next_width = curr_width - len(']')
874
+
875
+ a_len = a.shape[axis]
876
+ show_summary = summary_insert and 2 * edge_items < a_len
877
+ if show_summary:
878
+ leading_items = edge_items
879
+ trailing_items = edge_items
880
+ else:
881
+ leading_items = 0
882
+ trailing_items = a_len
883
+
884
+ # stringify the array with the hanging indent on the first line too
885
+ s = ''
886
+
887
+ # last axis (rows) - wrap elements if they would not fit on one line
888
+ if axes_left == 1:
889
+ # the length up until the beginning of the separator / bracket
890
+ if legacy <= 113:
891
+ elem_width = curr_width - len(separator.rstrip())
892
+ else:
893
+ elem_width = curr_width - max(
894
+ len(separator.rstrip()), len(']')
895
+ )
896
+
897
+ line = hanging_indent
898
+ for i in range(leading_items):
899
+ word = recurser(index + (i,), next_hanging_indent, next_width)
900
+ s, line = _extendLine_pretty(
901
+ s, line, word, elem_width, hanging_indent, legacy)
902
+ line += separator
903
+
904
+ if show_summary:
905
+ s, line = _extendLine(
906
+ s, line, summary_insert, elem_width, hanging_indent, legacy
907
+ )
908
+ if legacy <= 113:
909
+ line += ", "
910
+ else:
911
+ line += separator
912
+
913
+ for i in range(trailing_items, 1, -1):
914
+ word = recurser(index + (-i,), next_hanging_indent, next_width)
915
+ s, line = _extendLine_pretty(
916
+ s, line, word, elem_width, hanging_indent, legacy)
917
+ line += separator
918
+
919
+ if legacy <= 113:
920
+ # width of the separator is not considered on 1.13
921
+ elem_width = curr_width
922
+ word = recurser(index + (-1,), next_hanging_indent, next_width)
923
+ s, line = _extendLine_pretty(
924
+ s, line, word, elem_width, hanging_indent, legacy)
925
+
926
+ s += line
927
+
928
+ # other axes - insert newlines between rows
929
+ else:
930
+ s = ''
931
+ line_sep = separator.rstrip() + '\n' * (axes_left - 1)
932
+
933
+ for i in range(leading_items):
934
+ nested = recurser(
935
+ index + (i,), next_hanging_indent, next_width
936
+ )
937
+ s += hanging_indent + nested + line_sep
938
+
939
+ if show_summary:
940
+ if legacy <= 113:
941
+ # trailing space, fixed nbr of newlines,
942
+ # and fixed separator
943
+ s += hanging_indent + summary_insert + ", \n"
944
+ else:
945
+ s += hanging_indent + summary_insert + line_sep
946
+
947
+ for i in range(trailing_items, 1, -1):
948
+ nested = recurser(index + (-i,), next_hanging_indent,
949
+ next_width)
950
+ s += hanging_indent + nested + line_sep
951
+
952
+ nested = recurser(index + (-1,), next_hanging_indent, next_width)
953
+ s += hanging_indent + nested
954
+
955
+ # remove the hanging indent, and wrap in []
956
+ s = '[' + s[len(hanging_indent):] + ']'
957
+ return s
958
+
959
+ try:
960
+ # invoke the recursive part with an initial index and prefix
961
+ return recurser(index=(),
962
+ hanging_indent=next_line_prefix,
963
+ curr_width=line_width)
964
+ finally:
965
+ # recursive closures have a cyclic reference to themselves, which
966
+ # requires gc to collect (gh-10620). To avoid this problem, for
967
+ # performance and PyPy friendliness, we break the cycle:
968
+ recurser = None
969
+
970
+ def _none_or_positive_arg(x, name):
971
+ if x is None:
972
+ return -1
973
+ if x < 0:
974
+ raise ValueError(f"{name} must be >= 0")
975
+ return x
976
+
977
+ class FloatingFormat:
978
+ """ Formatter for subtypes of np.floating """
979
+ def __init__(self, data, precision, floatmode, suppress_small, sign=False,
980
+ *, legacy=None):
981
+ # for backcompatibility, accept bools
982
+ if isinstance(sign, bool):
983
+ sign = '+' if sign else '-'
984
+
985
+ self._legacy = legacy
986
+ if self._legacy <= 113:
987
+ # when not 0d, legacy does not support '-'
988
+ if data.shape != () and sign == '-':
989
+ sign = ' '
990
+
991
+ self.floatmode = floatmode
992
+ if floatmode == 'unique':
993
+ self.precision = None
994
+ else:
995
+ self.precision = precision
996
+
997
+ self.precision = _none_or_positive_arg(self.precision, 'precision')
998
+
999
+ self.suppress_small = suppress_small
1000
+ self.sign = sign
1001
+ self.exp_format = False
1002
+ self.large_exponent = False
1003
+ self.fillFormat(data)
1004
+
1005
+ def fillFormat(self, data):
1006
+ # only the finite values are used to compute the number of digits
1007
+ finite_vals = data[isfinite(data)]
1008
+
1009
+ # choose exponential mode based on the non-zero finite values:
1010
+ abs_non_zero = absolute(finite_vals[finite_vals != 0])
1011
+ if len(abs_non_zero) != 0:
1012
+ max_val = np.max(abs_non_zero)
1013
+ min_val = np.min(abs_non_zero)
1014
+ if self._legacy <= 202:
1015
+ exp_cutoff_max = 1.e8
1016
+ else:
1017
+ # consider data type while deciding the max cutoff for exp format
1018
+ exp_cutoff_max = 10.**min(8, np.finfo(data.dtype).precision)
1019
+ with errstate(over='ignore'): # division can overflow
1020
+ if max_val >= exp_cutoff_max or (not self.suppress_small and
1021
+ (min_val < 0.0001 or max_val / min_val > 1000.)):
1022
+ self.exp_format = True
1023
+
1024
+ # do a first pass of printing all the numbers, to determine sizes
1025
+ if len(finite_vals) == 0:
1026
+ self.pad_left = 0
1027
+ self.pad_right = 0
1028
+ self.trim = '.'
1029
+ self.exp_size = -1
1030
+ self.unique = True
1031
+ self.min_digits = None
1032
+ elif self.exp_format:
1033
+ trim, unique = '.', True
1034
+ if self.floatmode == 'fixed' or self._legacy <= 113:
1035
+ trim, unique = 'k', False
1036
+ strs = (dragon4_scientific(x, precision=self.precision,
1037
+ unique=unique, trim=trim, sign=self.sign == '+')
1038
+ for x in finite_vals)
1039
+ frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
1040
+ int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
1041
+ self.exp_size = max(len(s) for s in exp_strs) - 1
1042
+
1043
+ self.trim = 'k'
1044
+ self.precision = max(len(s) for s in frac_part)
1045
+ self.min_digits = self.precision
1046
+ self.unique = unique
1047
+
1048
+ # for back-compat with np 1.13, use 2 spaces & sign and full prec
1049
+ if self._legacy <= 113:
1050
+ self.pad_left = 3
1051
+ else:
1052
+ # this should be only 1 or 2. Can be calculated from sign.
1053
+ self.pad_left = max(len(s) for s in int_part)
1054
+ # pad_right is only needed for nan length calculation
1055
+ self.pad_right = self.exp_size + 2 + self.precision
1056
+ else:
1057
+ trim, unique = '.', True
1058
+ if self.floatmode == 'fixed':
1059
+ trim, unique = 'k', False
1060
+ strs = (dragon4_positional(x, precision=self.precision,
1061
+ fractional=True,
1062
+ unique=unique, trim=trim,
1063
+ sign=self.sign == '+')
1064
+ for x in finite_vals)
1065
+ int_part, frac_part = zip(*(s.split('.') for s in strs))
1066
+ if self._legacy <= 113:
1067
+ self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part)
1068
+ else:
1069
+ self.pad_left = max(len(s) for s in int_part)
1070
+ self.pad_right = max(len(s) for s in frac_part)
1071
+ self.exp_size = -1
1072
+ self.unique = unique
1073
+
1074
+ if self.floatmode in ['fixed', 'maxprec_equal']:
1075
+ self.precision = self.min_digits = self.pad_right
1076
+ self.trim = 'k'
1077
+ else:
1078
+ self.trim = '.'
1079
+ self.min_digits = 0
1080
+
1081
+ if self._legacy > 113:
1082
+ # account for sign = ' ' by adding one to pad_left
1083
+ if self.sign == ' ' and not any(np.signbit(finite_vals)):
1084
+ self.pad_left += 1
1085
+
1086
+ # if there are non-finite values, may need to increase pad_left
1087
+ if data.size != finite_vals.size:
1088
+ neginf = self.sign != '-' or any(data[isinf(data)] < 0)
1089
+ offset = self.pad_right + 1 # +1 for decimal pt
1090
+ current_options = format_options.get()
1091
+ self.pad_left = max(
1092
+ self.pad_left, len(current_options['nanstr']) - offset,
1093
+ len(current_options['infstr']) + neginf - offset
1094
+ )
1095
+
1096
+ def __call__(self, x):
1097
+ if not np.isfinite(x):
1098
+ with errstate(invalid='ignore'):
1099
+ current_options = format_options.get()
1100
+ if np.isnan(x):
1101
+ sign = '+' if self.sign == '+' else ''
1102
+ ret = sign + current_options['nanstr']
1103
+ else: # isinf
1104
+ sign = '-' if x < 0 else '+' if self.sign == '+' else ''
1105
+ ret = sign + current_options['infstr']
1106
+ return ' ' * (
1107
+ self.pad_left + self.pad_right + 1 - len(ret)
1108
+ ) + ret
1109
+
1110
+ if self.exp_format:
1111
+ return dragon4_scientific(x,
1112
+ precision=self.precision,
1113
+ min_digits=self.min_digits,
1114
+ unique=self.unique,
1115
+ trim=self.trim,
1116
+ sign=self.sign == '+',
1117
+ pad_left=self.pad_left,
1118
+ exp_digits=self.exp_size)
1119
+ else:
1120
+ return dragon4_positional(x,
1121
+ precision=self.precision,
1122
+ min_digits=self.min_digits,
1123
+ unique=self.unique,
1124
+ fractional=True,
1125
+ trim=self.trim,
1126
+ sign=self.sign == '+',
1127
+ pad_left=self.pad_left,
1128
+ pad_right=self.pad_right)
1129
+
1130
+
1131
+ @set_module('numpy')
1132
+ def format_float_scientific(x, precision=None, unique=True, trim='k',
1133
+ sign=False, pad_left=None, exp_digits=None,
1134
+ min_digits=None):
1135
+ """
1136
+ Format a floating-point scalar as a decimal string in scientific notation.
1137
+
1138
+ Provides control over rounding, trimming and padding. Uses and assumes
1139
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
1140
+
1141
+ Parameters
1142
+ ----------
1143
+ x : python float or numpy floating scalar
1144
+ Value to format.
1145
+ precision : non-negative integer or None, optional
1146
+ Maximum number of digits to print. May be None if `unique` is
1147
+ `True`, but must be an integer if unique is `False`.
1148
+ unique : boolean, optional
1149
+ If `True`, use a digit-generation strategy which gives the shortest
1150
+ representation which uniquely identifies the floating-point number from
1151
+ other values of the same type, by judicious rounding. If `precision`
1152
+ is given fewer digits than necessary can be printed. If `min_digits`
1153
+ is given more can be printed, in which cases the last digit is rounded
1154
+ with unbiased rounding.
1155
+ If `False`, digits are generated as if printing an infinite-precision
1156
+ value and stopping after `precision` digits, rounding the remaining
1157
+ value with unbiased rounding
1158
+ trim : one of 'k', '.', '0', '-', optional
1159
+ Controls post-processing trimming of trailing digits, as follows:
1160
+
1161
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
1162
+ * '.' : trim all trailing zeros, leave decimal point
1163
+ * '0' : trim all but the zero before the decimal point. Insert the
1164
+ zero if it is missing.
1165
+ * '-' : trim trailing zeros and any trailing decimal point
1166
+ sign : boolean, optional
1167
+ Whether to show the sign for positive values.
1168
+ pad_left : non-negative integer, optional
1169
+ Pad the left side of the string with whitespace until at least that
1170
+ many characters are to the left of the decimal point.
1171
+ exp_digits : non-negative integer, optional
1172
+ Pad the exponent with zeros until it contains at least this
1173
+ many digits. If omitted, the exponent will be at least 2 digits.
1174
+ min_digits : non-negative integer or None, optional
1175
+ Minimum number of digits to print. This only has an effect for
1176
+ `unique=True`. In that case more digits than necessary to uniquely
1177
+ identify the value may be printed and rounded unbiased.
1178
+
1179
+ .. versionadded:: 1.21.0
1180
+
1181
+ Returns
1182
+ -------
1183
+ rep : string
1184
+ The string representation of the floating point value
1185
+
1186
+ See Also
1187
+ --------
1188
+ format_float_positional
1189
+
1190
+ Examples
1191
+ --------
1192
+ >>> import numpy as np
1193
+ >>> np.format_float_scientific(np.float32(np.pi))
1194
+ '3.1415927e+00'
1195
+ >>> s = np.float32(1.23e24)
1196
+ >>> np.format_float_scientific(s, unique=False, precision=15)
1197
+ '1.230000071797338e+24'
1198
+ >>> np.format_float_scientific(s, exp_digits=4)
1199
+ '1.23e+0024'
1200
+ """
1201
+ precision = _none_or_positive_arg(precision, 'precision')
1202
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
1203
+ exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits')
1204
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
1205
+ if min_digits > 0 and precision > 0 and min_digits > precision:
1206
+ raise ValueError("min_digits must be less than or equal to precision")
1207
+ return dragon4_scientific(x, precision=precision, unique=unique,
1208
+ trim=trim, sign=sign, pad_left=pad_left,
1209
+ exp_digits=exp_digits, min_digits=min_digits)
1210
+
1211
+
1212
+ @set_module('numpy')
1213
+ def format_float_positional(x, precision=None, unique=True,
1214
+ fractional=True, trim='k', sign=False,
1215
+ pad_left=None, pad_right=None, min_digits=None):
1216
+ """
1217
+ Format a floating-point scalar as a decimal string in positional notation.
1218
+
1219
+ Provides control over rounding, trimming and padding. Uses and assumes
1220
+ IEEE unbiased rounding. Uses the "Dragon4" algorithm.
1221
+
1222
+ Parameters
1223
+ ----------
1224
+ x : python float or numpy floating scalar
1225
+ Value to format.
1226
+ precision : non-negative integer or None, optional
1227
+ Maximum number of digits to print. May be None if `unique` is
1228
+ `True`, but must be an integer if unique is `False`.
1229
+ unique : boolean, optional
1230
+ If `True`, use a digit-generation strategy which gives the shortest
1231
+ representation which uniquely identifies the floating-point number from
1232
+ other values of the same type, by judicious rounding. If `precision`
1233
+ is given fewer digits than necessary can be printed, or if `min_digits`
1234
+ is given more can be printed, in which cases the last digit is rounded
1235
+ with unbiased rounding.
1236
+ If `False`, digits are generated as if printing an infinite-precision
1237
+ value and stopping after `precision` digits, rounding the remaining
1238
+ value with unbiased rounding
1239
+ fractional : boolean, optional
1240
+ If `True`, the cutoffs of `precision` and `min_digits` refer to the
1241
+ total number of digits after the decimal point, including leading
1242
+ zeros.
1243
+ If `False`, `precision` and `min_digits` refer to the total number of
1244
+ significant digits, before or after the decimal point, ignoring leading
1245
+ zeros.
1246
+ trim : one of 'k', '.', '0', '-', optional
1247
+ Controls post-processing trimming of trailing digits, as follows:
1248
+
1249
+ * 'k' : keep trailing zeros, keep decimal point (no trimming)
1250
+ * '.' : trim all trailing zeros, leave decimal point
1251
+ * '0' : trim all but the zero before the decimal point. Insert the
1252
+ zero if it is missing.
1253
+ * '-' : trim trailing zeros and any trailing decimal point
1254
+ sign : boolean, optional
1255
+ Whether to show the sign for positive values.
1256
+ pad_left : non-negative integer, optional
1257
+ Pad the left side of the string with whitespace until at least that
1258
+ many characters are to the left of the decimal point.
1259
+ pad_right : non-negative integer, optional
1260
+ Pad the right side of the string with whitespace until at least that
1261
+ many characters are to the right of the decimal point.
1262
+ min_digits : non-negative integer or None, optional
1263
+ Minimum number of digits to print. Only has an effect if `unique=True`
1264
+ in which case additional digits past those necessary to uniquely
1265
+ identify the value may be printed, rounding the last additional digit.
1266
+
1267
+ .. versionadded:: 1.21.0
1268
+
1269
+ Returns
1270
+ -------
1271
+ rep : string
1272
+ The string representation of the floating point value
1273
+
1274
+ See Also
1275
+ --------
1276
+ format_float_scientific
1277
+
1278
+ Examples
1279
+ --------
1280
+ >>> import numpy as np
1281
+ >>> np.format_float_positional(np.float32(np.pi))
1282
+ '3.1415927'
1283
+ >>> np.format_float_positional(np.float16(np.pi))
1284
+ '3.14'
1285
+ >>> np.format_float_positional(np.float16(0.3))
1286
+ '0.3'
1287
+ >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
1288
+ '0.3000488281'
1289
+ """
1290
+ precision = _none_or_positive_arg(precision, 'precision')
1291
+ pad_left = _none_or_positive_arg(pad_left, 'pad_left')
1292
+ pad_right = _none_or_positive_arg(pad_right, 'pad_right')
1293
+ min_digits = _none_or_positive_arg(min_digits, 'min_digits')
1294
+ if not fractional and precision == 0:
1295
+ raise ValueError("precision must be greater than 0 if "
1296
+ "fractional=False")
1297
+ if min_digits > 0 and precision > 0 and min_digits > precision:
1298
+ raise ValueError("min_digits must be less than or equal to precision")
1299
+ return dragon4_positional(x, precision=precision, unique=unique,
1300
+ fractional=fractional, trim=trim,
1301
+ sign=sign, pad_left=pad_left,
1302
+ pad_right=pad_right, min_digits=min_digits)
1303
+
1304
+ class IntegerFormat:
1305
+ def __init__(self, data, sign='-'):
1306
+ if data.size > 0:
1307
+ data_max = np.max(data)
1308
+ data_min = np.min(data)
1309
+ data_max_str_len = len(str(data_max))
1310
+ if sign == ' ' and data_min < 0:
1311
+ sign = '-'
1312
+ if data_max >= 0 and sign in "+ ":
1313
+ data_max_str_len += 1
1314
+ max_str_len = max(data_max_str_len,
1315
+ len(str(data_min)))
1316
+ else:
1317
+ max_str_len = 0
1318
+ self.format = f'{{:{sign}{max_str_len}d}}'
1319
+
1320
+ def __call__(self, x):
1321
+ return self.format.format(x)
1322
+
1323
+ class BoolFormat:
1324
+ def __init__(self, data, **kwargs):
1325
+ # add an extra space so " True" and "False" have the same length and
1326
+ # array elements align nicely when printed, except in 0d arrays
1327
+ self.truestr = ' True' if data.shape != () else 'True'
1328
+
1329
+ def __call__(self, x):
1330
+ return self.truestr if x else "False"
1331
+
1332
+
1333
+ class ComplexFloatingFormat:
1334
+ """ Formatter for subtypes of np.complexfloating """
1335
+ def __init__(self, x, precision, floatmode, suppress_small,
1336
+ sign=False, *, legacy=None):
1337
+ # for backcompatibility, accept bools
1338
+ if isinstance(sign, bool):
1339
+ sign = '+' if sign else '-'
1340
+
1341
+ floatmode_real = floatmode_imag = floatmode
1342
+ if legacy <= 113:
1343
+ floatmode_real = 'maxprec_equal'
1344
+ floatmode_imag = 'maxprec'
1345
+
1346
+ self.real_format = FloatingFormat(
1347
+ x.real, precision, floatmode_real, suppress_small,
1348
+ sign=sign, legacy=legacy
1349
+ )
1350
+ self.imag_format = FloatingFormat(
1351
+ x.imag, precision, floatmode_imag, suppress_small,
1352
+ sign='+', legacy=legacy
1353
+ )
1354
+
1355
+ def __call__(self, x):
1356
+ r = self.real_format(x.real)
1357
+ i = self.imag_format(x.imag)
1358
+
1359
+ # add the 'j' before the terminal whitespace in i
1360
+ sp = len(i.rstrip())
1361
+ i = i[:sp] + 'j' + i[sp:]
1362
+
1363
+ return r + i
1364
+
1365
+
1366
+ class _TimelikeFormat:
1367
+ def __init__(self, data):
1368
+ non_nat = data[~isnat(data)]
1369
+ if len(non_nat) > 0:
1370
+ # Max str length of non-NaT elements
1371
+ max_str_len = max(len(self._format_non_nat(np.max(non_nat))),
1372
+ len(self._format_non_nat(np.min(non_nat))))
1373
+ else:
1374
+ max_str_len = 0
1375
+ if len(non_nat) < data.size:
1376
+ # data contains a NaT
1377
+ max_str_len = max(max_str_len, 5)
1378
+ self._format = f'%{max_str_len}s'
1379
+ self._nat = "'NaT'".rjust(max_str_len)
1380
+
1381
+ def _format_non_nat(self, x):
1382
+ # override in subclass
1383
+ raise NotImplementedError
1384
+
1385
+ def __call__(self, x):
1386
+ if isnat(x):
1387
+ return self._nat
1388
+ else:
1389
+ return self._format % self._format_non_nat(x)
1390
+
1391
+
1392
+ class DatetimeFormat(_TimelikeFormat):
1393
+ def __init__(self, x, unit=None, timezone=None, casting='same_kind',
1394
+ legacy=False):
1395
+ # Get the unit from the dtype
1396
+ if unit is None:
1397
+ if x.dtype.kind == 'M':
1398
+ unit = datetime_data(x.dtype)[0]
1399
+ else:
1400
+ unit = 's'
1401
+
1402
+ if timezone is None:
1403
+ timezone = 'naive'
1404
+ self.timezone = timezone
1405
+ self.unit = unit
1406
+ self.casting = casting
1407
+ self.legacy = legacy
1408
+
1409
+ # must be called after the above are configured
1410
+ super().__init__(x)
1411
+
1412
+ def __call__(self, x):
1413
+ if self.legacy <= 113:
1414
+ return self._format_non_nat(x)
1415
+ return super().__call__(x)
1416
+
1417
+ def _format_non_nat(self, x):
1418
+ return "'%s'" % datetime_as_string(x,
1419
+ unit=self.unit,
1420
+ timezone=self.timezone,
1421
+ casting=self.casting)
1422
+
1423
+
1424
+ class TimedeltaFormat(_TimelikeFormat):
1425
+ def _format_non_nat(self, x):
1426
+ return str(x.astype('i8'))
1427
+
1428
+
1429
+ class SubArrayFormat:
1430
+ def __init__(self, format_function, **options):
1431
+ self.format_function = format_function
1432
+ self.threshold = options['threshold']
1433
+ self.edge_items = options['edgeitems']
1434
+
1435
+ def __call__(self, a):
1436
+ self.summary_insert = "..." if a.size > self.threshold else ""
1437
+ return self.format_array(a)
1438
+
1439
+ def format_array(self, a):
1440
+ if np.ndim(a) == 0:
1441
+ return self.format_function(a)
1442
+
1443
+ if self.summary_insert and a.shape[0] > 2 * self.edge_items:
1444
+ formatted = (
1445
+ [self.format_array(a_) for a_ in a[:self.edge_items]]
1446
+ + [self.summary_insert]
1447
+ + [self.format_array(a_) for a_ in a[-self.edge_items:]]
1448
+ )
1449
+ else:
1450
+ formatted = [self.format_array(a_) for a_ in a]
1451
+
1452
+ return "[" + ", ".join(formatted) + "]"
1453
+
1454
+
1455
+ class StructuredVoidFormat:
1456
+ """
1457
+ Formatter for structured np.void objects.
1458
+
1459
+ This does not work on structured alias types like
1460
+ np.dtype(('i4', 'i2,i2')), as alias scalars lose their field information,
1461
+ and the implementation relies upon np.void.__getitem__.
1462
+ """
1463
+ def __init__(self, format_functions):
1464
+ self.format_functions = format_functions
1465
+
1466
+ @classmethod
1467
+ def from_data(cls, data, **options):
1468
+ """
1469
+ This is a second way to initialize StructuredVoidFormat,
1470
+ using the raw data as input. Added to avoid changing
1471
+ the signature of __init__.
1472
+ """
1473
+ format_functions = []
1474
+ for field_name in data.dtype.names:
1475
+ format_function = _get_format_function(data[field_name], **options)
1476
+ if data.dtype[field_name].shape != ():
1477
+ format_function = SubArrayFormat(format_function, **options)
1478
+ format_functions.append(format_function)
1479
+ return cls(format_functions)
1480
+
1481
+ def __call__(self, x):
1482
+ str_fields = [
1483
+ format_function(field)
1484
+ for field, format_function in zip(x, self.format_functions)
1485
+ ]
1486
+ if len(str_fields) == 1:
1487
+ return f"({str_fields[0]},)"
1488
+ else:
1489
+ return f"({', '.join(str_fields)})"
1490
+
1491
+
1492
+ def _void_scalar_to_string(x, is_repr=True):
1493
+ """
1494
+ Implements the repr for structured-void scalars. It is called from the
1495
+ scalartypes.c.src code, and is placed here because it uses the elementwise
1496
+ formatters defined above.
1497
+ """
1498
+ options = format_options.get().copy()
1499
+
1500
+ if options["legacy"] <= 125:
1501
+ return StructuredVoidFormat.from_data(array(x), **options)(x)
1502
+
1503
+ if options.get('formatter') is None:
1504
+ options['formatter'] = {}
1505
+ options['formatter'].setdefault('float_kind', str)
1506
+ val_repr = StructuredVoidFormat.from_data(array(x), **options)(x)
1507
+ if not is_repr:
1508
+ return val_repr
1509
+ cls = type(x)
1510
+ cls_fqn = cls.__module__.replace("numpy", "np") + "." + cls.__name__
1511
+ void_dtype = np.dtype((np.void, x.dtype))
1512
+ return f"{cls_fqn}({val_repr}, dtype={void_dtype!s})"
1513
+
1514
+
1515
+ _typelessdata = [int_, float64, complex128, _nt.bool]
1516
+
1517
+
1518
+ def dtype_is_implied(dtype):
1519
+ """
1520
+ Determine if the given dtype is implied by the representation
1521
+ of its values.
1522
+
1523
+ Parameters
1524
+ ----------
1525
+ dtype : dtype
1526
+ Data type
1527
+
1528
+ Returns
1529
+ -------
1530
+ implied : bool
1531
+ True if the dtype is implied by the representation of its values.
1532
+
1533
+ Examples
1534
+ --------
1535
+ >>> import numpy as np
1536
+ >>> np._core.arrayprint.dtype_is_implied(int)
1537
+ True
1538
+ >>> np.array([1, 2, 3], int)
1539
+ array([1, 2, 3])
1540
+ >>> np._core.arrayprint.dtype_is_implied(np.int8)
1541
+ False
1542
+ >>> np.array([1, 2, 3], np.int8)
1543
+ array([1, 2, 3], dtype=int8)
1544
+ """
1545
+ dtype = np.dtype(dtype)
1546
+ if format_options.get()['legacy'] <= 113 and dtype.type == np.bool:
1547
+ return False
1548
+
1549
+ # not just void types can be structured, and names are not part of the repr
1550
+ if dtype.names is not None:
1551
+ return False
1552
+
1553
+ # should care about endianness *unless size is 1* (e.g., int8, bool)
1554
+ if not dtype.isnative:
1555
+ return False
1556
+
1557
+ return dtype.type in _typelessdata
1558
+
1559
+
1560
+ def dtype_short_repr(dtype):
1561
+ """
1562
+ Convert a dtype to a short form which evaluates to the same dtype.
1563
+
1564
+ The intent is roughly that the following holds
1565
+
1566
+ >>> from numpy import *
1567
+ >>> dt = np.int64([1, 2]).dtype
1568
+ >>> assert eval(dtype_short_repr(dt)) == dt
1569
+ """
1570
+ if type(dtype).__repr__ != np.dtype.__repr__:
1571
+ # TODO: Custom repr for user DTypes, logic should likely move.
1572
+ return repr(dtype)
1573
+ if dtype.names is not None:
1574
+ # structured dtypes give a list or tuple repr
1575
+ return str(dtype)
1576
+ elif issubclass(dtype.type, flexible):
1577
+ # handle these separately so they don't give garbage like str256
1578
+ return f"'{str(dtype)}'"
1579
+
1580
+ typename = dtype.name
1581
+ if not dtype.isnative:
1582
+ # deal with cases like dtype('<u2') that are identical to an
1583
+ # established dtype (in this case uint16)
1584
+ # except that they have a different endianness.
1585
+ return f"'{str(dtype)}'"
1586
+ # quote typenames which can't be represented as python variable names
1587
+ if typename and not (typename[0].isalpha() and typename.isalnum()):
1588
+ typename = repr(typename)
1589
+ return typename
1590
+
1591
+
1592
+ def _array_repr_implementation(
1593
+ arr, max_line_width=None, precision=None, suppress_small=None,
1594
+ array2string=array2string):
1595
+ """Internal version of array_repr() that allows overriding array2string."""
1596
+ current_options = format_options.get()
1597
+ override_repr = current_options["override_repr"]
1598
+ if override_repr is not None:
1599
+ return override_repr(arr)
1600
+
1601
+ if max_line_width is None:
1602
+ max_line_width = current_options['linewidth']
1603
+
1604
+ if type(arr) is not ndarray:
1605
+ class_name = type(arr).__name__
1606
+ else:
1607
+ class_name = "array"
1608
+
1609
+ prefix = class_name + "("
1610
+ if (current_options['legacy'] <= 113 and
1611
+ arr.shape == () and not arr.dtype.names):
1612
+ lst = repr(arr.item())
1613
+ else:
1614
+ lst = array2string(arr, max_line_width, precision, suppress_small,
1615
+ ', ', prefix, suffix=")")
1616
+
1617
+ # Add dtype and shape information if these cannot be inferred from
1618
+ # the array string.
1619
+ extras = []
1620
+ if ((arr.size == 0 and arr.shape != (0,))
1621
+ or (current_options['legacy'] > 210
1622
+ and arr.size > current_options['threshold'])):
1623
+ extras.append(f"shape={arr.shape}")
1624
+ if not dtype_is_implied(arr.dtype) or arr.size == 0:
1625
+ extras.append(f"dtype={dtype_short_repr(arr.dtype)}")
1626
+
1627
+ if not extras:
1628
+ return prefix + lst + ")"
1629
+
1630
+ arr_str = prefix + lst + ","
1631
+ extra_str = ", ".join(extras) + ")"
1632
+ # compute whether we should put extras on a new line: Do so if adding the
1633
+ # extras would extend the last line past max_line_width.
1634
+ # Note: This line gives the correct result even when rfind returns -1.
1635
+ last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1)
1636
+ spacer = " "
1637
+ if current_options['legacy'] <= 113:
1638
+ if issubclass(arr.dtype.type, flexible):
1639
+ spacer = '\n' + ' ' * len(prefix)
1640
+ elif last_line_len + len(extra_str) + 1 > max_line_width:
1641
+ spacer = '\n' + ' ' * len(prefix)
1642
+
1643
+ return arr_str + spacer + extra_str
1644
+
1645
+
1646
+ def _array_repr_dispatcher(
1647
+ arr, max_line_width=None, precision=None, suppress_small=None):
1648
+ return (arr,)
1649
+
1650
+
1651
+ @array_function_dispatch(_array_repr_dispatcher, module='numpy')
1652
+ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
1653
+ """
1654
+ Return the string representation of an array.
1655
+
1656
+ Parameters
1657
+ ----------
1658
+ arr : ndarray
1659
+ Input array.
1660
+ max_line_width : int, optional
1661
+ Inserts newlines if text is longer than `max_line_width`.
1662
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
1663
+ precision : int, optional
1664
+ Floating point precision.
1665
+ Defaults to ``numpy.get_printoptions()['precision']``.
1666
+ suppress_small : bool, optional
1667
+ Represent numbers "very close" to zero as zero; default is False.
1668
+ Very close is defined by precision: if the precision is 8, e.g.,
1669
+ numbers smaller (in absolute value) than 5e-9 are represented as
1670
+ zero.
1671
+ Defaults to ``numpy.get_printoptions()['suppress']``.
1672
+
1673
+ Returns
1674
+ -------
1675
+ string : str
1676
+ The string representation of an array.
1677
+
1678
+ See Also
1679
+ --------
1680
+ array_str, array2string, set_printoptions
1681
+
1682
+ Examples
1683
+ --------
1684
+ >>> import numpy as np
1685
+ >>> np.array_repr(np.array([1,2]))
1686
+ 'array([1, 2])'
1687
+ >>> np.array_repr(np.ma.array([0.]))
1688
+ 'MaskedArray([0.])'
1689
+ >>> np.array_repr(np.array([], np.int32))
1690
+ 'array([], dtype=int32)'
1691
+
1692
+ >>> x = np.array([1e-6, 4e-7, 2, 3])
1693
+ >>> np.array_repr(x, precision=6, suppress_small=True)
1694
+ 'array([0.000001, 0. , 2. , 3. ])'
1695
+
1696
+ """
1697
+ return _array_repr_implementation(
1698
+ arr, max_line_width, precision, suppress_small)
1699
+
1700
+
1701
+ @_recursive_guard()
1702
+ def _guarded_repr_or_str(v):
1703
+ if isinstance(v, bytes):
1704
+ return repr(v)
1705
+ return str(v)
1706
+
1707
+
1708
+ def _array_str_implementation(
1709
+ a, max_line_width=None, precision=None, suppress_small=None,
1710
+ array2string=array2string):
1711
+ """Internal version of array_str() that allows overriding array2string."""
1712
+ if (format_options.get()['legacy'] <= 113 and
1713
+ a.shape == () and not a.dtype.names):
1714
+ return str(a.item())
1715
+
1716
+ # the str of 0d arrays is a special case: It should appear like a scalar,
1717
+ # so floats are not truncated by `precision`, and strings are not wrapped
1718
+ # in quotes. So we return the str of the scalar value.
1719
+ if a.shape == ():
1720
+ # obtain a scalar and call str on it, avoiding problems for subclasses
1721
+ # for which indexing with () returns a 0d instead of a scalar by using
1722
+ # ndarray's getindex. Also guard against recursive 0d object arrays.
1723
+ return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
1724
+
1725
+ return array2string(a, max_line_width, precision, suppress_small, ' ', "")
1726
+
1727
+
1728
+ def _array_str_dispatcher(
1729
+ a, max_line_width=None, precision=None, suppress_small=None):
1730
+ return (a,)
1731
+
1732
+
1733
+ @array_function_dispatch(_array_str_dispatcher, module='numpy')
1734
+ def array_str(a, max_line_width=None, precision=None, suppress_small=None):
1735
+ """
1736
+ Return a string representation of the data in an array.
1737
+
1738
+ The data in the array is returned as a single string. This function is
1739
+ similar to `array_repr`, the difference being that `array_repr` also
1740
+ returns information on the kind of array and its data type.
1741
+
1742
+ Parameters
1743
+ ----------
1744
+ a : ndarray
1745
+ Input array.
1746
+ max_line_width : int, optional
1747
+ Inserts newlines if text is longer than `max_line_width`.
1748
+ Defaults to ``numpy.get_printoptions()['linewidth']``.
1749
+ precision : int, optional
1750
+ Floating point precision.
1751
+ Defaults to ``numpy.get_printoptions()['precision']``.
1752
+ suppress_small : bool, optional
1753
+ Represent numbers "very close" to zero as zero; default is False.
1754
+ Very close is defined by precision: if the precision is 8, e.g.,
1755
+ numbers smaller (in absolute value) than 5e-9 are represented as
1756
+ zero.
1757
+ Defaults to ``numpy.get_printoptions()['suppress']``.
1758
+
1759
+ See Also
1760
+ --------
1761
+ array2string, array_repr, set_printoptions
1762
+
1763
+ Examples
1764
+ --------
1765
+ >>> import numpy as np
1766
+ >>> np.array_str(np.arange(3))
1767
+ '[0 1 2]'
1768
+
1769
+ """
1770
+ return _array_str_implementation(
1771
+ a, max_line_width, precision, suppress_small)
1772
+
1773
+
1774
+ # needed if __array_function__ is disabled
1775
+ _array2string_impl = getattr(array2string, '__wrapped__', array2string)
1776
+ _default_array_str = functools.partial(_array_str_implementation,
1777
+ array2string=_array2string_impl)
1778
+ _default_array_repr = functools.partial(_array_repr_implementation,
1779
+ array2string=_array2string_impl)
python/user_packages/Python313/site-packages/numpy/_core/arrayprint.pyi ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+
3
+ # Using a private class is by no means ideal, but it is simply a consequence
4
+ # of a `contextlib.context` returning an instance of aforementioned class
5
+ from contextlib import _GeneratorContextManager
6
+ from typing import (
7
+ Any,
8
+ Final,
9
+ Literal,
10
+ SupportsIndex,
11
+ TypeAlias,
12
+ TypedDict,
13
+ type_check_only,
14
+ )
15
+
16
+ import numpy as np
17
+ from numpy._typing import NDArray, _CharLike_co, _FloatLike_co
18
+
19
+ __all__ = [
20
+ "array2string",
21
+ "array_repr",
22
+ "array_str",
23
+ "format_float_positional",
24
+ "format_float_scientific",
25
+ "get_printoptions",
26
+ "printoptions",
27
+ "set_printoptions",
28
+ ]
29
+
30
+ ###
31
+
32
+ _FloatMode: TypeAlias = Literal["fixed", "unique", "maxprec", "maxprec_equal"]
33
+ _LegacyNoStyle: TypeAlias = Literal["1.21", "1.25", "2.1", False]
34
+ _Legacy: TypeAlias = Literal["1.13", _LegacyNoStyle]
35
+ _Sign: TypeAlias = Literal["-", "+", " "]
36
+ _Trim: TypeAlias = Literal["k", ".", "0", "-"]
37
+ _ReprFunc: TypeAlias = Callable[[NDArray[Any]], str]
38
+
39
+ @type_check_only
40
+ class _FormatDict(TypedDict, total=False):
41
+ bool: Callable[[np.bool], str]
42
+ int: Callable[[np.integer], str]
43
+ timedelta: Callable[[np.timedelta64], str]
44
+ datetime: Callable[[np.datetime64], str]
45
+ float: Callable[[np.floating], str]
46
+ longfloat: Callable[[np.longdouble], str]
47
+ complexfloat: Callable[[np.complexfloating], str]
48
+ longcomplexfloat: Callable[[np.clongdouble], str]
49
+ void: Callable[[np.void], str]
50
+ numpystr: Callable[[_CharLike_co], str]
51
+ object: Callable[[object], str]
52
+ all: Callable[[object], str]
53
+ int_kind: Callable[[np.integer], str]
54
+ float_kind: Callable[[np.floating], str]
55
+ complex_kind: Callable[[np.complexfloating], str]
56
+ str_kind: Callable[[_CharLike_co], str]
57
+
58
+ @type_check_only
59
+ class _FormatOptions(TypedDict):
60
+ precision: int
61
+ threshold: int
62
+ edgeitems: int
63
+ linewidth: int
64
+ suppress: bool
65
+ nanstr: str
66
+ infstr: str
67
+ formatter: _FormatDict | None
68
+ sign: _Sign
69
+ floatmode: _FloatMode
70
+ legacy: _Legacy
71
+
72
+ ###
73
+
74
+ __docformat__: Final = "restructuredtext" # undocumented
75
+
76
+ def set_printoptions(
77
+ precision: SupportsIndex | None = None,
78
+ threshold: int | None = None,
79
+ edgeitems: int | None = None,
80
+ linewidth: int | None = None,
81
+ suppress: bool | None = None,
82
+ nanstr: str | None = None,
83
+ infstr: str | None = None,
84
+ formatter: _FormatDict | None = None,
85
+ sign: _Sign | None = None,
86
+ floatmode: _FloatMode | None = None,
87
+ *,
88
+ legacy: _Legacy | None = None,
89
+ override_repr: _ReprFunc | None = None,
90
+ ) -> None: ...
91
+ def get_printoptions() -> _FormatOptions: ...
92
+
93
+ # public numpy export
94
+ def array2string(
95
+ a: NDArray[Any],
96
+ max_line_width: int | None = None,
97
+ precision: SupportsIndex | None = None,
98
+ suppress_small: bool | None = None,
99
+ separator: str = " ",
100
+ prefix: str = "",
101
+ *,
102
+ formatter: _FormatDict | None = None,
103
+ threshold: int | None = None,
104
+ edgeitems: int | None = None,
105
+ sign: _Sign | None = None,
106
+ floatmode: _FloatMode | None = None,
107
+ suffix: str = "",
108
+ legacy: _Legacy | None = None,
109
+ ) -> str: ...
110
+
111
+ def format_float_scientific(
112
+ x: _FloatLike_co,
113
+ precision: int | None = None,
114
+ unique: bool = True,
115
+ trim: _Trim = "k",
116
+ sign: bool = False,
117
+ pad_left: int | None = None,
118
+ exp_digits: int | None = None,
119
+ min_digits: int | None = None,
120
+ ) -> str: ...
121
+ def format_float_positional(
122
+ x: _FloatLike_co,
123
+ precision: int | None = None,
124
+ unique: bool = True,
125
+ fractional: bool = True,
126
+ trim: _Trim = "k",
127
+ sign: bool = False,
128
+ pad_left: int | None = None,
129
+ pad_right: int | None = None,
130
+ min_digits: int | None = None,
131
+ ) -> str: ...
132
+ def array_repr(
133
+ arr: NDArray[Any],
134
+ max_line_width: int | None = None,
135
+ precision: SupportsIndex | None = None,
136
+ suppress_small: bool | None = None,
137
+ ) -> str: ...
138
+ def array_str(
139
+ a: NDArray[Any],
140
+ max_line_width: int | None = None,
141
+ precision: SupportsIndex | None = None,
142
+ suppress_small: bool | None = None,
143
+ ) -> str: ...
144
+ def printoptions(
145
+ precision: SupportsIndex | None = ...,
146
+ threshold: int | None = ...,
147
+ edgeitems: int | None = ...,
148
+ linewidth: int | None = ...,
149
+ suppress: bool | None = ...,
150
+ nanstr: str | None = ...,
151
+ infstr: str | None = ...,
152
+ formatter: _FormatDict | None = ...,
153
+ sign: _Sign | None = None,
154
+ floatmode: _FloatMode | None = None,
155
+ *,
156
+ legacy: _Legacy | None = None,
157
+ override_repr: _ReprFunc | None = None,
158
+ ) -> _GeneratorContextManager[_FormatOptions]: ...
python/user_packages/Python313/site-packages/numpy/_core/cversions.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple script to compute the api hash of the current API.
2
+
3
+ The API has is defined by numpy_api_order and ufunc_api_order.
4
+
5
+ """
6
+ from os.path import dirname
7
+
8
+ from code_generators.genapi import fullapi_hash
9
+ from code_generators.numpy_api import full_api
10
+
11
+ if __name__ == '__main__':
12
+ curdir = dirname(__file__)
13
+ print(fullapi_hash(full_api))
python/user_packages/Python313/site-packages/numpy/_core/defchararray.py ADDED
@@ -0,0 +1,1414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains a set of functions for vectorized string
3
+ operations and methods.
4
+
5
+ .. note::
6
+ The `chararray` class exists for backwards compatibility with
7
+ Numarray, it is not recommended for new development. Starting from numpy
8
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
9
+ `dtype` `object_`, `bytes_` or `str_`, and use the free functions
10
+ in the `numpy.char` module for fast vectorized string operations.
11
+
12
+ Some methods will only be available if the corresponding string method is
13
+ available in your version of Python.
14
+
15
+ The preferred alias for `defchararray` is `numpy.char`.
16
+
17
+ """
18
+ import functools
19
+
20
+ import numpy as np
21
+ from numpy._core import overrides
22
+ from numpy._core.multiarray import compare_chararrays
23
+ from numpy._core.strings import (
24
+ _join as join,
25
+ _rsplit as rsplit,
26
+ _split as split,
27
+ _splitlines as splitlines,
28
+ )
29
+ from numpy._utils import set_module
30
+ from numpy.strings import *
31
+ from numpy.strings import (
32
+ multiply as strings_multiply,
33
+ partition as strings_partition,
34
+ rpartition as strings_rpartition,
35
+ )
36
+
37
+ from .numeric import array as narray, asarray as asnarray, ndarray
38
+ from .numerictypes import bytes_, character, str_
39
+
40
+ __all__ = [
41
+ 'equal', 'not_equal', 'greater_equal', 'less_equal',
42
+ 'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
43
+ 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
44
+ 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
45
+ 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
46
+ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
47
+ 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
48
+ 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
49
+ 'array', 'asarray', 'compare_chararrays', 'chararray'
50
+ ]
51
+
52
+
53
+ array_function_dispatch = functools.partial(
54
+ overrides.array_function_dispatch, module='numpy.char')
55
+
56
+
57
+ def _binary_op_dispatcher(x1, x2):
58
+ return (x1, x2)
59
+
60
+
61
+ @array_function_dispatch(_binary_op_dispatcher)
62
+ def equal(x1, x2):
63
+ """
64
+ Return (x1 == x2) element-wise.
65
+
66
+ Unlike `numpy.equal`, this comparison is performed by first
67
+ stripping whitespace characters from the end of the string. This
68
+ behavior is provided for backward-compatibility with numarray.
69
+
70
+ Parameters
71
+ ----------
72
+ x1, x2 : array_like of str or unicode
73
+ Input arrays of the same shape.
74
+
75
+ Returns
76
+ -------
77
+ out : ndarray
78
+ Output array of bools.
79
+
80
+ Examples
81
+ --------
82
+ >>> import numpy as np
83
+ >>> y = "aa "
84
+ >>> x = "aa"
85
+ >>> np.char.equal(x, y)
86
+ array(True)
87
+
88
+ See Also
89
+ --------
90
+ not_equal, greater_equal, less_equal, greater, less
91
+ """
92
+ return compare_chararrays(x1, x2, '==', True)
93
+
94
+
95
+ @array_function_dispatch(_binary_op_dispatcher)
96
+ def not_equal(x1, x2):
97
+ """
98
+ Return (x1 != x2) element-wise.
99
+
100
+ Unlike `numpy.not_equal`, this comparison is performed by first
101
+ stripping whitespace characters from the end of the string. This
102
+ behavior is provided for backward-compatibility with numarray.
103
+
104
+ Parameters
105
+ ----------
106
+ x1, x2 : array_like of str or unicode
107
+ Input arrays of the same shape.
108
+
109
+ Returns
110
+ -------
111
+ out : ndarray
112
+ Output array of bools.
113
+
114
+ See Also
115
+ --------
116
+ equal, greater_equal, less_equal, greater, less
117
+
118
+ Examples
119
+ --------
120
+ >>> import numpy as np
121
+ >>> x1 = np.array(['a', 'b', 'c'])
122
+ >>> np.char.not_equal(x1, 'b')
123
+ array([ True, False, True])
124
+
125
+ """
126
+ return compare_chararrays(x1, x2, '!=', True)
127
+
128
+
129
+ @array_function_dispatch(_binary_op_dispatcher)
130
+ def greater_equal(x1, x2):
131
+ """
132
+ Return (x1 >= x2) element-wise.
133
+
134
+ Unlike `numpy.greater_equal`, this comparison is performed by
135
+ first stripping whitespace characters from the end of the string.
136
+ This behavior is provided for backward-compatibility with
137
+ numarray.
138
+
139
+ Parameters
140
+ ----------
141
+ x1, x2 : array_like of str or unicode
142
+ Input arrays of the same shape.
143
+
144
+ Returns
145
+ -------
146
+ out : ndarray
147
+ Output array of bools.
148
+
149
+ See Also
150
+ --------
151
+ equal, not_equal, less_equal, greater, less
152
+
153
+ Examples
154
+ --------
155
+ >>> import numpy as np
156
+ >>> x1 = np.array(['a', 'b', 'c'])
157
+ >>> np.char.greater_equal(x1, 'b')
158
+ array([False, True, True])
159
+
160
+ """
161
+ return compare_chararrays(x1, x2, '>=', True)
162
+
163
+
164
+ @array_function_dispatch(_binary_op_dispatcher)
165
+ def less_equal(x1, x2):
166
+ """
167
+ Return (x1 <= x2) element-wise.
168
+
169
+ Unlike `numpy.less_equal`, this comparison is performed by first
170
+ stripping whitespace characters from the end of the string. This
171
+ behavior is provided for backward-compatibility with numarray.
172
+
173
+ Parameters
174
+ ----------
175
+ x1, x2 : array_like of str or unicode
176
+ Input arrays of the same shape.
177
+
178
+ Returns
179
+ -------
180
+ out : ndarray
181
+ Output array of bools.
182
+
183
+ See Also
184
+ --------
185
+ equal, not_equal, greater_equal, greater, less
186
+
187
+ Examples
188
+ --------
189
+ >>> import numpy as np
190
+ >>> x1 = np.array(['a', 'b', 'c'])
191
+ >>> np.char.less_equal(x1, 'b')
192
+ array([ True, True, False])
193
+
194
+ """
195
+ return compare_chararrays(x1, x2, '<=', True)
196
+
197
+
198
+ @array_function_dispatch(_binary_op_dispatcher)
199
+ def greater(x1, x2):
200
+ """
201
+ Return (x1 > x2) element-wise.
202
+
203
+ Unlike `numpy.greater`, this comparison is performed by first
204
+ stripping whitespace characters from the end of the string. This
205
+ behavior is provided for backward-compatibility with numarray.
206
+
207
+ Parameters
208
+ ----------
209
+ x1, x2 : array_like of str or unicode
210
+ Input arrays of the same shape.
211
+
212
+ Returns
213
+ -------
214
+ out : ndarray
215
+ Output array of bools.
216
+
217
+ See Also
218
+ --------
219
+ equal, not_equal, greater_equal, less_equal, less
220
+
221
+ Examples
222
+ --------
223
+ >>> import numpy as np
224
+ >>> x1 = np.array(['a', 'b', 'c'])
225
+ >>> np.char.greater(x1, 'b')
226
+ array([False, False, True])
227
+
228
+ """
229
+ return compare_chararrays(x1, x2, '>', True)
230
+
231
+
232
+ @array_function_dispatch(_binary_op_dispatcher)
233
+ def less(x1, x2):
234
+ """
235
+ Return (x1 < x2) element-wise.
236
+
237
+ Unlike `numpy.greater`, this comparison is performed by first
238
+ stripping whitespace characters from the end of the string. This
239
+ behavior is provided for backward-compatibility with numarray.
240
+
241
+ Parameters
242
+ ----------
243
+ x1, x2 : array_like of str or unicode
244
+ Input arrays of the same shape.
245
+
246
+ Returns
247
+ -------
248
+ out : ndarray
249
+ Output array of bools.
250
+
251
+ See Also
252
+ --------
253
+ equal, not_equal, greater_equal, less_equal, greater
254
+
255
+ Examples
256
+ --------
257
+ >>> import numpy as np
258
+ >>> x1 = np.array(['a', 'b', 'c'])
259
+ >>> np.char.less(x1, 'b')
260
+ array([True, False, False])
261
+
262
+ """
263
+ return compare_chararrays(x1, x2, '<', True)
264
+
265
+
266
+ @set_module("numpy.char")
267
+ def multiply(a, i):
268
+ """
269
+ Return (a * i), that is string multiple concatenation,
270
+ element-wise.
271
+
272
+ Values in ``i`` of less than 0 are treated as 0 (which yields an
273
+ empty string).
274
+
275
+ Parameters
276
+ ----------
277
+ a : array_like, with `np.bytes_` or `np.str_` dtype
278
+
279
+ i : array_like, with any integer dtype
280
+
281
+ Returns
282
+ -------
283
+ out : ndarray
284
+ Output array of str or unicode, depending on input types
285
+
286
+ Notes
287
+ -----
288
+ This is a thin wrapper around np.strings.multiply that raises
289
+ `ValueError` when ``i`` is not an integer. It only
290
+ exists for backwards-compatibility.
291
+
292
+ Examples
293
+ --------
294
+ >>> import numpy as np
295
+ >>> a = np.array(["a", "b", "c"])
296
+ >>> np.strings.multiply(a, 3)
297
+ array(['aaa', 'bbb', 'ccc'], dtype='<U3')
298
+ >>> i = np.array([1, 2, 3])
299
+ >>> np.strings.multiply(a, i)
300
+ array(['a', 'bb', 'ccc'], dtype='<U3')
301
+ >>> np.strings.multiply(np.array(['a']), i)
302
+ array(['a', 'aa', 'aaa'], dtype='<U3')
303
+ >>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
304
+ >>> np.strings.multiply(a, 3)
305
+ array([['aaa', 'bbb', 'ccc'],
306
+ ['ddd', 'eee', 'fff']], dtype='<U3')
307
+ >>> np.strings.multiply(a, i)
308
+ array([['a', 'bb', 'ccc'],
309
+ ['d', 'ee', 'fff']], dtype='<U3')
310
+
311
+ """
312
+ try:
313
+ return strings_multiply(a, i)
314
+ except TypeError:
315
+ raise ValueError("Can only multiply by integers")
316
+
317
+
318
+ @set_module("numpy.char")
319
+ def partition(a, sep):
320
+ """
321
+ Partition each element in `a` around `sep`.
322
+
323
+ Calls :meth:`str.partition` element-wise.
324
+
325
+ For each element in `a`, split the element as the first
326
+ occurrence of `sep`, and return 3 strings containing the part
327
+ before the separator, the separator itself, and the part after
328
+ the separator. If the separator is not found, return 3 strings
329
+ containing the string itself, followed by two empty strings.
330
+
331
+ Parameters
332
+ ----------
333
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
334
+ Input array
335
+ sep : {str, unicode}
336
+ Separator to split each string element in `a`.
337
+
338
+ Returns
339
+ -------
340
+ out : ndarray
341
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
342
+ depending on input types. The output array will have an extra
343
+ dimension with 3 elements per input element.
344
+
345
+ Examples
346
+ --------
347
+ >>> import numpy as np
348
+ >>> x = np.array(["Numpy is nice!"])
349
+ >>> np.char.partition(x, " ")
350
+ array([['Numpy', ' ', 'is nice!']], dtype='<U8')
351
+
352
+ See Also
353
+ --------
354
+ str.partition
355
+
356
+ """
357
+ return np.stack(strings_partition(a, sep), axis=-1)
358
+
359
+
360
+ @set_module("numpy.char")
361
+ def rpartition(a, sep):
362
+ """
363
+ Partition (split) each element around the right-most separator.
364
+
365
+ Calls :meth:`str.rpartition` element-wise.
366
+
367
+ For each element in `a`, split the element as the last
368
+ occurrence of `sep`, and return 3 strings containing the part
369
+ before the separator, the separator itself, and the part after
370
+ the separator. If the separator is not found, return 3 strings
371
+ containing the string itself, followed by two empty strings.
372
+
373
+ Parameters
374
+ ----------
375
+ a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
376
+ Input array
377
+ sep : str or unicode
378
+ Right-most separator to split each element in array.
379
+
380
+ Returns
381
+ -------
382
+ out : ndarray
383
+ Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
384
+ depending on input types. The output array will have an extra
385
+ dimension with 3 elements per input element.
386
+
387
+ See Also
388
+ --------
389
+ str.rpartition
390
+
391
+ Examples
392
+ --------
393
+ >>> import numpy as np
394
+ >>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
395
+ >>> np.char.rpartition(a, 'A')
396
+ array([['aAaAa', 'A', ''],
397
+ [' a', 'A', ' '],
398
+ ['abB', 'A', 'Bba']], dtype='<U5')
399
+
400
+ """
401
+ return np.stack(strings_rpartition(a, sep), axis=-1)
402
+
403
+
404
+ @set_module("numpy.char")
405
+ class chararray(ndarray):
406
+ """
407
+ chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
408
+ strides=None, order=None)
409
+
410
+ Provides a convenient view on arrays of string and unicode values.
411
+
412
+ .. note::
413
+ The `chararray` class exists for backwards compatibility with
414
+ Numarray, it is not recommended for new development. Starting from numpy
415
+ 1.4, if one needs arrays of strings, it is recommended to use arrays of
416
+ `dtype` `~numpy.object_`, `~numpy.bytes_` or `~numpy.str_`, and use
417
+ the free functions in the `numpy.char` module for fast vectorized
418
+ string operations.
419
+
420
+ Versus a NumPy array of dtype `~numpy.bytes_` or `~numpy.str_`, this
421
+ class adds the following functionality:
422
+
423
+ 1) values automatically have whitespace removed from the end
424
+ when indexed
425
+
426
+ 2) comparison operators automatically remove whitespace from the
427
+ end when comparing values
428
+
429
+ 3) vectorized string operations are provided as methods
430
+ (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
431
+
432
+ chararrays should be created using `numpy.char.array` or
433
+ `numpy.char.asarray`, rather than this constructor directly.
434
+
435
+ This constructor creates the array, using `buffer` (with `offset`
436
+ and `strides`) if it is not ``None``. If `buffer` is ``None``, then
437
+ constructs a new array with `strides` in "C order", unless both
438
+ ``len(shape) >= 2`` and ``order='F'``, in which case `strides`
439
+ is in "Fortran order".
440
+
441
+ Methods
442
+ -------
443
+ astype
444
+ argsort
445
+ copy
446
+ count
447
+ decode
448
+ dump
449
+ dumps
450
+ encode
451
+ endswith
452
+ expandtabs
453
+ fill
454
+ find
455
+ flatten
456
+ getfield
457
+ index
458
+ isalnum
459
+ isalpha
460
+ isdecimal
461
+ isdigit
462
+ islower
463
+ isnumeric
464
+ isspace
465
+ istitle
466
+ isupper
467
+ item
468
+ join
469
+ ljust
470
+ lower
471
+ lstrip
472
+ nonzero
473
+ put
474
+ ravel
475
+ repeat
476
+ replace
477
+ reshape
478
+ resize
479
+ rfind
480
+ rindex
481
+ rjust
482
+ rsplit
483
+ rstrip
484
+ searchsorted
485
+ setfield
486
+ setflags
487
+ sort
488
+ split
489
+ splitlines
490
+ squeeze
491
+ startswith
492
+ strip
493
+ swapaxes
494
+ swapcase
495
+ take
496
+ title
497
+ tofile
498
+ tolist
499
+ translate
500
+ transpose
501
+ upper
502
+ view
503
+ zfill
504
+
505
+ Parameters
506
+ ----------
507
+ shape : tuple
508
+ Shape of the array.
509
+ itemsize : int, optional
510
+ Length of each array element, in number of characters. Default is 1.
511
+ unicode : bool, optional
512
+ Are the array elements of type unicode (True) or string (False).
513
+ Default is False.
514
+ buffer : object exposing the buffer interface or str, optional
515
+ Memory address of the start of the array data. Default is None,
516
+ in which case a new array is created.
517
+ offset : int, optional
518
+ Fixed stride displacement from the beginning of an axis?
519
+ Default is 0. Needs to be >=0.
520
+ strides : array_like of ints, optional
521
+ Strides for the array (see `~numpy.ndarray.strides` for
522
+ full description). Default is None.
523
+ order : {'C', 'F'}, optional
524
+ The order in which the array data is stored in memory: 'C' ->
525
+ "row major" order (the default), 'F' -> "column major"
526
+ (Fortran) order.
527
+
528
+ Examples
529
+ --------
530
+ >>> import numpy as np
531
+ >>> charar = np.char.chararray((3, 3))
532
+ >>> charar[:] = 'a'
533
+ >>> charar
534
+ chararray([[b'a', b'a', b'a'],
535
+ [b'a', b'a', b'a'],
536
+ [b'a', b'a', b'a']], dtype='|S1')
537
+
538
+ >>> charar = np.char.chararray(charar.shape, itemsize=5)
539
+ >>> charar[:] = 'abc'
540
+ >>> charar
541
+ chararray([[b'abc', b'abc', b'abc'],
542
+ [b'abc', b'abc', b'abc'],
543
+ [b'abc', b'abc', b'abc']], dtype='|S5')
544
+
545
+ """
546
+ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
547
+ offset=0, strides=None, order='C'):
548
+ if unicode:
549
+ dtype = str_
550
+ else:
551
+ dtype = bytes_
552
+
553
+ # force itemsize to be a Python int, since using NumPy integer
554
+ # types results in itemsize.itemsize being used as the size of
555
+ # strings in the new array.
556
+ itemsize = int(itemsize)
557
+
558
+ if isinstance(buffer, str):
559
+ # unicode objects do not have the buffer interface
560
+ filler = buffer
561
+ buffer = None
562
+ else:
563
+ filler = None
564
+
565
+ if buffer is None:
566
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
567
+ order=order)
568
+ else:
569
+ self = ndarray.__new__(subtype, shape, (dtype, itemsize),
570
+ buffer=buffer,
571
+ offset=offset, strides=strides,
572
+ order=order)
573
+ if filler is not None:
574
+ self[...] = filler
575
+
576
+ return self
577
+
578
+ def __array_wrap__(self, arr, context=None, return_scalar=False):
579
+ # When calling a ufunc (and some other functions), we return a
580
+ # chararray if the ufunc output is a string-like array,
581
+ # or an ndarray otherwise
582
+ if arr.dtype.char in "SUbc":
583
+ return arr.view(type(self))
584
+ return arr
585
+
586
+ def __array_finalize__(self, obj):
587
+ # The b is a special case because it is used for reconstructing.
588
+ if self.dtype.char not in 'VSUbc':
589
+ raise ValueError("Can only create a chararray from string data.")
590
+
591
+ def __getitem__(self, obj):
592
+ val = ndarray.__getitem__(self, obj)
593
+ if isinstance(val, character):
594
+ return val.rstrip()
595
+ return val
596
+
597
+ # IMPLEMENTATION NOTE: Most of the methods of this class are
598
+ # direct delegations to the free functions in this module.
599
+ # However, those that return an array of strings should instead
600
+ # return a chararray, so some extra wrapping is required.
601
+
602
+ def __eq__(self, other):
603
+ """
604
+ Return (self == other) element-wise.
605
+
606
+ See Also
607
+ --------
608
+ equal
609
+ """
610
+ return equal(self, other)
611
+
612
+ def __ne__(self, other):
613
+ """
614
+ Return (self != other) element-wise.
615
+
616
+ See Also
617
+ --------
618
+ not_equal
619
+ """
620
+ return not_equal(self, other)
621
+
622
+ def __ge__(self, other):
623
+ """
624
+ Return (self >= other) element-wise.
625
+
626
+ See Also
627
+ --------
628
+ greater_equal
629
+ """
630
+ return greater_equal(self, other)
631
+
632
+ def __le__(self, other):
633
+ """
634
+ Return (self <= other) element-wise.
635
+
636
+ See Also
637
+ --------
638
+ less_equal
639
+ """
640
+ return less_equal(self, other)
641
+
642
+ def __gt__(self, other):
643
+ """
644
+ Return (self > other) element-wise.
645
+
646
+ See Also
647
+ --------
648
+ greater
649
+ """
650
+ return greater(self, other)
651
+
652
+ def __lt__(self, other):
653
+ """
654
+ Return (self < other) element-wise.
655
+
656
+ See Also
657
+ --------
658
+ less
659
+ """
660
+ return less(self, other)
661
+
662
+ def __add__(self, other):
663
+ """
664
+ Return (self + other), that is string concatenation,
665
+ element-wise for a pair of array_likes of str or unicode.
666
+
667
+ See Also
668
+ --------
669
+ add
670
+ """
671
+ return add(self, other)
672
+
673
+ def __radd__(self, other):
674
+ """
675
+ Return (other + self), that is string concatenation,
676
+ element-wise for a pair of array_likes of `bytes_` or `str_`.
677
+
678
+ See Also
679
+ --------
680
+ add
681
+ """
682
+ return add(other, self)
683
+
684
+ def __mul__(self, i):
685
+ """
686
+ Return (self * i), that is string multiple concatenation,
687
+ element-wise.
688
+
689
+ See Also
690
+ --------
691
+ multiply
692
+ """
693
+ return asarray(multiply(self, i))
694
+
695
+ def __rmul__(self, i):
696
+ """
697
+ Return (self * i), that is string multiple concatenation,
698
+ element-wise.
699
+
700
+ See Also
701
+ --------
702
+ multiply
703
+ """
704
+ return asarray(multiply(self, i))
705
+
706
+ def __mod__(self, i):
707
+ """
708
+ Return (self % i), that is pre-Python 2.6 string formatting
709
+ (interpolation), element-wise for a pair of array_likes of `bytes_`
710
+ or `str_`.
711
+
712
+ See Also
713
+ --------
714
+ mod
715
+ """
716
+ return asarray(mod(self, i))
717
+
718
+ def __rmod__(self, other):
719
+ return NotImplemented
720
+
721
+ def argsort(self, axis=-1, kind=None, order=None, *, stable=None):
722
+ """
723
+ Return the indices that sort the array lexicographically.
724
+
725
+ For full documentation see `numpy.argsort`, for which this method is
726
+ in fact merely a "thin wrapper."
727
+
728
+ Examples
729
+ --------
730
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
731
+ >>> c = c.view(np.char.chararray); c
732
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
733
+ dtype='|S5')
734
+ >>> c[c.argsort()]
735
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
736
+ dtype='|S5')
737
+
738
+ """
739
+ return self.__array__().argsort(axis, kind, order, stable=stable)
740
+ argsort.__doc__ = ndarray.argsort.__doc__
741
+
742
+ def capitalize(self):
743
+ """
744
+ Return a copy of `self` with only the first character of each element
745
+ capitalized.
746
+
747
+ See Also
748
+ --------
749
+ char.capitalize
750
+
751
+ """
752
+ return asarray(capitalize(self))
753
+
754
+ def center(self, width, fillchar=' '):
755
+ """
756
+ Return a copy of `self` with its elements centered in a
757
+ string of length `width`.
758
+
759
+ See Also
760
+ --------
761
+ center
762
+ """
763
+ return asarray(center(self, width, fillchar))
764
+
765
+ def count(self, sub, start=0, end=None):
766
+ """
767
+ Returns an array with the number of non-overlapping occurrences of
768
+ substring `sub` in the range [`start`, `end`].
769
+
770
+ See Also
771
+ --------
772
+ char.count
773
+
774
+ """
775
+ return count(self, sub, start, end)
776
+
777
+ def decode(self, encoding=None, errors=None):
778
+ """
779
+ Calls ``bytes.decode`` element-wise.
780
+
781
+ See Also
782
+ --------
783
+ char.decode
784
+
785
+ """
786
+ return decode(self, encoding, errors)
787
+
788
+ def encode(self, encoding=None, errors=None):
789
+ """
790
+ Calls :meth:`str.encode` element-wise.
791
+
792
+ See Also
793
+ --------
794
+ char.encode
795
+
796
+ """
797
+ return encode(self, encoding, errors)
798
+
799
+ def endswith(self, suffix, start=0, end=None):
800
+ """
801
+ Returns a boolean array which is `True` where the string element
802
+ in `self` ends with `suffix`, otherwise `False`.
803
+
804
+ See Also
805
+ --------
806
+ char.endswith
807
+
808
+ """
809
+ return endswith(self, suffix, start, end)
810
+
811
+ def expandtabs(self, tabsize=8):
812
+ """
813
+ Return a copy of each string element where all tab characters are
814
+ replaced by one or more spaces.
815
+
816
+ See Also
817
+ --------
818
+ char.expandtabs
819
+
820
+ """
821
+ return asarray(expandtabs(self, tabsize))
822
+
823
+ def find(self, sub, start=0, end=None):
824
+ """
825
+ For each element, return the lowest index in the string where
826
+ substring `sub` is found.
827
+
828
+ See Also
829
+ --------
830
+ char.find
831
+
832
+ """
833
+ return find(self, sub, start, end)
834
+
835
+ def index(self, sub, start=0, end=None):
836
+ """
837
+ Like `find`, but raises :exc:`ValueError` when the substring is not
838
+ found.
839
+
840
+ See Also
841
+ --------
842
+ char.index
843
+
844
+ """
845
+ return index(self, sub, start, end)
846
+
847
+ def isalnum(self):
848
+ """
849
+ Returns true for each element if all characters in the string
850
+ are alphanumeric and there is at least one character, false
851
+ otherwise.
852
+
853
+ See Also
854
+ --------
855
+ char.isalnum
856
+
857
+ """
858
+ return isalnum(self)
859
+
860
+ def isalpha(self):
861
+ """
862
+ Returns true for each element if all characters in the string
863
+ are alphabetic and there is at least one character, false
864
+ otherwise.
865
+
866
+ See Also
867
+ --------
868
+ char.isalpha
869
+
870
+ """
871
+ return isalpha(self)
872
+
873
+ def isdigit(self):
874
+ """
875
+ Returns true for each element if all characters in the string are
876
+ digits and there is at least one character, false otherwise.
877
+
878
+ See Also
879
+ --------
880
+ char.isdigit
881
+
882
+ """
883
+ return isdigit(self)
884
+
885
+ def islower(self):
886
+ """
887
+ Returns true for each element if all cased characters in the
888
+ string are lowercase and there is at least one cased character,
889
+ false otherwise.
890
+
891
+ See Also
892
+ --------
893
+ char.islower
894
+
895
+ """
896
+ return islower(self)
897
+
898
+ def isspace(self):
899
+ """
900
+ Returns true for each element if there are only whitespace
901
+ characters in the string and there is at least one character,
902
+ false otherwise.
903
+
904
+ See Also
905
+ --------
906
+ char.isspace
907
+
908
+ """
909
+ return isspace(self)
910
+
911
+ def istitle(self):
912
+ """
913
+ Returns true for each element if the element is a titlecased
914
+ string and there is at least one character, false otherwise.
915
+
916
+ See Also
917
+ --------
918
+ char.istitle
919
+
920
+ """
921
+ return istitle(self)
922
+
923
+ def isupper(self):
924
+ """
925
+ Returns true for each element if all cased characters in the
926
+ string are uppercase and there is at least one character, false
927
+ otherwise.
928
+
929
+ See Also
930
+ --------
931
+ char.isupper
932
+
933
+ """
934
+ return isupper(self)
935
+
936
+ def join(self, seq):
937
+ """
938
+ Return a string which is the concatenation of the strings in the
939
+ sequence `seq`.
940
+
941
+ See Also
942
+ --------
943
+ char.join
944
+
945
+ """
946
+ return join(self, seq)
947
+
948
+ def ljust(self, width, fillchar=' '):
949
+ """
950
+ Return an array with the elements of `self` left-justified in a
951
+ string of length `width`.
952
+
953
+ See Also
954
+ --------
955
+ char.ljust
956
+
957
+ """
958
+ return asarray(ljust(self, width, fillchar))
959
+
960
+ def lower(self):
961
+ """
962
+ Return an array with the elements of `self` converted to
963
+ lowercase.
964
+
965
+ See Also
966
+ --------
967
+ char.lower
968
+
969
+ """
970
+ return asarray(lower(self))
971
+
972
+ def lstrip(self, chars=None):
973
+ """
974
+ For each element in `self`, return a copy with the leading characters
975
+ removed.
976
+
977
+ See Also
978
+ --------
979
+ char.lstrip
980
+
981
+ """
982
+ return lstrip(self, chars)
983
+
984
+ def partition(self, sep):
985
+ """
986
+ Partition each element in `self` around `sep`.
987
+
988
+ See Also
989
+ --------
990
+ partition
991
+ """
992
+ return asarray(partition(self, sep))
993
+
994
+ def replace(self, old, new, count=None):
995
+ """
996
+ For each element in `self`, return a copy of the string with all
997
+ occurrences of substring `old` replaced by `new`.
998
+
999
+ See Also
1000
+ --------
1001
+ char.replace
1002
+
1003
+ """
1004
+ return replace(self, old, new, count if count is not None else -1)
1005
+
1006
+ def rfind(self, sub, start=0, end=None):
1007
+ """
1008
+ For each element in `self`, return the highest index in the string
1009
+ where substring `sub` is found, such that `sub` is contained
1010
+ within [`start`, `end`].
1011
+
1012
+ See Also
1013
+ --------
1014
+ char.rfind
1015
+
1016
+ """
1017
+ return rfind(self, sub, start, end)
1018
+
1019
+ def rindex(self, sub, start=0, end=None):
1020
+ """
1021
+ Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
1022
+ not found.
1023
+
1024
+ See Also
1025
+ --------
1026
+ char.rindex
1027
+
1028
+ """
1029
+ return rindex(self, sub, start, end)
1030
+
1031
+ def rjust(self, width, fillchar=' '):
1032
+ """
1033
+ Return an array with the elements of `self`
1034
+ right-justified in a string of length `width`.
1035
+
1036
+ See Also
1037
+ --------
1038
+ char.rjust
1039
+
1040
+ """
1041
+ return asarray(rjust(self, width, fillchar))
1042
+
1043
+ def rpartition(self, sep):
1044
+ """
1045
+ Partition each element in `self` around `sep`.
1046
+
1047
+ See Also
1048
+ --------
1049
+ rpartition
1050
+ """
1051
+ return asarray(rpartition(self, sep))
1052
+
1053
+ def rsplit(self, sep=None, maxsplit=None):
1054
+ """
1055
+ For each element in `self`, return a list of the words in
1056
+ the string, using `sep` as the delimiter string.
1057
+
1058
+ See Also
1059
+ --------
1060
+ char.rsplit
1061
+
1062
+ """
1063
+ return rsplit(self, sep, maxsplit)
1064
+
1065
+ def rstrip(self, chars=None):
1066
+ """
1067
+ For each element in `self`, return a copy with the trailing
1068
+ characters removed.
1069
+
1070
+ See Also
1071
+ --------
1072
+ char.rstrip
1073
+
1074
+ """
1075
+ return rstrip(self, chars)
1076
+
1077
+ def split(self, sep=None, maxsplit=None):
1078
+ """
1079
+ For each element in `self`, return a list of the words in the
1080
+ string, using `sep` as the delimiter string.
1081
+
1082
+ See Also
1083
+ --------
1084
+ char.split
1085
+
1086
+ """
1087
+ return split(self, sep, maxsplit)
1088
+
1089
+ def splitlines(self, keepends=None):
1090
+ """
1091
+ For each element in `self`, return a list of the lines in the
1092
+ element, breaking at line boundaries.
1093
+
1094
+ See Also
1095
+ --------
1096
+ char.splitlines
1097
+
1098
+ """
1099
+ return splitlines(self, keepends)
1100
+
1101
+ def startswith(self, prefix, start=0, end=None):
1102
+ """
1103
+ Returns a boolean array which is `True` where the string element
1104
+ in `self` starts with `prefix`, otherwise `False`.
1105
+
1106
+ See Also
1107
+ --------
1108
+ char.startswith
1109
+
1110
+ """
1111
+ return startswith(self, prefix, start, end)
1112
+
1113
+ def strip(self, chars=None):
1114
+ """
1115
+ For each element in `self`, return a copy with the leading and
1116
+ trailing characters removed.
1117
+
1118
+ See Also
1119
+ --------
1120
+ char.strip
1121
+
1122
+ """
1123
+ return strip(self, chars)
1124
+
1125
+ def swapcase(self):
1126
+ """
1127
+ For each element in `self`, return a copy of the string with
1128
+ uppercase characters converted to lowercase and vice versa.
1129
+
1130
+ See Also
1131
+ --------
1132
+ char.swapcase
1133
+
1134
+ """
1135
+ return asarray(swapcase(self))
1136
+
1137
+ def title(self):
1138
+ """
1139
+ For each element in `self`, return a titlecased version of the
1140
+ string: words start with uppercase characters, all remaining cased
1141
+ characters are lowercase.
1142
+
1143
+ See Also
1144
+ --------
1145
+ char.title
1146
+
1147
+ """
1148
+ return asarray(title(self))
1149
+
1150
+ def translate(self, table, deletechars=None):
1151
+ """
1152
+ For each element in `self`, return a copy of the string where
1153
+ all characters occurring in the optional argument
1154
+ `deletechars` are removed, and the remaining characters have
1155
+ been mapped through the given translation table.
1156
+
1157
+ See Also
1158
+ --------
1159
+ char.translate
1160
+
1161
+ """
1162
+ return asarray(translate(self, table, deletechars))
1163
+
1164
+ def upper(self):
1165
+ """
1166
+ Return an array with the elements of `self` converted to
1167
+ uppercase.
1168
+
1169
+ See Also
1170
+ --------
1171
+ char.upper
1172
+
1173
+ """
1174
+ return asarray(upper(self))
1175
+
1176
+ def zfill(self, width):
1177
+ """
1178
+ Return the numeric string left-filled with zeros in a string of
1179
+ length `width`.
1180
+
1181
+ See Also
1182
+ --------
1183
+ char.zfill
1184
+
1185
+ """
1186
+ return asarray(zfill(self, width))
1187
+
1188
+ def isnumeric(self):
1189
+ """
1190
+ For each element in `self`, return True if there are only
1191
+ numeric characters in the element.
1192
+
1193
+ See Also
1194
+ --------
1195
+ char.isnumeric
1196
+
1197
+ """
1198
+ return isnumeric(self)
1199
+
1200
+ def isdecimal(self):
1201
+ """
1202
+ For each element in `self`, return True if there are only
1203
+ decimal characters in the element.
1204
+
1205
+ See Also
1206
+ --------
1207
+ char.isdecimal
1208
+
1209
+ """
1210
+ return isdecimal(self)
1211
+
1212
+
1213
+ @set_module("numpy.char")
1214
+ def array(obj, itemsize=None, copy=True, unicode=None, order=None):
1215
+ """
1216
+ Create a `~numpy.char.chararray`.
1217
+
1218
+ .. note::
1219
+ This class is provided for numarray backward-compatibility.
1220
+ New code (not concerned with numarray compatibility) should use
1221
+ arrays of type `bytes_` or `str_` and use the free functions
1222
+ in :mod:`numpy.char` for fast vectorized string operations instead.
1223
+
1224
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
1225
+ class adds the following functionality:
1226
+
1227
+ 1) values automatically have whitespace removed from the end
1228
+ when indexed
1229
+
1230
+ 2) comparison operators automatically remove whitespace from the
1231
+ end when comparing values
1232
+
1233
+ 3) vectorized string operations are provided as methods
1234
+ (e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
1235
+ and infix operators (e.g. ``+, *, %``)
1236
+
1237
+ Parameters
1238
+ ----------
1239
+ obj : array of str or unicode-like
1240
+
1241
+ itemsize : int, optional
1242
+ `itemsize` is the number of characters per scalar in the
1243
+ resulting array. If `itemsize` is None, and `obj` is an
1244
+ object array or a Python list, the `itemsize` will be
1245
+ automatically determined. If `itemsize` is provided and `obj`
1246
+ is of type str or unicode, then the `obj` string will be
1247
+ chunked into `itemsize` pieces.
1248
+
1249
+ copy : bool, optional
1250
+ If true (default), then the object is copied. Otherwise, a copy
1251
+ will only be made if ``__array__`` returns a copy, if obj is a
1252
+ nested sequence, or if a copy is needed to satisfy any of the other
1253
+ requirements (`itemsize`, unicode, `order`, etc.).
1254
+
1255
+ unicode : bool, optional
1256
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
1257
+ characters, when false only 8-bit characters. If unicode is
1258
+ None and `obj` is one of the following:
1259
+
1260
+ - a `~numpy.char.chararray`,
1261
+ - an ndarray of type :class:`str_` or :class:`bytes_`
1262
+ - a Python :class:`str` or :class:`bytes` object,
1263
+
1264
+ then the unicode setting of the output array will be
1265
+ automatically determined.
1266
+
1267
+ order : {'C', 'F', 'A'}, optional
1268
+ Specify the order of the array. If order is 'C' (default), then the
1269
+ array will be in C-contiguous order (last-index varies the
1270
+ fastest). If order is 'F', then the returned array
1271
+ will be in Fortran-contiguous order (first-index varies the
1272
+ fastest). If order is 'A', then the returned array may
1273
+ be in any order (either C-, Fortran-contiguous, or even
1274
+ discontiguous).
1275
+
1276
+ Examples
1277
+ --------
1278
+
1279
+ >>> import numpy as np
1280
+ >>> char_array = np.char.array(['hello', 'world', 'numpy','array'])
1281
+ >>> char_array
1282
+ chararray(['hello', 'world', 'numpy', 'array'], dtype='<U5')
1283
+
1284
+ """
1285
+ if isinstance(obj, (bytes, str)):
1286
+ if unicode is None:
1287
+ if isinstance(obj, str):
1288
+ unicode = True
1289
+ else:
1290
+ unicode = False
1291
+
1292
+ if itemsize is None:
1293
+ itemsize = len(obj)
1294
+ shape = len(obj) // itemsize
1295
+
1296
+ return chararray(shape, itemsize=itemsize, unicode=unicode,
1297
+ buffer=obj, order=order)
1298
+
1299
+ if isinstance(obj, (list, tuple)):
1300
+ obj = asnarray(obj)
1301
+
1302
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
1303
+ # If we just have a vanilla chararray, create a chararray
1304
+ # view around it.
1305
+ if not isinstance(obj, chararray):
1306
+ obj = obj.view(chararray)
1307
+
1308
+ if itemsize is None:
1309
+ itemsize = obj.itemsize
1310
+ # itemsize is in 8-bit chars, so for Unicode, we need
1311
+ # to divide by the size of a single Unicode character,
1312
+ # which for NumPy is always 4
1313
+ if issubclass(obj.dtype.type, str_):
1314
+ itemsize //= 4
1315
+
1316
+ if unicode is None:
1317
+ if issubclass(obj.dtype.type, str_):
1318
+ unicode = True
1319
+ else:
1320
+ unicode = False
1321
+
1322
+ if unicode:
1323
+ dtype = str_
1324
+ else:
1325
+ dtype = bytes_
1326
+
1327
+ if order is not None:
1328
+ obj = asnarray(obj, order=order)
1329
+ if (copy or
1330
+ (itemsize != obj.itemsize) or
1331
+ (not unicode and isinstance(obj, str_)) or
1332
+ (unicode and isinstance(obj, bytes_))):
1333
+ obj = obj.astype((dtype, int(itemsize)))
1334
+ return obj
1335
+
1336
+ if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
1337
+ if itemsize is None:
1338
+ # Since no itemsize was specified, convert the input array to
1339
+ # a list so the ndarray constructor will automatically
1340
+ # determine the itemsize for us.
1341
+ obj = obj.tolist()
1342
+ # Fall through to the default case
1343
+
1344
+ if unicode:
1345
+ dtype = str_
1346
+ else:
1347
+ dtype = bytes_
1348
+
1349
+ if itemsize is None:
1350
+ val = narray(obj, dtype=dtype, order=order, subok=True)
1351
+ else:
1352
+ val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
1353
+ return val.view(chararray)
1354
+
1355
+
1356
+ @set_module("numpy.char")
1357
+ def asarray(obj, itemsize=None, unicode=None, order=None):
1358
+ """
1359
+ Convert the input to a `~numpy.char.chararray`, copying the data only if
1360
+ necessary.
1361
+
1362
+ Versus a NumPy array of dtype `bytes_` or `str_`, this
1363
+ class adds the following functionality:
1364
+
1365
+ 1) values automatically have whitespace removed from the end
1366
+ when indexed
1367
+
1368
+ 2) comparison operators automatically remove whitespace from the
1369
+ end when comparing values
1370
+
1371
+ 3) vectorized string operations are provided as methods
1372
+ (e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
1373
+ and infix operators (e.g. ``+``, ``*``, ``%``)
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ obj : array of str or unicode-like
1378
+
1379
+ itemsize : int, optional
1380
+ `itemsize` is the number of characters per scalar in the
1381
+ resulting array. If `itemsize` is None, and `obj` is an
1382
+ object array or a Python list, the `itemsize` will be
1383
+ automatically determined. If `itemsize` is provided and `obj`
1384
+ is of type str or unicode, then the `obj` string will be
1385
+ chunked into `itemsize` pieces.
1386
+
1387
+ unicode : bool, optional
1388
+ When true, the resulting `~numpy.char.chararray` can contain Unicode
1389
+ characters, when false only 8-bit characters. If unicode is
1390
+ None and `obj` is one of the following:
1391
+
1392
+ - a `~numpy.char.chararray`,
1393
+ - an ndarray of type `str_` or `unicode_`
1394
+ - a Python str or unicode object,
1395
+
1396
+ then the unicode setting of the output array will be
1397
+ automatically determined.
1398
+
1399
+ order : {'C', 'F'}, optional
1400
+ Specify the order of the array. If order is 'C' (default), then the
1401
+ array will be in C-contiguous order (last-index varies the
1402
+ fastest). If order is 'F', then the returned array
1403
+ will be in Fortran-contiguous order (first-index varies the
1404
+ fastest).
1405
+
1406
+ Examples
1407
+ --------
1408
+ >>> import numpy as np
1409
+ >>> np.char.asarray(['hello', 'world'])
1410
+ chararray(['hello', 'world'], dtype='<U5')
1411
+
1412
+ """
1413
+ return array(obj, itemsize, copy=False,
1414
+ unicode=unicode, order=order)
python/user_packages/Python313/site-packages/numpy/_core/defchararray.pyi ADDED
@@ -0,0 +1,1150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Any,
3
+ Literal as L,
4
+ Self,
5
+ SupportsIndex,
6
+ SupportsInt,
7
+ TypeAlias,
8
+ overload,
9
+ )
10
+ from typing_extensions import Buffer, TypeVar
11
+
12
+ import numpy as np
13
+ from numpy import _OrderKACF, bytes_, dtype, int_, ndarray, object_, str_
14
+ from numpy._core.multiarray import compare_chararrays
15
+ from numpy._typing import (
16
+ NDArray,
17
+ _AnyShape,
18
+ _ArrayLikeAnyString_co as UST_co,
19
+ _ArrayLikeBool_co as b_co,
20
+ _ArrayLikeBytes_co as S_co,
21
+ _ArrayLikeInt_co as i_co,
22
+ _ArrayLikeStr_co as U_co,
23
+ _ArrayLikeString_co as T_co,
24
+ _Shape,
25
+ _ShapeLike,
26
+ _SupportsArray,
27
+ )
28
+
29
+ __all__ = [
30
+ "equal",
31
+ "not_equal",
32
+ "greater_equal",
33
+ "less_equal",
34
+ "greater",
35
+ "less",
36
+ "str_len",
37
+ "add",
38
+ "multiply",
39
+ "mod",
40
+ "capitalize",
41
+ "center",
42
+ "count",
43
+ "decode",
44
+ "encode",
45
+ "endswith",
46
+ "expandtabs",
47
+ "find",
48
+ "index",
49
+ "isalnum",
50
+ "isalpha",
51
+ "isdigit",
52
+ "islower",
53
+ "isspace",
54
+ "istitle",
55
+ "isupper",
56
+ "join",
57
+ "ljust",
58
+ "lower",
59
+ "lstrip",
60
+ "partition",
61
+ "replace",
62
+ "rfind",
63
+ "rindex",
64
+ "rjust",
65
+ "rpartition",
66
+ "rsplit",
67
+ "rstrip",
68
+ "split",
69
+ "splitlines",
70
+ "startswith",
71
+ "strip",
72
+ "swapcase",
73
+ "title",
74
+ "translate",
75
+ "upper",
76
+ "zfill",
77
+ "isnumeric",
78
+ "isdecimal",
79
+ "array",
80
+ "asarray",
81
+ "compare_chararrays",
82
+ "chararray",
83
+ ]
84
+
85
+ _ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True)
86
+ _CharacterT = TypeVar("_CharacterT", bound=np.character)
87
+ _CharDTypeT_co = TypeVar("_CharDTypeT_co", bound=dtype[np.character], default=dtype, covariant=True)
88
+
89
+ _CharArray: TypeAlias = chararray[_AnyShape, dtype[_CharacterT]]
90
+
91
+ _StringDTypeArray: TypeAlias = np.ndarray[_AnyShape, np.dtypes.StringDType]
92
+ _StringDTypeOrUnicodeArray: TypeAlias = _StringDTypeArray | NDArray[np.str_]
93
+ _StringDTypeSupportsArray: TypeAlias = _SupportsArray[np.dtypes.StringDType]
94
+
95
+ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
96
+ @overload
97
+ def __new__(
98
+ subtype,
99
+ shape: _ShapeLike,
100
+ itemsize: SupportsIndex | SupportsInt = 1,
101
+ unicode: L[False] = False,
102
+ buffer: Buffer | np.ndarray | None = None,
103
+ offset: SupportsIndex = 0,
104
+ strides: _ShapeLike | None = None,
105
+ order: _OrderKACF = "C",
106
+ ) -> _CharArray[bytes_]: ...
107
+ @overload
108
+ def __new__(
109
+ subtype,
110
+ shape: _ShapeLike,
111
+ itemsize: SupportsIndex | SupportsInt,
112
+ unicode: L[True],
113
+ buffer: Buffer | np.ndarray | None = None,
114
+ offset: SupportsIndex = 0,
115
+ strides: _ShapeLike | None = None,
116
+ order: _OrderKACF = "C",
117
+ ) -> _CharArray[str_]: ...
118
+ @overload
119
+ def __new__(
120
+ subtype,
121
+ shape: _ShapeLike,
122
+ itemsize: SupportsIndex | SupportsInt = 1,
123
+ *,
124
+ unicode: L[True],
125
+ buffer: Buffer | np.ndarray | None = None,
126
+ offset: SupportsIndex = 0,
127
+ strides: _ShapeLike | None = None,
128
+ order: _OrderKACF = "C",
129
+ ) -> _CharArray[str_]: ...
130
+
131
+ def __array_finalize__(self, obj: object) -> None: ...
132
+ def __mul__(self, other: i_co) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
133
+ def __rmul__(self, other: i_co) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
134
+ def __mod__(self, i: Any) -> chararray[_AnyShape, _CharDTypeT_co]: ... # type: ignore[override]
135
+
136
+ @overload # type: ignore[override]
137
+ def __eq__(
138
+ self: _CharArray[str_],
139
+ other: U_co,
140
+ ) -> NDArray[np.bool]: ...
141
+ @overload
142
+ def __eq__(
143
+ self: _CharArray[bytes_],
144
+ other: S_co,
145
+ ) -> NDArray[np.bool]: ...
146
+
147
+ @overload # type: ignore[override]
148
+ def __ne__(
149
+ self: _CharArray[str_],
150
+ other: U_co,
151
+ ) -> NDArray[np.bool]: ...
152
+ @overload
153
+ def __ne__(
154
+ self: _CharArray[bytes_],
155
+ other: S_co,
156
+ ) -> NDArray[np.bool]: ...
157
+
158
+ @overload # type: ignore[override]
159
+ def __ge__(
160
+ self: _CharArray[str_],
161
+ other: U_co,
162
+ ) -> NDArray[np.bool]: ...
163
+ @overload
164
+ def __ge__(
165
+ self: _CharArray[bytes_],
166
+ other: S_co,
167
+ ) -> NDArray[np.bool]: ...
168
+
169
+ @overload # type: ignore[override]
170
+ def __le__(
171
+ self: _CharArray[str_],
172
+ other: U_co,
173
+ ) -> NDArray[np.bool]: ...
174
+ @overload
175
+ def __le__(
176
+ self: _CharArray[bytes_],
177
+ other: S_co,
178
+ ) -> NDArray[np.bool]: ...
179
+
180
+ @overload # type: ignore[override]
181
+ def __gt__(
182
+ self: _CharArray[str_],
183
+ other: U_co,
184
+ ) -> NDArray[np.bool]: ...
185
+ @overload
186
+ def __gt__(
187
+ self: _CharArray[bytes_],
188
+ other: S_co,
189
+ ) -> NDArray[np.bool]: ...
190
+
191
+ @overload # type: ignore[override]
192
+ def __lt__(
193
+ self: _CharArray[str_],
194
+ other: U_co,
195
+ ) -> NDArray[np.bool]: ...
196
+ @overload
197
+ def __lt__(
198
+ self: _CharArray[bytes_],
199
+ other: S_co,
200
+ ) -> NDArray[np.bool]: ...
201
+
202
+ @overload # type: ignore[override]
203
+ def __add__(
204
+ self: _CharArray[str_],
205
+ other: U_co,
206
+ ) -> _CharArray[str_]: ...
207
+ @overload
208
+ def __add__(
209
+ self: _CharArray[bytes_],
210
+ other: S_co,
211
+ ) -> _CharArray[bytes_]: ...
212
+
213
+ @overload # type: ignore[override]
214
+ def __radd__(
215
+ self: _CharArray[str_],
216
+ other: U_co,
217
+ ) -> _CharArray[str_]: ...
218
+ @overload
219
+ def __radd__(
220
+ self: _CharArray[bytes_],
221
+ other: S_co,
222
+ ) -> _CharArray[bytes_]: ...
223
+
224
+ @overload
225
+ def center(
226
+ self: _CharArray[str_],
227
+ width: i_co,
228
+ fillchar: U_co = " ",
229
+ ) -> _CharArray[str_]: ...
230
+ @overload
231
+ def center(
232
+ self: _CharArray[bytes_],
233
+ width: i_co,
234
+ fillchar: str | S_co = " ",
235
+ ) -> _CharArray[bytes_]: ...
236
+
237
+ @overload
238
+ def count(
239
+ self: _CharArray[str_],
240
+ sub: U_co,
241
+ start: i_co = 0,
242
+ end: i_co | None = None,
243
+ ) -> NDArray[int_]: ...
244
+ @overload
245
+ def count(
246
+ self: _CharArray[bytes_],
247
+ sub: S_co,
248
+ start: i_co = 0,
249
+ end: i_co | None = None,
250
+ ) -> NDArray[int_]: ...
251
+
252
+ def decode(
253
+ self: _CharArray[bytes_],
254
+ encoding: str | None = None,
255
+ errors: str | None = None,
256
+ ) -> _CharArray[str_]: ...
257
+
258
+ def encode(
259
+ self: _CharArray[str_],
260
+ encoding: str | None = None,
261
+ errors: str | None = None,
262
+ ) -> _CharArray[bytes_]: ...
263
+
264
+ @overload
265
+ def endswith(
266
+ self: _CharArray[str_],
267
+ suffix: U_co,
268
+ start: i_co = 0,
269
+ end: i_co | None = None,
270
+ ) -> NDArray[np.bool]: ...
271
+ @overload
272
+ def endswith(
273
+ self: _CharArray[bytes_],
274
+ suffix: S_co,
275
+ start: i_co = 0,
276
+ end: i_co | None = None,
277
+ ) -> NDArray[np.bool]: ...
278
+
279
+ def expandtabs(
280
+ self,
281
+ tabsize: i_co = 8,
282
+ ) -> Self: ...
283
+
284
+ @overload
285
+ def find(
286
+ self: _CharArray[str_],
287
+ sub: U_co,
288
+ start: i_co = 0,
289
+ end: i_co | None = None,
290
+ ) -> NDArray[int_]: ...
291
+ @overload
292
+ def find(
293
+ self: _CharArray[bytes_],
294
+ sub: S_co,
295
+ start: i_co = 0,
296
+ end: i_co | None = None,
297
+ ) -> NDArray[int_]: ...
298
+
299
+ @overload
300
+ def index(
301
+ self: _CharArray[str_],
302
+ sub: U_co,
303
+ start: i_co = 0,
304
+ end: i_co | None = None,
305
+ ) -> NDArray[int_]: ...
306
+ @overload
307
+ def index(
308
+ self: _CharArray[bytes_],
309
+ sub: S_co,
310
+ start: i_co = 0,
311
+ end: i_co | None = None,
312
+ ) -> NDArray[int_]: ...
313
+
314
+ @overload
315
+ def join(
316
+ self: _CharArray[str_],
317
+ seq: U_co,
318
+ ) -> _CharArray[str_]: ...
319
+ @overload
320
+ def join(
321
+ self: _CharArray[bytes_],
322
+ seq: S_co,
323
+ ) -> _CharArray[bytes_]: ...
324
+
325
+ @overload
326
+ def ljust(
327
+ self: _CharArray[str_],
328
+ width: i_co,
329
+ fillchar: U_co = " ",
330
+ ) -> _CharArray[str_]: ...
331
+ @overload
332
+ def ljust(
333
+ self: _CharArray[bytes_],
334
+ width: i_co,
335
+ fillchar: str | S_co = " ",
336
+ ) -> _CharArray[bytes_]: ...
337
+
338
+ @overload
339
+ def lstrip(
340
+ self: _CharArray[str_],
341
+ chars: U_co | None = None,
342
+ ) -> _CharArray[str_]: ...
343
+ @overload
344
+ def lstrip(
345
+ self: _CharArray[bytes_],
346
+ chars: S_co | None = None,
347
+ ) -> _CharArray[bytes_]: ...
348
+
349
+ @overload # type: ignore[override]
350
+ def partition(
351
+ self: _CharArray[str_],
352
+ sep: U_co,
353
+ ) -> _CharArray[str_]: ...
354
+ @overload
355
+ def partition(
356
+ self: _CharArray[bytes_],
357
+ sep: S_co,
358
+ ) -> _CharArray[bytes_]: ...
359
+
360
+ @overload
361
+ def replace(
362
+ self: _CharArray[str_],
363
+ old: U_co,
364
+ new: U_co,
365
+ count: i_co | None = None,
366
+ ) -> _CharArray[str_]: ...
367
+ @overload
368
+ def replace(
369
+ self: _CharArray[bytes_],
370
+ old: S_co,
371
+ new: S_co,
372
+ count: i_co | None = None,
373
+ ) -> _CharArray[bytes_]: ...
374
+
375
+ @overload
376
+ def rfind(
377
+ self: _CharArray[str_],
378
+ sub: U_co,
379
+ start: i_co = 0,
380
+ end: i_co | None = None,
381
+ ) -> NDArray[int_]: ...
382
+ @overload
383
+ def rfind(
384
+ self: _CharArray[bytes_],
385
+ sub: S_co,
386
+ start: i_co = 0,
387
+ end: i_co | None = None,
388
+ ) -> NDArray[int_]: ...
389
+
390
+ @overload
391
+ def rindex(
392
+ self: _CharArray[str_],
393
+ sub: U_co,
394
+ start: i_co = 0,
395
+ end: i_co | None = None,
396
+ ) -> NDArray[int_]: ...
397
+ @overload
398
+ def rindex(
399
+ self: _CharArray[bytes_],
400
+ sub: S_co,
401
+ start: i_co = 0,
402
+ end: i_co | None = None,
403
+ ) -> NDArray[int_]: ...
404
+
405
+ @overload
406
+ def rjust(
407
+ self: _CharArray[str_],
408
+ width: i_co,
409
+ fillchar: U_co = " ",
410
+ ) -> _CharArray[str_]: ...
411
+ @overload
412
+ def rjust(
413
+ self: _CharArray[bytes_],
414
+ width: i_co,
415
+ fillchar: str | S_co = " ",
416
+ ) -> _CharArray[bytes_]: ...
417
+
418
+ @overload
419
+ def rpartition(
420
+ self: _CharArray[str_],
421
+ sep: U_co,
422
+ ) -> _CharArray[str_]: ...
423
+ @overload
424
+ def rpartition(
425
+ self: _CharArray[bytes_],
426
+ sep: S_co,
427
+ ) -> _CharArray[bytes_]: ...
428
+
429
+ @overload
430
+ def rsplit(
431
+ self: _CharArray[str_],
432
+ sep: U_co | None = None,
433
+ maxsplit: i_co | None = None,
434
+ ) -> NDArray[object_]: ...
435
+ @overload
436
+ def rsplit(
437
+ self: _CharArray[bytes_],
438
+ sep: S_co | None = None,
439
+ maxsplit: i_co | None = None,
440
+ ) -> NDArray[object_]: ...
441
+
442
+ @overload
443
+ def rstrip(
444
+ self: _CharArray[str_],
445
+ chars: U_co | None = None,
446
+ ) -> _CharArray[str_]: ...
447
+ @overload
448
+ def rstrip(
449
+ self: _CharArray[bytes_],
450
+ chars: S_co | None = None,
451
+ ) -> _CharArray[bytes_]: ...
452
+
453
+ @overload
454
+ def split(
455
+ self: _CharArray[str_],
456
+ sep: U_co | None = None,
457
+ maxsplit: i_co | None = None,
458
+ ) -> NDArray[object_]: ...
459
+ @overload
460
+ def split(
461
+ self: _CharArray[bytes_],
462
+ sep: S_co | None = None,
463
+ maxsplit: i_co | None = None,
464
+ ) -> NDArray[object_]: ...
465
+
466
+ def splitlines(self, keepends: b_co | None = None) -> NDArray[object_]: ...
467
+
468
+ @overload
469
+ def startswith(
470
+ self: _CharArray[str_],
471
+ prefix: U_co,
472
+ start: i_co = 0,
473
+ end: i_co | None = None,
474
+ ) -> NDArray[np.bool]: ...
475
+ @overload
476
+ def startswith(
477
+ self: _CharArray[bytes_],
478
+ prefix: S_co,
479
+ start: i_co = 0,
480
+ end: i_co | None = None,
481
+ ) -> NDArray[np.bool]: ...
482
+
483
+ @overload
484
+ def strip(
485
+ self: _CharArray[str_],
486
+ chars: U_co | None = None,
487
+ ) -> _CharArray[str_]: ...
488
+ @overload
489
+ def strip(
490
+ self: _CharArray[bytes_],
491
+ chars: S_co | None = None,
492
+ ) -> _CharArray[bytes_]: ...
493
+
494
+ @overload
495
+ def translate(
496
+ self: _CharArray[str_],
497
+ table: U_co,
498
+ deletechars: U_co | None = None,
499
+ ) -> _CharArray[str_]: ...
500
+ @overload
501
+ def translate(
502
+ self: _CharArray[bytes_],
503
+ table: S_co,
504
+ deletechars: S_co | None = None,
505
+ ) -> _CharArray[bytes_]: ...
506
+
507
+ def zfill(self, width: i_co) -> Self: ...
508
+ def capitalize(self) -> Self: ...
509
+ def title(self) -> Self: ...
510
+ def swapcase(self) -> Self: ...
511
+ def lower(self) -> Self: ...
512
+ def upper(self) -> Self: ...
513
+ def isalnum(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
514
+ def isalpha(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
515
+ def isdigit(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
516
+ def islower(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
517
+ def isspace(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
518
+ def istitle(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
519
+ def isupper(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
520
+ def isnumeric(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
521
+ def isdecimal(self) -> ndarray[_ShapeT_co, dtype[np.bool]]: ...
522
+
523
+ # Comparison
524
+ @overload
525
+ def equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
526
+ @overload
527
+ def equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
528
+ @overload
529
+ def equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
530
+
531
+ @overload
532
+ def not_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
533
+ @overload
534
+ def not_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
535
+ @overload
536
+ def not_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
537
+
538
+ @overload
539
+ def greater_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
540
+ @overload
541
+ def greater_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
542
+ @overload
543
+ def greater_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
544
+
545
+ @overload
546
+ def less_equal(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
547
+ @overload
548
+ def less_equal(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
549
+ @overload
550
+ def less_equal(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
551
+
552
+ @overload
553
+ def greater(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
554
+ @overload
555
+ def greater(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
556
+ @overload
557
+ def greater(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
558
+
559
+ @overload
560
+ def less(x1: U_co, x2: U_co) -> NDArray[np.bool]: ...
561
+ @overload
562
+ def less(x1: S_co, x2: S_co) -> NDArray[np.bool]: ...
563
+ @overload
564
+ def less(x1: T_co, x2: T_co) -> NDArray[np.bool]: ...
565
+
566
+ @overload
567
+ def add(x1: U_co, x2: U_co) -> NDArray[np.str_]: ...
568
+ @overload
569
+ def add(x1: S_co, x2: S_co) -> NDArray[np.bytes_]: ...
570
+ @overload
571
+ def add(x1: _StringDTypeSupportsArray, x2: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
572
+ @overload
573
+ def add(x1: T_co, x2: T_co) -> _StringDTypeOrUnicodeArray: ...
574
+
575
+ @overload
576
+ def multiply(a: U_co, i: i_co) -> NDArray[np.str_]: ...
577
+ @overload
578
+ def multiply(a: S_co, i: i_co) -> NDArray[np.bytes_]: ...
579
+ @overload
580
+ def multiply(a: _StringDTypeSupportsArray, i: i_co) -> _StringDTypeArray: ...
581
+ @overload
582
+ def multiply(a: T_co, i: i_co) -> _StringDTypeOrUnicodeArray: ...
583
+
584
+ @overload
585
+ def mod(a: U_co, value: Any) -> NDArray[np.str_]: ...
586
+ @overload
587
+ def mod(a: S_co, value: Any) -> NDArray[np.bytes_]: ...
588
+ @overload
589
+ def mod(a: _StringDTypeSupportsArray, value: Any) -> _StringDTypeArray: ...
590
+ @overload
591
+ def mod(a: T_co, value: Any) -> _StringDTypeOrUnicodeArray: ...
592
+
593
+ @overload
594
+ def capitalize(a: U_co) -> NDArray[str_]: ...
595
+ @overload
596
+ def capitalize(a: S_co) -> NDArray[bytes_]: ...
597
+ @overload
598
+ def capitalize(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
599
+ @overload
600
+ def capitalize(a: T_co) -> _StringDTypeOrUnicodeArray: ...
601
+
602
+ @overload
603
+ def center(a: U_co, width: i_co, fillchar: U_co = " ") -> NDArray[str_]: ...
604
+ @overload
605
+ def center(a: S_co, width: i_co, fillchar: str | S_co = " ") -> NDArray[bytes_]: ...
606
+ @overload
607
+ def center(a: _StringDTypeSupportsArray, width: i_co, fillchar: str | _StringDTypeSupportsArray = " ") -> _StringDTypeArray: ...
608
+ @overload
609
+ def center(a: T_co, width: i_co, fillchar: T_co = " ") -> _StringDTypeOrUnicodeArray: ...
610
+
611
+ def decode(
612
+ a: S_co,
613
+ encoding: str | None = None,
614
+ errors: str | None = None,
615
+ ) -> NDArray[str_]: ...
616
+ def encode(
617
+ a: U_co | T_co,
618
+ encoding: str | None = None,
619
+ errors: str | None = None,
620
+ ) -> NDArray[bytes_]: ...
621
+
622
+ @overload
623
+ def expandtabs(a: U_co, tabsize: i_co = 8) -> NDArray[str_]: ...
624
+ @overload
625
+ def expandtabs(a: S_co, tabsize: i_co = 8) -> NDArray[bytes_]: ...
626
+ @overload
627
+ def expandtabs(a: _StringDTypeSupportsArray, tabsize: i_co = 8) -> _StringDTypeArray: ...
628
+ @overload
629
+ def expandtabs(a: T_co, tabsize: i_co = 8) -> _StringDTypeOrUnicodeArray: ...
630
+
631
+ @overload
632
+ def join(sep: U_co, seq: U_co) -> NDArray[str_]: ...
633
+ @overload
634
+ def join(sep: S_co, seq: S_co) -> NDArray[bytes_]: ...
635
+ @overload
636
+ def join(sep: _StringDTypeSupportsArray, seq: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
637
+ @overload
638
+ def join(sep: T_co, seq: T_co) -> _StringDTypeOrUnicodeArray: ...
639
+
640
+ @overload
641
+ def ljust(a: U_co, width: i_co, fillchar: U_co = " ") -> NDArray[str_]: ...
642
+ @overload
643
+ def ljust(a: S_co, width: i_co, fillchar: str | S_co = " ") -> NDArray[bytes_]: ...
644
+ @overload
645
+ def ljust(a: _StringDTypeSupportsArray, width: i_co, fillchar: str | _StringDTypeSupportsArray = " ") -> _StringDTypeArray: ...
646
+ @overload
647
+ def ljust(a: T_co, width: i_co, fillchar: T_co = " ") -> _StringDTypeOrUnicodeArray: ...
648
+
649
+ @overload
650
+ def lower(a: U_co) -> NDArray[str_]: ...
651
+ @overload
652
+ def lower(a: S_co) -> NDArray[bytes_]: ...
653
+ @overload
654
+ def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
655
+ @overload
656
+ def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
657
+
658
+ @overload
659
+ def lstrip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
660
+ @overload
661
+ def lstrip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
662
+ @overload
663
+ def lstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
664
+ @overload
665
+ def lstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
666
+
667
+ @overload
668
+ def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
669
+ @overload
670
+ def partition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
671
+ @overload
672
+ def partition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
673
+ @overload
674
+ def partition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
675
+
676
+ @overload
677
+ def replace(
678
+ a: U_co,
679
+ old: U_co,
680
+ new: U_co,
681
+ count: i_co | None = -1,
682
+ ) -> NDArray[str_]: ...
683
+ @overload
684
+ def replace(
685
+ a: S_co,
686
+ old: S_co,
687
+ new: S_co,
688
+ count: i_co | None = -1,
689
+ ) -> NDArray[bytes_]: ...
690
+ @overload
691
+ def replace(
692
+ a: _StringDTypeSupportsArray,
693
+ old: _StringDTypeSupportsArray,
694
+ new: _StringDTypeSupportsArray,
695
+ count: i_co = -1,
696
+ ) -> _StringDTypeArray: ...
697
+ @overload
698
+ def replace(
699
+ a: T_co,
700
+ old: T_co,
701
+ new: T_co,
702
+ count: i_co = -1,
703
+ ) -> _StringDTypeOrUnicodeArray: ...
704
+
705
+ @overload
706
+ def rjust(
707
+ a: U_co,
708
+ width: i_co,
709
+ fillchar: U_co = " ",
710
+ ) -> NDArray[str_]: ...
711
+ @overload
712
+ def rjust(
713
+ a: S_co,
714
+ width: i_co,
715
+ fillchar: str | S_co = " ",
716
+ ) -> NDArray[bytes_]: ...
717
+ @overload
718
+ def rjust(
719
+ a: _StringDTypeSupportsArray,
720
+ width: i_co,
721
+ fillchar: str | _StringDTypeSupportsArray = " ",
722
+ ) -> _StringDTypeArray: ...
723
+ @overload
724
+ def rjust(
725
+ a: T_co,
726
+ width: i_co,
727
+ fillchar: T_co = " ",
728
+ ) -> _StringDTypeOrUnicodeArray: ...
729
+
730
+ @overload
731
+ def rpartition(a: U_co, sep: U_co) -> NDArray[str_]: ...
732
+ @overload
733
+ def rpartition(a: S_co, sep: S_co) -> NDArray[bytes_]: ...
734
+ @overload
735
+ def rpartition(a: _StringDTypeSupportsArray, sep: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
736
+ @overload
737
+ def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
738
+
739
+ @overload
740
+ def rsplit(
741
+ a: U_co,
742
+ sep: U_co | None = None,
743
+ maxsplit: i_co | None = None,
744
+ ) -> NDArray[object_]: ...
745
+ @overload
746
+ def rsplit(
747
+ a: S_co,
748
+ sep: S_co | None = None,
749
+ maxsplit: i_co | None = None,
750
+ ) -> NDArray[object_]: ...
751
+ @overload
752
+ def rsplit(
753
+ a: _StringDTypeSupportsArray,
754
+ sep: _StringDTypeSupportsArray | None = None,
755
+ maxsplit: i_co | None = None,
756
+ ) -> NDArray[object_]: ...
757
+ @overload
758
+ def rsplit(
759
+ a: T_co,
760
+ sep: T_co | None = None,
761
+ maxsplit: i_co | None = None,
762
+ ) -> NDArray[object_]: ...
763
+
764
+ @overload
765
+ def rstrip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
766
+ @overload
767
+ def rstrip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
768
+ @overload
769
+ def rstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
770
+ @overload
771
+ def rstrip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
772
+
773
+ @overload
774
+ def split(
775
+ a: U_co,
776
+ sep: U_co | None = None,
777
+ maxsplit: i_co | None = None,
778
+ ) -> NDArray[object_]: ...
779
+ @overload
780
+ def split(
781
+ a: S_co,
782
+ sep: S_co | None = None,
783
+ maxsplit: i_co | None = None,
784
+ ) -> NDArray[object_]: ...
785
+ @overload
786
+ def split(
787
+ a: _StringDTypeSupportsArray,
788
+ sep: _StringDTypeSupportsArray | None = None,
789
+ maxsplit: i_co | None = None,
790
+ ) -> NDArray[object_]: ...
791
+ @overload
792
+ def split(
793
+ a: T_co,
794
+ sep: T_co | None = None,
795
+ maxsplit: i_co | None = None,
796
+ ) -> NDArray[object_]: ...
797
+
798
+ def splitlines(a: UST_co, keepends: b_co | None = None) -> NDArray[np.object_]: ...
799
+
800
+ @overload
801
+ def strip(a: U_co, chars: U_co | None = None) -> NDArray[str_]: ...
802
+ @overload
803
+ def strip(a: S_co, chars: S_co | None = None) -> NDArray[bytes_]: ...
804
+ @overload
805
+ def strip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = None) -> _StringDTypeArray: ...
806
+ @overload
807
+ def strip(a: T_co, chars: T_co | None = None) -> _StringDTypeOrUnicodeArray: ...
808
+
809
+ @overload
810
+ def swapcase(a: U_co) -> NDArray[str_]: ...
811
+ @overload
812
+ def swapcase(a: S_co) -> NDArray[bytes_]: ...
813
+ @overload
814
+ def swapcase(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
815
+ @overload
816
+ def swapcase(a: T_co) -> _StringDTypeOrUnicodeArray: ...
817
+
818
+ @overload
819
+ def title(a: U_co) -> NDArray[str_]: ...
820
+ @overload
821
+ def title(a: S_co) -> NDArray[bytes_]: ...
822
+ @overload
823
+ def title(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
824
+ @overload
825
+ def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
826
+
827
+ @overload
828
+ def translate(
829
+ a: U_co,
830
+ table: str,
831
+ deletechars: str | None = None,
832
+ ) -> NDArray[str_]: ...
833
+ @overload
834
+ def translate(
835
+ a: S_co,
836
+ table: str,
837
+ deletechars: str | None = None,
838
+ ) -> NDArray[bytes_]: ...
839
+ @overload
840
+ def translate(
841
+ a: _StringDTypeSupportsArray,
842
+ table: str,
843
+ deletechars: str | None = None,
844
+ ) -> _StringDTypeArray: ...
845
+ @overload
846
+ def translate(
847
+ a: T_co,
848
+ table: str,
849
+ deletechars: str | None = None,
850
+ ) -> _StringDTypeOrUnicodeArray: ...
851
+
852
+ @overload
853
+ def upper(a: U_co) -> NDArray[str_]: ...
854
+ @overload
855
+ def upper(a: S_co) -> NDArray[bytes_]: ...
856
+ @overload
857
+ def upper(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
858
+ @overload
859
+ def upper(a: T_co) -> _StringDTypeOrUnicodeArray: ...
860
+
861
+ @overload
862
+ def zfill(a: U_co, width: i_co) -> NDArray[str_]: ...
863
+ @overload
864
+ def zfill(a: S_co, width: i_co) -> NDArray[bytes_]: ...
865
+ @overload
866
+ def zfill(a: _StringDTypeSupportsArray, width: i_co) -> _StringDTypeArray: ...
867
+ @overload
868
+ def zfill(a: T_co, width: i_co) -> _StringDTypeOrUnicodeArray: ...
869
+
870
+ # String information
871
+ @overload
872
+ def count(
873
+ a: U_co,
874
+ sub: U_co,
875
+ start: i_co = 0,
876
+ end: i_co | None = None,
877
+ ) -> NDArray[int_]: ...
878
+ @overload
879
+ def count(
880
+ a: S_co,
881
+ sub: S_co,
882
+ start: i_co = 0,
883
+ end: i_co | None = None,
884
+ ) -> NDArray[int_]: ...
885
+ @overload
886
+ def count(
887
+ a: T_co,
888
+ sub: T_co,
889
+ start: i_co = 0,
890
+ end: i_co | None = None,
891
+ ) -> NDArray[np.int_]: ...
892
+
893
+ @overload
894
+ def endswith(
895
+ a: U_co,
896
+ suffix: U_co,
897
+ start: i_co = 0,
898
+ end: i_co | None = None,
899
+ ) -> NDArray[np.bool]: ...
900
+ @overload
901
+ def endswith(
902
+ a: S_co,
903
+ suffix: S_co,
904
+ start: i_co = 0,
905
+ end: i_co | None = None,
906
+ ) -> NDArray[np.bool]: ...
907
+ @overload
908
+ def endswith(
909
+ a: T_co,
910
+ suffix: T_co,
911
+ start: i_co = 0,
912
+ end: i_co | None = None,
913
+ ) -> NDArray[np.bool]: ...
914
+
915
+ @overload
916
+ def find(
917
+ a: U_co,
918
+ sub: U_co,
919
+ start: i_co = 0,
920
+ end: i_co | None = None,
921
+ ) -> NDArray[int_]: ...
922
+ @overload
923
+ def find(
924
+ a: S_co,
925
+ sub: S_co,
926
+ start: i_co = 0,
927
+ end: i_co | None = None,
928
+ ) -> NDArray[int_]: ...
929
+ @overload
930
+ def find(
931
+ a: T_co,
932
+ sub: T_co,
933
+ start: i_co = 0,
934
+ end: i_co | None = None,
935
+ ) -> NDArray[np.int_]: ...
936
+
937
+ @overload
938
+ def index(
939
+ a: U_co,
940
+ sub: U_co,
941
+ start: i_co = 0,
942
+ end: i_co | None = None,
943
+ ) -> NDArray[int_]: ...
944
+ @overload
945
+ def index(
946
+ a: S_co,
947
+ sub: S_co,
948
+ start: i_co = 0,
949
+ end: i_co | None = None,
950
+ ) -> NDArray[int_]: ...
951
+ @overload
952
+ def index(
953
+ a: T_co,
954
+ sub: T_co,
955
+ start: i_co = 0,
956
+ end: i_co | None = None,
957
+ ) -> NDArray[np.int_]: ...
958
+
959
+ def isalpha(a: UST_co) -> NDArray[np.bool]: ...
960
+ def isalnum(a: UST_co) -> NDArray[np.bool]: ...
961
+ def isdecimal(a: U_co | T_co) -> NDArray[np.bool]: ...
962
+ def isdigit(a: UST_co) -> NDArray[np.bool]: ...
963
+ def islower(a: UST_co) -> NDArray[np.bool]: ...
964
+ def isnumeric(a: U_co | T_co) -> NDArray[np.bool]: ...
965
+ def isspace(a: UST_co) -> NDArray[np.bool]: ...
966
+ def istitle(a: UST_co) -> NDArray[np.bool]: ...
967
+ def isupper(a: UST_co) -> NDArray[np.bool]: ...
968
+
969
+ @overload
970
+ def rfind(
971
+ a: U_co,
972
+ sub: U_co,
973
+ start: i_co = 0,
974
+ end: i_co | None = None,
975
+ ) -> NDArray[int_]: ...
976
+ @overload
977
+ def rfind(
978
+ a: S_co,
979
+ sub: S_co,
980
+ start: i_co = 0,
981
+ end: i_co | None = None,
982
+ ) -> NDArray[int_]: ...
983
+ @overload
984
+ def rfind(
985
+ a: T_co,
986
+ sub: T_co,
987
+ start: i_co = 0,
988
+ end: i_co | None = None,
989
+ ) -> NDArray[np.int_]: ...
990
+
991
+ @overload
992
+ def rindex(
993
+ a: U_co,
994
+ sub: U_co,
995
+ start: i_co = 0,
996
+ end: i_co | None = None,
997
+ ) -> NDArray[int_]: ...
998
+ @overload
999
+ def rindex(
1000
+ a: S_co,
1001
+ sub: S_co,
1002
+ start: i_co = 0,
1003
+ end: i_co | None = None,
1004
+ ) -> NDArray[int_]: ...
1005
+ @overload
1006
+ def rindex(
1007
+ a: T_co,
1008
+ sub: T_co,
1009
+ start: i_co = 0,
1010
+ end: i_co | None = None,
1011
+ ) -> NDArray[np.int_]: ...
1012
+
1013
+ @overload
1014
+ def startswith(
1015
+ a: U_co,
1016
+ prefix: U_co,
1017
+ start: i_co = 0,
1018
+ end: i_co | None = None,
1019
+ ) -> NDArray[np.bool]: ...
1020
+ @overload
1021
+ def startswith(
1022
+ a: S_co,
1023
+ prefix: S_co,
1024
+ start: i_co = 0,
1025
+ end: i_co | None = None,
1026
+ ) -> NDArray[np.bool]: ...
1027
+ @overload
1028
+ def startswith(
1029
+ a: T_co,
1030
+ prefix: T_co,
1031
+ start: i_co = 0,
1032
+ end: i_co | None = None,
1033
+ ) -> NDArray[np.bool]: ...
1034
+
1035
+ def str_len(A: UST_co) -> NDArray[int_]: ...
1036
+
1037
+ # Overload 1 and 2: str- or bytes-based array-likes
1038
+ # overload 3 and 4: arbitrary object with unicode=False (-> bytes_)
1039
+ # overload 5 and 6: arbitrary object with unicode=True (-> str_)
1040
+ # overload 7: arbitrary object with unicode=None (default) (-> str_ | bytes_)
1041
+ @overload
1042
+ def array(
1043
+ obj: U_co,
1044
+ itemsize: int | None = None,
1045
+ copy: bool = True,
1046
+ unicode: L[True] | None = None,
1047
+ order: _OrderKACF = None,
1048
+ ) -> _CharArray[str_]: ...
1049
+ @overload
1050
+ def array(
1051
+ obj: S_co,
1052
+ itemsize: int | None = None,
1053
+ copy: bool = True,
1054
+ unicode: L[False] | None = None,
1055
+ order: _OrderKACF = None,
1056
+ ) -> _CharArray[bytes_]: ...
1057
+ @overload
1058
+ def array(
1059
+ obj: object,
1060
+ itemsize: int | None,
1061
+ copy: bool,
1062
+ unicode: L[False],
1063
+ order: _OrderKACF = None,
1064
+ ) -> _CharArray[bytes_]: ...
1065
+ @overload
1066
+ def array(
1067
+ obj: object,
1068
+ itemsize: int | None = None,
1069
+ copy: bool = True,
1070
+ *,
1071
+ unicode: L[False],
1072
+ order: _OrderKACF = None,
1073
+ ) -> _CharArray[bytes_]: ...
1074
+ @overload
1075
+ def array(
1076
+ obj: object,
1077
+ itemsize: int | None,
1078
+ copy: bool,
1079
+ unicode: L[True],
1080
+ order: _OrderKACF = None,
1081
+ ) -> _CharArray[str_]: ...
1082
+ @overload
1083
+ def array(
1084
+ obj: object,
1085
+ itemsize: int | None = None,
1086
+ copy: bool = True,
1087
+ *,
1088
+ unicode: L[True],
1089
+ order: _OrderKACF = None,
1090
+ ) -> _CharArray[str_]: ...
1091
+ @overload
1092
+ def array(
1093
+ obj: object,
1094
+ itemsize: int | None = None,
1095
+ copy: bool = True,
1096
+ unicode: bool | None = None,
1097
+ order: _OrderKACF = None,
1098
+ ) -> _CharArray[str_] | _CharArray[bytes_]: ...
1099
+
1100
+ @overload
1101
+ def asarray(
1102
+ obj: U_co,
1103
+ itemsize: int | None = None,
1104
+ unicode: L[True] | None = None,
1105
+ order: _OrderKACF = None,
1106
+ ) -> _CharArray[str_]: ...
1107
+ @overload
1108
+ def asarray(
1109
+ obj: S_co,
1110
+ itemsize: int | None = None,
1111
+ unicode: L[False] | None = None,
1112
+ order: _OrderKACF = None,
1113
+ ) -> _CharArray[bytes_]: ...
1114
+ @overload
1115
+ def asarray(
1116
+ obj: object,
1117
+ itemsize: int | None,
1118
+ unicode: L[False],
1119
+ order: _OrderKACF = None,
1120
+ ) -> _CharArray[bytes_]: ...
1121
+ @overload
1122
+ def asarray(
1123
+ obj: object,
1124
+ itemsize: int | None = None,
1125
+ *,
1126
+ unicode: L[False],
1127
+ order: _OrderKACF = None,
1128
+ ) -> _CharArray[bytes_]: ...
1129
+ @overload
1130
+ def asarray(
1131
+ obj: object,
1132
+ itemsize: int | None,
1133
+ unicode: L[True],
1134
+ order: _OrderKACF = None,
1135
+ ) -> _CharArray[str_]: ...
1136
+ @overload
1137
+ def asarray(
1138
+ obj: object,
1139
+ itemsize: int | None = None,
1140
+ *,
1141
+ unicode: L[True],
1142
+ order: _OrderKACF = None,
1143
+ ) -> _CharArray[str_]: ...
1144
+ @overload
1145
+ def asarray(
1146
+ obj: object,
1147
+ itemsize: int | None = None,
1148
+ unicode: bool | None = None,
1149
+ order: _OrderKACF = None,
1150
+ ) -> _CharArray[str_] | _CharArray[bytes_]: ...
python/user_packages/Python313/site-packages/numpy/_core/einsumfunc.py ADDED
@@ -0,0 +1,1650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of optimized einsum.
3
+
4
+ """
5
+ import functools
6
+ import itertools
7
+ import operator
8
+
9
+ from numpy._core.multiarray import c_einsum, matmul
10
+ from numpy._core.numeric import asanyarray, reshape
11
+ from numpy._core.overrides import array_function_dispatch
12
+ from numpy._core.umath import multiply
13
+
14
+ __all__ = ['einsum', 'einsum_path']
15
+
16
+ # importing string for string.ascii_letters would be too slow
17
+ # the first import before caching has been measured to take 800 µs (#23777)
18
+ # imports begin with uppercase to mimic ASCII values to avoid sorting issues
19
+ einsum_symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
20
+ einsum_symbols_set = set(einsum_symbols)
21
+
22
+
23
+ def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
24
+ """
25
+ Computes the number of FLOPS in the contraction.
26
+
27
+ Parameters
28
+ ----------
29
+ idx_contraction : iterable
30
+ The indices involved in the contraction
31
+ inner : bool
32
+ Does this contraction require an inner product?
33
+ num_terms : int
34
+ The number of terms in a contraction
35
+ size_dictionary : dict
36
+ The size of each of the indices in idx_contraction
37
+
38
+ Returns
39
+ -------
40
+ flop_count : int
41
+ The total number of FLOPS required for the contraction.
42
+
43
+ Examples
44
+ --------
45
+
46
+ >>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
47
+ 30
48
+
49
+ >>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
50
+ 60
51
+
52
+ """
53
+
54
+ overall_size = _compute_size_by_dict(idx_contraction, size_dictionary)
55
+ op_factor = max(1, num_terms - 1)
56
+ if inner:
57
+ op_factor += 1
58
+
59
+ return overall_size * op_factor
60
+
61
+ def _compute_size_by_dict(indices, idx_dict):
62
+ """
63
+ Computes the product of the elements in indices based on the dictionary
64
+ idx_dict.
65
+
66
+ Parameters
67
+ ----------
68
+ indices : iterable
69
+ Indices to base the product on.
70
+ idx_dict : dictionary
71
+ Dictionary of index sizes
72
+
73
+ Returns
74
+ -------
75
+ ret : int
76
+ The resulting product.
77
+
78
+ Examples
79
+ --------
80
+ >>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
81
+ 90
82
+
83
+ """
84
+ ret = 1
85
+ for i in indices:
86
+ ret *= idx_dict[i]
87
+ return ret
88
+
89
+
90
+ def _find_contraction(positions, input_sets, output_set):
91
+ """
92
+ Finds the contraction for a given set of input and output sets.
93
+
94
+ Parameters
95
+ ----------
96
+ positions : iterable
97
+ Integer positions of terms used in the contraction.
98
+ input_sets : list
99
+ List of sets that represent the lhs side of the einsum subscript
100
+ output_set : set
101
+ Set that represents the rhs side of the overall einsum subscript
102
+
103
+ Returns
104
+ -------
105
+ new_result : set
106
+ The indices of the resulting contraction
107
+ remaining : list
108
+ List of sets that have not been contracted, the new set is appended to
109
+ the end of this list
110
+ idx_removed : set
111
+ Indices removed from the entire contraction
112
+ idx_contraction : set
113
+ The indices used in the current contraction
114
+
115
+ Examples
116
+ --------
117
+
118
+ # A simple dot product test case
119
+ >>> pos = (0, 1)
120
+ >>> isets = [set('ab'), set('bc')]
121
+ >>> oset = set('ac')
122
+ >>> _find_contraction(pos, isets, oset)
123
+ ({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})
124
+
125
+ # A more complex case with additional terms in the contraction
126
+ >>> pos = (0, 2)
127
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
128
+ >>> oset = set('ac')
129
+ >>> _find_contraction(pos, isets, oset)
130
+ ({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
131
+ """
132
+
133
+ idx_contract = set()
134
+ idx_remain = output_set.copy()
135
+ remaining = []
136
+ for ind, value in enumerate(input_sets):
137
+ if ind in positions:
138
+ idx_contract |= value
139
+ else:
140
+ remaining.append(value)
141
+ idx_remain |= value
142
+
143
+ new_result = idx_remain & idx_contract
144
+ idx_removed = (idx_contract - new_result)
145
+ remaining.append(new_result)
146
+
147
+ return (new_result, remaining, idx_removed, idx_contract)
148
+
149
+
150
+ def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
151
+ """
152
+ Computes all possible pair contractions, sieves the results based
153
+ on ``memory_limit`` and returns the lowest cost path. This algorithm
154
+ scales factorial with respect to the elements in the list ``input_sets``.
155
+
156
+ Parameters
157
+ ----------
158
+ input_sets : list
159
+ List of sets that represent the lhs side of the einsum subscript
160
+ output_set : set
161
+ Set that represents the rhs side of the overall einsum subscript
162
+ idx_dict : dictionary
163
+ Dictionary of index sizes
164
+ memory_limit : int
165
+ The maximum number of elements in a temporary array
166
+
167
+ Returns
168
+ -------
169
+ path : list
170
+ The optimal contraction order within the memory limit constraint.
171
+
172
+ Examples
173
+ --------
174
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
175
+ >>> oset = set()
176
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
177
+ >>> _optimal_path(isets, oset, idx_sizes, 5000)
178
+ [(0, 2), (0, 1)]
179
+ """
180
+
181
+ full_results = [(0, [], input_sets)]
182
+ for iteration in range(len(input_sets) - 1):
183
+ iter_results = []
184
+
185
+ # Compute all unique pairs
186
+ for curr in full_results:
187
+ cost, positions, remaining = curr
188
+ for con in itertools.combinations(
189
+ range(len(input_sets) - iteration), 2
190
+ ):
191
+
192
+ # Find the contraction
193
+ cont = _find_contraction(con, remaining, output_set)
194
+ new_result, new_input_sets, idx_removed, idx_contract = cont
195
+
196
+ # Sieve the results based on memory_limit
197
+ new_size = _compute_size_by_dict(new_result, idx_dict)
198
+ if new_size > memory_limit:
199
+ continue
200
+
201
+ # Build (total_cost, positions, indices_remaining)
202
+ total_cost = cost + _flop_count(
203
+ idx_contract, idx_removed, len(con), idx_dict
204
+ )
205
+ new_pos = positions + [con]
206
+ iter_results.append((total_cost, new_pos, new_input_sets))
207
+
208
+ # Update combinatorial list, if we did not find anything return best
209
+ # path + remaining contractions
210
+ if iter_results:
211
+ full_results = iter_results
212
+ else:
213
+ path = min(full_results, key=lambda x: x[0])[1]
214
+ path += [tuple(range(len(input_sets) - iteration))]
215
+ return path
216
+
217
+ # If we have not found anything return single einsum contraction
218
+ if len(full_results) == 0:
219
+ return [tuple(range(len(input_sets)))]
220
+
221
+ path = min(full_results, key=lambda x: x[0])[1]
222
+ return path
223
+
224
+ def _parse_possible_contraction(
225
+ positions, input_sets, output_set, idx_dict,
226
+ memory_limit, path_cost, naive_cost
227
+ ):
228
+ """Compute the cost (removed size + flops) and resultant indices for
229
+ performing the contraction specified by ``positions``.
230
+
231
+ Parameters
232
+ ----------
233
+ positions : tuple of int
234
+ The locations of the proposed tensors to contract.
235
+ input_sets : list of sets
236
+ The indices found on each tensors.
237
+ output_set : set
238
+ The output indices of the expression.
239
+ idx_dict : dict
240
+ Mapping of each index to its size.
241
+ memory_limit : int
242
+ The total allowed size for an intermediary tensor.
243
+ path_cost : int
244
+ The contraction cost so far.
245
+ naive_cost : int
246
+ The cost of the unoptimized expression.
247
+
248
+ Returns
249
+ -------
250
+ cost : (int, int)
251
+ A tuple containing the size of any indices removed, and the flop cost.
252
+ positions : tuple of int
253
+ The locations of the proposed tensors to contract.
254
+ new_input_sets : list of sets
255
+ The resulting new list of indices if this proposed contraction
256
+ is performed.
257
+
258
+ """
259
+
260
+ # Find the contraction
261
+ contract = _find_contraction(positions, input_sets, output_set)
262
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
263
+
264
+ # Sieve the results based on memory_limit
265
+ new_size = _compute_size_by_dict(idx_result, idx_dict)
266
+ if new_size > memory_limit:
267
+ return None
268
+
269
+ # Build sort tuple
270
+ old_sizes = (
271
+ _compute_size_by_dict(input_sets[p], idx_dict) for p in positions
272
+ )
273
+ removed_size = sum(old_sizes) - new_size
274
+
275
+ # NB: removed_size used to be just the size of any removed indices i.e.:
276
+ # helpers.compute_size_by_dict(idx_removed, idx_dict)
277
+ cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict)
278
+ sort = (-removed_size, cost)
279
+
280
+ # Sieve based on total cost as well
281
+ if (path_cost + cost) > naive_cost:
282
+ return None
283
+
284
+ # Add contraction to possible choices
285
+ return [sort, positions, new_input_sets]
286
+
287
+
288
+ def _update_other_results(results, best):
289
+ """Update the positions and provisional input_sets of ``results``
290
+ based on performing the contraction result ``best``. Remove any
291
+ involving the tensors contracted.
292
+
293
+ Parameters
294
+ ----------
295
+ results : list
296
+ List of contraction results produced by
297
+ ``_parse_possible_contraction``.
298
+ best : list
299
+ The best contraction of ``results`` i.e. the one that
300
+ will be performed.
301
+
302
+ Returns
303
+ -------
304
+ mod_results : list
305
+ The list of modified results, updated with outcome of
306
+ ``best`` contraction.
307
+ """
308
+
309
+ best_con = best[1]
310
+ bx, by = best_con
311
+ mod_results = []
312
+
313
+ for cost, (x, y), con_sets in results:
314
+
315
+ # Ignore results involving tensors just contracted
316
+ if x in best_con or y in best_con:
317
+ continue
318
+
319
+ # Update the input_sets
320
+ del con_sets[by - int(by > x) - int(by > y)]
321
+ del con_sets[bx - int(bx > x) - int(bx > y)]
322
+ con_sets.insert(-1, best[2][-1])
323
+
324
+ # Update the position indices
325
+ mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)
326
+ mod_results.append((cost, mod_con, con_sets))
327
+
328
+ return mod_results
329
+
330
+ def _greedy_path(input_sets, output_set, idx_dict, memory_limit):
331
+ """
332
+ Finds the path by contracting the best pair until the input list is
333
+ exhausted. The best pair is found by minimizing the tuple
334
+ ``(-prod(indices_removed), cost)``. What this amounts to is prioritizing
335
+ matrix multiplication or inner product operations, then Hadamard like
336
+ operations, and finally outer operations. Outer products are limited by
337
+ ``memory_limit``. This algorithm scales cubically with respect to the
338
+ number of elements in the list ``input_sets``.
339
+
340
+ Parameters
341
+ ----------
342
+ input_sets : list
343
+ List of sets that represent the lhs side of the einsum subscript
344
+ output_set : set
345
+ Set that represents the rhs side of the overall einsum subscript
346
+ idx_dict : dictionary
347
+ Dictionary of index sizes
348
+ memory_limit : int
349
+ The maximum number of elements in a temporary array
350
+
351
+ Returns
352
+ -------
353
+ path : list
354
+ The greedy contraction order within the memory limit constraint.
355
+
356
+ Examples
357
+ --------
358
+ >>> isets = [set('abd'), set('ac'), set('bdc')]
359
+ >>> oset = set()
360
+ >>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
361
+ >>> _greedy_path(isets, oset, idx_sizes, 5000)
362
+ [(0, 2), (0, 1)]
363
+ """
364
+
365
+ # Handle trivial cases that leaked through
366
+ if len(input_sets) == 1:
367
+ return [(0,)]
368
+ elif len(input_sets) == 2:
369
+ return [(0, 1)]
370
+
371
+ # Build up a naive cost
372
+ contract = _find_contraction(
373
+ range(len(input_sets)), input_sets, output_set
374
+ )
375
+ idx_result, new_input_sets, idx_removed, idx_contract = contract
376
+ naive_cost = _flop_count(
377
+ idx_contract, idx_removed, len(input_sets), idx_dict
378
+ )
379
+
380
+ # Initially iterate over all pairs
381
+ comb_iter = itertools.combinations(range(len(input_sets)), 2)
382
+ known_contractions = []
383
+
384
+ path_cost = 0
385
+ path = []
386
+
387
+ for iteration in range(len(input_sets) - 1):
388
+
389
+ # Iterate over all pairs on the first step, only previously
390
+ # found pairs on subsequent steps
391
+ for positions in comb_iter:
392
+
393
+ # Always initially ignore outer products
394
+ if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):
395
+ continue
396
+
397
+ result = _parse_possible_contraction(
398
+ positions, input_sets, output_set, idx_dict,
399
+ memory_limit, path_cost, naive_cost
400
+ )
401
+ if result is not None:
402
+ known_contractions.append(result)
403
+
404
+ # If we do not have a inner contraction, rescan pairs
405
+ # including outer products
406
+ if len(known_contractions) == 0:
407
+
408
+ # Then check the outer products
409
+ for positions in itertools.combinations(
410
+ range(len(input_sets)), 2
411
+ ):
412
+ result = _parse_possible_contraction(
413
+ positions, input_sets, output_set, idx_dict,
414
+ memory_limit, path_cost, naive_cost
415
+ )
416
+ if result is not None:
417
+ known_contractions.append(result)
418
+
419
+ # If we still did not find any remaining contractions,
420
+ # default back to einsum like behavior
421
+ if len(known_contractions) == 0:
422
+ path.append(tuple(range(len(input_sets))))
423
+ break
424
+
425
+ # Sort based on first index
426
+ best = min(known_contractions, key=lambda x: x[0])
427
+
428
+ # Now propagate as many unused contractions as possible
429
+ # to the next iteration
430
+ known_contractions = _update_other_results(known_contractions, best)
431
+
432
+ # Next iteration only compute contractions with the new tensor
433
+ # All other contractions have been accounted for
434
+ input_sets = best[2]
435
+ new_tensor_pos = len(input_sets) - 1
436
+ comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos))
437
+
438
+ # Update path and total cost
439
+ path.append(best[1])
440
+ path_cost += best[0][1]
441
+
442
+ return path
443
+
444
+
445
+ def _parse_einsum_input(operands):
446
+ """
447
+ A reproduction of einsum c side einsum parsing in python.
448
+
449
+ Returns
450
+ -------
451
+ input_strings : str
452
+ Parsed input strings
453
+ output_string : str
454
+ Parsed output string
455
+ operands : list of array_like
456
+ The operands to use in the numpy contraction
457
+
458
+ Examples
459
+ --------
460
+ The operand list is simplified to reduce printing:
461
+
462
+ >>> np.random.seed(123)
463
+ >>> a = np.random.rand(4, 4)
464
+ >>> b = np.random.rand(4, 4, 4)
465
+ >>> _parse_einsum_input(('...a,...a->...', a, b))
466
+ ('za,xza', 'xz', [a, b]) # may vary
467
+
468
+ >>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
469
+ ('za,xza', 'xz', [a, b]) # may vary
470
+ """
471
+
472
+ if len(operands) == 0:
473
+ raise ValueError("No input operands")
474
+
475
+ if isinstance(operands[0], str):
476
+ subscripts = operands[0].replace(" ", "")
477
+ operands = [asanyarray(v) for v in operands[1:]]
478
+
479
+ # Ensure all characters are valid
480
+ for s in subscripts:
481
+ if s in '.,->':
482
+ continue
483
+ if s not in einsum_symbols:
484
+ raise ValueError(f"Character {s} is not a valid symbol.")
485
+
486
+ else:
487
+ tmp_operands = list(operands)
488
+ operand_list = []
489
+ subscript_list = []
490
+ for p in range(len(operands) // 2):
491
+ operand_list.append(tmp_operands.pop(0))
492
+ subscript_list.append(tmp_operands.pop(0))
493
+
494
+ output_list = tmp_operands[-1] if len(tmp_operands) else None
495
+ operands = [asanyarray(v) for v in operand_list]
496
+ subscripts = ""
497
+ last = len(subscript_list) - 1
498
+ for num, sub in enumerate(subscript_list):
499
+ for s in sub:
500
+ if s is Ellipsis:
501
+ subscripts += "..."
502
+ else:
503
+ try:
504
+ s = operator.index(s)
505
+ except TypeError as e:
506
+ raise TypeError(
507
+ "For this input type lists must contain "
508
+ "either int or Ellipsis"
509
+ ) from e
510
+ subscripts += einsum_symbols[s]
511
+ if num != last:
512
+ subscripts += ","
513
+
514
+ if output_list is not None:
515
+ subscripts += "->"
516
+ for s in output_list:
517
+ if s is Ellipsis:
518
+ subscripts += "..."
519
+ else:
520
+ try:
521
+ s = operator.index(s)
522
+ except TypeError as e:
523
+ raise TypeError(
524
+ "For this input type lists must contain "
525
+ "either int or Ellipsis"
526
+ ) from e
527
+ subscripts += einsum_symbols[s]
528
+ # Check for proper "->"
529
+ if ("-" in subscripts) or (">" in subscripts):
530
+ invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
531
+ if invalid or (subscripts.count("->") != 1):
532
+ raise ValueError("Subscripts can only contain one '->'.")
533
+
534
+ # Parse ellipses
535
+ if "." in subscripts:
536
+ used = subscripts.replace(".", "").replace(",", "").replace("->", "")
537
+ unused = list(einsum_symbols_set - set(used))
538
+ ellipse_inds = "".join(unused)
539
+ longest = 0
540
+
541
+ if "->" in subscripts:
542
+ input_tmp, output_sub = subscripts.split("->")
543
+ split_subscripts = input_tmp.split(",")
544
+ out_sub = True
545
+ else:
546
+ split_subscripts = subscripts.split(',')
547
+ out_sub = False
548
+
549
+ for num, sub in enumerate(split_subscripts):
550
+ if "." in sub:
551
+ if (sub.count(".") != 3) or (sub.count("...") != 1):
552
+ raise ValueError("Invalid Ellipses.")
553
+
554
+ # Take into account numerical values
555
+ if operands[num].shape == ():
556
+ ellipse_count = 0
557
+ else:
558
+ ellipse_count = max(operands[num].ndim, 1)
559
+ ellipse_count -= (len(sub) - 3)
560
+
561
+ if ellipse_count > longest:
562
+ longest = ellipse_count
563
+
564
+ if ellipse_count < 0:
565
+ raise ValueError("Ellipses lengths do not match.")
566
+ elif ellipse_count == 0:
567
+ split_subscripts[num] = sub.replace('...', '')
568
+ else:
569
+ rep_inds = ellipse_inds[-ellipse_count:]
570
+ split_subscripts[num] = sub.replace('...', rep_inds)
571
+
572
+ subscripts = ",".join(split_subscripts)
573
+ if longest == 0:
574
+ out_ellipse = ""
575
+ else:
576
+ out_ellipse = ellipse_inds[-longest:]
577
+
578
+ if out_sub:
579
+ subscripts += "->" + output_sub.replace("...", out_ellipse)
580
+ else:
581
+ # Special care for outputless ellipses
582
+ output_subscript = ""
583
+ tmp_subscripts = subscripts.replace(",", "")
584
+ for s in sorted(set(tmp_subscripts)):
585
+ if s not in (einsum_symbols):
586
+ raise ValueError(f"Character {s} is not a valid symbol.")
587
+ if tmp_subscripts.count(s) == 1:
588
+ output_subscript += s
589
+ normal_inds = ''.join(sorted(set(output_subscript) -
590
+ set(out_ellipse)))
591
+
592
+ subscripts += "->" + out_ellipse + normal_inds
593
+
594
+ # Build output string if does not exist
595
+ if "->" in subscripts:
596
+ input_subscripts, output_subscript = subscripts.split("->")
597
+ else:
598
+ input_subscripts = subscripts
599
+ # Build output subscripts
600
+ tmp_subscripts = subscripts.replace(",", "")
601
+ output_subscript = ""
602
+ for s in sorted(set(tmp_subscripts)):
603
+ if s not in einsum_symbols:
604
+ raise ValueError(f"Character {s} is not a valid symbol.")
605
+ if tmp_subscripts.count(s) == 1:
606
+ output_subscript += s
607
+
608
+ # Make sure output subscripts are in the input
609
+ for char in output_subscript:
610
+ if output_subscript.count(char) != 1:
611
+ raise ValueError("Output character %s appeared more than once in "
612
+ "the output." % char)
613
+ if char not in input_subscripts:
614
+ raise ValueError(f"Output character {char} did not appear in the input")
615
+
616
+ # Make sure number operands is equivalent to the number of terms
617
+ if len(input_subscripts.split(',')) != len(operands):
618
+ raise ValueError("Number of einsum subscripts must be equal to the "
619
+ "number of operands.")
620
+
621
+ return (input_subscripts, output_subscript, operands)
622
+
623
+
624
+ def _einsum_path_dispatcher(*operands, optimize=None, einsum_call=None):
625
+ # NOTE: technically, we should only dispatch on array-like arguments, not
626
+ # subscripts (given as strings). But separating operands into
627
+ # arrays/subscripts is a little tricky/slow (given einsum's two supported
628
+ # signatures), so as a practical shortcut we dispatch on everything.
629
+ # Strings will be ignored for dispatching since they don't define
630
+ # __array_function__.
631
+ return operands
632
+
633
+
634
+ @array_function_dispatch(_einsum_path_dispatcher, module='numpy')
635
+ def einsum_path(*operands, optimize='greedy', einsum_call=False):
636
+ """
637
+ einsum_path(subscripts, *operands, optimize='greedy')
638
+
639
+ Evaluates the lowest cost contraction order for an einsum expression by
640
+ considering the creation of intermediate arrays.
641
+
642
+ Parameters
643
+ ----------
644
+ subscripts : str
645
+ Specifies the subscripts for summation.
646
+ *operands : list of array_like
647
+ These are the arrays for the operation.
648
+ optimize : {bool, list, tuple, 'greedy', 'optimal'}
649
+ Choose the type of path. If a tuple is provided, the second argument is
650
+ assumed to be the maximum intermediate size created. If only a single
651
+ argument is provided the largest input or output array size is used
652
+ as a maximum intermediate size.
653
+
654
+ * if a list is given that starts with ``einsum_path``, uses this as the
655
+ contraction path
656
+ * if False no optimization is taken
657
+ * if True defaults to the 'greedy' algorithm
658
+ * 'optimal' An algorithm that combinatorially explores all possible
659
+ ways of contracting the listed tensors and chooses the least costly
660
+ path. Scales exponentially with the number of terms in the
661
+ contraction.
662
+ * 'greedy' An algorithm that chooses the best pair contraction
663
+ at each step. Effectively, this algorithm searches the largest inner,
664
+ Hadamard, and then outer products at each step. Scales cubically with
665
+ the number of terms in the contraction. Equivalent to the 'optimal'
666
+ path for most contractions.
667
+
668
+ Default is 'greedy'.
669
+
670
+ Returns
671
+ -------
672
+ path : list of tuples
673
+ A list representation of the einsum path.
674
+ string_repr : str
675
+ A printable representation of the einsum path.
676
+
677
+ Notes
678
+ -----
679
+ The resulting path indicates which terms of the input contraction should be
680
+ contracted first, the result of this contraction is then appended to the
681
+ end of the contraction list. This list can then be iterated over until all
682
+ intermediate contractions are complete.
683
+
684
+ See Also
685
+ --------
686
+ einsum, linalg.multi_dot
687
+
688
+ Examples
689
+ --------
690
+
691
+ We can begin with a chain dot example. In this case, it is optimal to
692
+ contract the ``b`` and ``c`` tensors first as represented by the first
693
+ element of the path ``(1, 2)``. The resulting tensor is added to the end
694
+ of the contraction and the remaining contraction ``(0, 1)`` is then
695
+ completed.
696
+
697
+ >>> np.random.seed(123)
698
+ >>> a = np.random.rand(2, 2)
699
+ >>> b = np.random.rand(2, 5)
700
+ >>> c = np.random.rand(5, 2)
701
+ >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
702
+ >>> print(path_info[0])
703
+ ['einsum_path', (1, 2), (0, 1)]
704
+ >>> print(path_info[1])
705
+ Complete contraction: ij,jk,kl->il # may vary
706
+ Naive scaling: 4
707
+ Optimized scaling: 3
708
+ Naive FLOP count: 1.600e+02
709
+ Optimized FLOP count: 5.600e+01
710
+ Theoretical speedup: 2.857
711
+ Largest intermediate: 4.000e+00 elements
712
+ -------------------------------------------------------------------------
713
+ scaling current remaining
714
+ -------------------------------------------------------------------------
715
+ 3 kl,jk->jl ij,jl->il
716
+ 3 jl,ij->il il->il
717
+
718
+
719
+ A more complex index transformation example.
720
+
721
+ >>> I = np.random.rand(10, 10, 10, 10)
722
+ >>> C = np.random.rand(10, 10)
723
+ >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
724
+ ... optimize='greedy')
725
+
726
+ >>> print(path_info[0])
727
+ ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
728
+ >>> print(path_info[1])
729
+ Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
730
+ Naive scaling: 8
731
+ Optimized scaling: 5
732
+ Naive FLOP count: 8.000e+08
733
+ Optimized FLOP count: 8.000e+05
734
+ Theoretical speedup: 1000.000
735
+ Largest intermediate: 1.000e+04 elements
736
+ --------------------------------------------------------------------------
737
+ scaling current remaining
738
+ --------------------------------------------------------------------------
739
+ 5 abcd,ea->bcde fb,gc,hd,bcde->efgh
740
+ 5 bcde,fb->cdef gc,hd,cdef->efgh
741
+ 5 cdef,gc->defg hd,defg->efgh
742
+ 5 defg,hd->efgh efgh->efgh
743
+ """
744
+
745
+ # Figure out what the path really is
746
+ path_type = optimize
747
+ if path_type is True:
748
+ path_type = 'greedy'
749
+ if path_type is None:
750
+ path_type = False
751
+
752
+ explicit_einsum_path = False
753
+ memory_limit = None
754
+
755
+ # No optimization or a named path algorithm
756
+ if (path_type is False) or isinstance(path_type, str):
757
+ pass
758
+
759
+ # Given an explicit path
760
+ elif len(path_type) and (path_type[0] == 'einsum_path'):
761
+ explicit_einsum_path = True
762
+
763
+ # Path tuple with memory limit
764
+ elif ((len(path_type) == 2) and isinstance(path_type[0], str) and
765
+ isinstance(path_type[1], (int, float))):
766
+ memory_limit = int(path_type[1])
767
+ path_type = path_type[0]
768
+
769
+ else:
770
+ raise TypeError(f"Did not understand the path: {str(path_type)}")
771
+
772
+ # Hidden option, only einsum should call this
773
+ einsum_call_arg = einsum_call
774
+
775
+ # Python side parsing
776
+ input_subscripts, output_subscript, operands = (
777
+ _parse_einsum_input(operands)
778
+ )
779
+
780
+ # Build a few useful list and sets
781
+ input_list = input_subscripts.split(',')
782
+ num_inputs = len(input_list)
783
+ input_sets = [set(x) for x in input_list]
784
+ output_set = set(output_subscript)
785
+ indices = set(input_subscripts.replace(',', ''))
786
+ num_indices = len(indices)
787
+
788
+ # Get length of each unique dimension and ensure all dimensions are correct
789
+ dimension_dict = {}
790
+ for tnum, term in enumerate(input_list):
791
+ sh = operands[tnum].shape
792
+ if len(sh) != len(term):
793
+ raise ValueError("Einstein sum subscript %s does not contain the "
794
+ "correct number of indices for operand %d."
795
+ % (input_subscripts[tnum], tnum))
796
+ for cnum, char in enumerate(term):
797
+ dim = sh[cnum]
798
+
799
+ if char in dimension_dict.keys():
800
+ # For broadcasting cases we always want the largest dim size
801
+ if dimension_dict[char] == 1:
802
+ dimension_dict[char] = dim
803
+ elif dim not in (1, dimension_dict[char]):
804
+ raise ValueError("Size of label '%s' for operand %d (%d) "
805
+ "does not match previous terms (%d)."
806
+ % (char, tnum, dimension_dict[char], dim))
807
+ else:
808
+ dimension_dict[char] = dim
809
+
810
+ # Compute size of each input array plus the output array
811
+ size_list = [_compute_size_by_dict(term, dimension_dict)
812
+ for term in input_list + [output_subscript]]
813
+ max_size = max(size_list)
814
+
815
+ if memory_limit is None:
816
+ memory_arg = max_size
817
+ else:
818
+ memory_arg = memory_limit
819
+
820
+ # Compute the path
821
+ if explicit_einsum_path:
822
+ path = path_type[1:]
823
+ elif (
824
+ (path_type is False)
825
+ or (num_inputs in [1, 2])
826
+ or (indices == output_set)
827
+ ):
828
+ # Nothing to be optimized, leave it to einsum
829
+ path = [tuple(range(num_inputs))]
830
+ elif path_type == "greedy":
831
+ path = _greedy_path(
832
+ input_sets, output_set, dimension_dict, memory_arg
833
+ )
834
+ elif path_type == "optimal":
835
+ path = _optimal_path(
836
+ input_sets, output_set, dimension_dict, memory_arg
837
+ )
838
+ else:
839
+ raise KeyError("Path name %s not found", path_type)
840
+
841
+ cost_list, scale_list, size_list, contraction_list = [], [], [], []
842
+
843
+ # Build contraction tuple (positions, gemm, einsum_str, remaining)
844
+ for cnum, contract_inds in enumerate(path):
845
+ # Make sure we remove inds from right to left
846
+ contract_inds = tuple(sorted(contract_inds, reverse=True))
847
+
848
+ contract = _find_contraction(contract_inds, input_sets, output_set)
849
+ out_inds, input_sets, idx_removed, idx_contract = contract
850
+
851
+ if not einsum_call_arg:
852
+ # these are only needed for printing info
853
+ cost = _flop_count(
854
+ idx_contract, idx_removed, len(contract_inds), dimension_dict
855
+ )
856
+ cost_list.append(cost)
857
+ scale_list.append(len(idx_contract))
858
+ size_list.append(_compute_size_by_dict(out_inds, dimension_dict))
859
+
860
+ tmp_inputs = []
861
+ for x in contract_inds:
862
+ tmp_inputs.append(input_list.pop(x))
863
+
864
+ # Last contraction
865
+ if (cnum - len(path)) == -1:
866
+ idx_result = output_subscript
867
+ else:
868
+ sort_result = [(dimension_dict[ind], ind) for ind in out_inds]
869
+ idx_result = "".join([x[1] for x in sorted(sort_result)])
870
+
871
+ input_list.append(idx_result)
872
+ einsum_str = ",".join(tmp_inputs) + "->" + idx_result
873
+
874
+ contraction = (contract_inds, einsum_str, input_list[:])
875
+ contraction_list.append(contraction)
876
+
877
+ if len(input_list) != 1:
878
+ # Explicit "einsum_path" is usually trusted, but we detect this kind of
879
+ # mistake in order to prevent from returning an intermediate value.
880
+ raise RuntimeError(
881
+ f"Invalid einsum_path is specified: {len(input_list) - 1} more "
882
+ "operands has to be contracted.")
883
+
884
+ if einsum_call_arg:
885
+ return (operands, contraction_list)
886
+
887
+ # Return the path along with a nice string representation
888
+ overall_contraction = input_subscripts + "->" + output_subscript
889
+ header = ("scaling", "current", "remaining")
890
+
891
+ # Compute naive cost
892
+ # This isn't quite right, need to look into exactly how einsum does this
893
+ inner_product = (
894
+ sum(len(set(x)) for x in input_subscripts.split(',')) - num_indices
895
+ ) > 0
896
+ naive_cost = _flop_count(
897
+ indices, inner_product, num_inputs, dimension_dict
898
+ )
899
+
900
+ opt_cost = sum(cost_list) + 1
901
+ speedup = naive_cost / opt_cost
902
+ max_i = max(size_list)
903
+
904
+ path_print = f" Complete contraction: {overall_contraction}\n"
905
+ path_print += f" Naive scaling: {num_indices}\n"
906
+ path_print += " Optimized scaling: %d\n" % max(scale_list)
907
+ path_print += f" Naive FLOP count: {naive_cost:.3e}\n"
908
+ path_print += f" Optimized FLOP count: {opt_cost:.3e}\n"
909
+ path_print += f" Theoretical speedup: {speedup:3.3f}\n"
910
+ path_print += f" Largest intermediate: {max_i:.3e} elements\n"
911
+ path_print += "-" * 74 + "\n"
912
+ path_print += "%6s %24s %40s\n" % header
913
+ path_print += "-" * 74
914
+
915
+ for n, contraction in enumerate(contraction_list):
916
+ _, einsum_str, remaining = contraction
917
+ remaining_str = ",".join(remaining) + "->" + output_subscript
918
+ path_run = (scale_list[n], einsum_str, remaining_str)
919
+ path_print += "\n%4d %24s %40s" % path_run
920
+
921
+ path = ['einsum_path'] + path
922
+ return (path, path_print)
923
+
924
+
925
+ def _parse_eq_to_pure_multiplication(a_term, shape_a, b_term, shape_b, out):
926
+ """If there are no contracted indices, then we can directly transpose and
927
+ insert singleton dimensions into ``a`` and ``b`` such that (broadcast)
928
+ elementwise multiplication performs the einsum.
929
+
930
+ No need to cache this as it is within the cached
931
+ ``_parse_eq_to_batch_matmul``.
932
+
933
+ """
934
+ desired_a = ""
935
+ desired_b = ""
936
+ new_shape_a = []
937
+ new_shape_b = []
938
+ for ix in out:
939
+ if ix in a_term:
940
+ desired_a += ix
941
+ new_shape_a.append(shape_a[a_term.index(ix)])
942
+ else:
943
+ new_shape_a.append(1)
944
+ if ix in b_term:
945
+ desired_b += ix
946
+ new_shape_b.append(shape_b[b_term.index(ix)])
947
+ else:
948
+ new_shape_b.append(1)
949
+
950
+ if desired_a != a_term:
951
+ eq_a = f"{a_term}->{desired_a}"
952
+ else:
953
+ eq_a = None
954
+ if desired_b != b_term:
955
+ eq_b = f"{b_term}->{desired_b}"
956
+ else:
957
+ eq_b = None
958
+
959
+ return (
960
+ eq_a,
961
+ eq_b,
962
+ new_shape_a,
963
+ new_shape_b,
964
+ None, # new_shape_ab, not needed since not fusing
965
+ None, # perm_ab, not needed as we transpose a and b first
966
+ True, # pure_multiplication=True
967
+ )
968
+
969
+
970
+ @functools.lru_cache(2**12)
971
+ def _parse_eq_to_batch_matmul(eq, shape_a, shape_b):
972
+ """Cached parsing of a two term einsum equation into the necessary
973
+ sequence of arguments for contracttion via batched matrix multiplication.
974
+ The steps we need to specify are:
975
+
976
+ 1. Remove repeated and trivial indices from the left and right terms,
977
+ and transpose them, done as a single einsum.
978
+ 2. Fuse the remaining indices so we have two 3D tensors.
979
+ 3. Perform the batched matrix multiplication.
980
+ 4. Unfuse the output to get the desired final index order.
981
+
982
+ """
983
+ lhs, out = eq.split("->")
984
+ a_term, b_term = lhs.split(",")
985
+
986
+ if len(a_term) != len(shape_a):
987
+ raise ValueError(f"Term '{a_term}' does not match shape {shape_a}.")
988
+ if len(b_term) != len(shape_b):
989
+ raise ValueError(f"Term '{b_term}' does not match shape {shape_b}.")
990
+
991
+ sizes = {}
992
+ singletons = set()
993
+
994
+ # parse left term to unique indices with size > 1
995
+ left = {}
996
+ for ix, d in zip(a_term, shape_a):
997
+ if d == 1:
998
+ # everything (including broadcasting) works nicely if simply ignore
999
+ # such dimensions, but we do need to track if they appear in output
1000
+ # and thus should be reintroduced later
1001
+ singletons.add(ix)
1002
+ continue
1003
+ if sizes.setdefault(ix, d) != d:
1004
+ # set and check size
1005
+ raise ValueError(
1006
+ f"Index {ix} has mismatched sizes {sizes[ix]} and {d}."
1007
+ )
1008
+ left[ix] = True
1009
+
1010
+ # parse right term to unique indices with size > 1
1011
+ right = {}
1012
+ for ix, d in zip(b_term, shape_b):
1013
+ # broadcast indices (size 1 on one input and size != 1
1014
+ # on the other) should not be treated as singletons
1015
+ if d == 1:
1016
+ if ix not in left:
1017
+ singletons.add(ix)
1018
+ continue
1019
+ singletons.discard(ix)
1020
+
1021
+ if sizes.setdefault(ix, d) != d:
1022
+ # set and check size
1023
+ raise ValueError(
1024
+ f"Index {ix} has mismatched sizes {sizes[ix]} and {d}."
1025
+ )
1026
+ right[ix] = True
1027
+
1028
+ # now we classify the unique size > 1 indices only
1029
+ bat_inds = [] # appears on A, B, O
1030
+ con_inds = [] # appears on A, B, .
1031
+ a_keep = [] # appears on A, ., O
1032
+ b_keep = [] # appears on ., B, O
1033
+ # other indices (appearing on A or B only) will
1034
+ # be summed or traced out prior to the matmul
1035
+ for ix in left:
1036
+ if right.pop(ix, False):
1037
+ if ix in out:
1038
+ bat_inds.append(ix)
1039
+ else:
1040
+ con_inds.append(ix)
1041
+ elif ix in out:
1042
+ a_keep.append(ix)
1043
+ # now only indices unique to right remain
1044
+ for ix in right:
1045
+ if ix in out:
1046
+ b_keep.append(ix)
1047
+
1048
+ if not con_inds:
1049
+ # contraction is pure multiplication, prepare inputs differently
1050
+ return _parse_eq_to_pure_multiplication(
1051
+ a_term, shape_a, b_term, shape_b, out
1052
+ )
1053
+
1054
+ # only need the size one indices that appear in the output
1055
+ singletons = [ix for ix in out if ix in singletons]
1056
+
1057
+ # take diagonal, remove any trivial axes and transpose left
1058
+ desired_a = "".join((*bat_inds, *a_keep, *con_inds))
1059
+ if a_term != desired_a:
1060
+ eq_a = f"{a_term}->{desired_a}"
1061
+ else:
1062
+ eq_a = None
1063
+
1064
+ # take diagonal, remove any trivial axes and transpose right
1065
+ desired_b = "".join((*bat_inds, *con_inds, *b_keep))
1066
+ if b_term != desired_b:
1067
+ eq_b = f"{b_term}->{desired_b}"
1068
+ else:
1069
+ eq_b = None
1070
+
1071
+ # then we want to reshape
1072
+ if bat_inds:
1073
+ lgroups = (bat_inds, a_keep, con_inds)
1074
+ rgroups = (bat_inds, con_inds, b_keep)
1075
+ ogroups = (bat_inds, a_keep, b_keep)
1076
+ else:
1077
+ # avoid size 1 batch dimension if no batch indices
1078
+ lgroups = (a_keep, con_inds)
1079
+ rgroups = (con_inds, b_keep)
1080
+ ogroups = (a_keep, b_keep)
1081
+
1082
+ if any(len(group) != 1 for group in lgroups):
1083
+ # need to fuse 'kept' and contracted indices
1084
+ # (though could allow batch indices to be broadcast)
1085
+ new_shape_a = tuple(
1086
+ functools.reduce(operator.mul, (sizes[ix] for ix in ix_group), 1)
1087
+ for ix_group in lgroups
1088
+ )
1089
+ else:
1090
+ new_shape_a = None
1091
+
1092
+ if any(len(group) != 1 for group in rgroups):
1093
+ # need to fuse 'kept' and contracted indices
1094
+ # (though could allow batch indices to be broadcast)
1095
+ new_shape_b = tuple(
1096
+ functools.reduce(operator.mul, (sizes[ix] for ix in ix_group), 1)
1097
+ for ix_group in rgroups
1098
+ )
1099
+ else:
1100
+ new_shape_b = None
1101
+
1102
+ if any(len(group) != 1 for group in ogroups) or singletons:
1103
+ new_shape_ab = (1,) * len(singletons) + tuple(
1104
+ sizes[ix] for ix_group in ogroups for ix in ix_group
1105
+ )
1106
+ else:
1107
+ new_shape_ab = None
1108
+
1109
+ # then we might need to permute the matmul produced output:
1110
+ out_produced = "".join((*singletons, *bat_inds, *a_keep, *b_keep))
1111
+ if out_produced != out:
1112
+ perm_ab = tuple(out_produced.index(ix) for ix in out)
1113
+ else:
1114
+ perm_ab = None
1115
+
1116
+ return (
1117
+ eq_a,
1118
+ eq_b,
1119
+ new_shape_a,
1120
+ new_shape_b,
1121
+ new_shape_ab,
1122
+ perm_ab,
1123
+ False, # pure_multiplication=False
1124
+ )
1125
+
1126
+
1127
+ @functools.lru_cache(maxsize=64)
1128
+ def _parse_output_order(order, a_is_fcontig, b_is_fcontig):
1129
+ order = order.upper()
1130
+ if order == "K":
1131
+ return None
1132
+ elif order in "CF":
1133
+ return order
1134
+ elif order == "A":
1135
+ if a_is_fcontig and b_is_fcontig:
1136
+ return "F"
1137
+ else:
1138
+ return "C"
1139
+ else:
1140
+ raise ValueError(
1141
+ "ValueError: order must be one of "
1142
+ f"'C', 'F', 'A', or 'K' (got '{order}')"
1143
+ )
1144
+
1145
+
1146
+ def bmm_einsum(eq, a, b, out=None, **kwargs):
1147
+ """Perform arbitrary pairwise einsums using only ``matmul``, or
1148
+ ``multiply`` if no contracted indices are involved (plus maybe single term
1149
+ ``einsum`` to prepare the terms individually). The logic for each is cached
1150
+ based on the equation and array shape, and each step is only performed if
1151
+ necessary.
1152
+
1153
+ Parameters
1154
+ ----------
1155
+ eq : str
1156
+ The einsum equation.
1157
+ a : array_like
1158
+ The first array to contract.
1159
+ b : array_like
1160
+ The second array to contract.
1161
+
1162
+ Returns
1163
+ -------
1164
+ array_like
1165
+
1166
+ Notes
1167
+ -----
1168
+ A fuller description of this algorithm, and original source for this
1169
+ implementation, can be found at https://github.com/jcmgray/einsum_bmm.
1170
+ """
1171
+ (
1172
+ eq_a,
1173
+ eq_b,
1174
+ new_shape_a,
1175
+ new_shape_b,
1176
+ new_shape_ab,
1177
+ perm_ab,
1178
+ pure_multiplication,
1179
+ ) = _parse_eq_to_batch_matmul(eq, a.shape, b.shape)
1180
+
1181
+ # n.b. one could special case various cases to call c_einsum directly here
1182
+
1183
+ # need to handle `order` a little manually, since we do transpose
1184
+ # operations before and potentially after the ufunc calls
1185
+ output_order = _parse_output_order(
1186
+ kwargs.pop("order", "K"), a.flags.f_contiguous, b.flags.f_contiguous
1187
+ )
1188
+
1189
+ # prepare left
1190
+ if eq_a is not None:
1191
+ # diagonals, sums, and tranpose
1192
+ a = c_einsum(eq_a, a)
1193
+ if new_shape_a is not None:
1194
+ a = reshape(a, new_shape_a)
1195
+
1196
+ # prepare right
1197
+ if eq_b is not None:
1198
+ # diagonals, sums, and tranpose
1199
+ b = c_einsum(eq_b, b)
1200
+ if new_shape_b is not None:
1201
+ b = reshape(b, new_shape_b)
1202
+
1203
+ if pure_multiplication:
1204
+ # no contracted indices
1205
+ if output_order is not None:
1206
+ kwargs["order"] = output_order
1207
+
1208
+ # do the 'contraction' via multiplication!
1209
+ return multiply(a, b, out=out, **kwargs)
1210
+
1211
+ # can only supply out here if no other reshaping / transposing
1212
+ matmul_out_compatible = (new_shape_ab is None) and (perm_ab is None)
1213
+ if matmul_out_compatible:
1214
+ kwargs["out"] = out
1215
+
1216
+ # do the contraction!
1217
+ ab = matmul(a, b, **kwargs)
1218
+
1219
+ # prepare the output
1220
+ if new_shape_ab is not None:
1221
+ ab = reshape(ab, new_shape_ab)
1222
+ if perm_ab is not None:
1223
+ ab = ab.transpose(perm_ab)
1224
+
1225
+ if (out is not None) and (not matmul_out_compatible):
1226
+ # handle case where out is specified, but we also needed
1227
+ # to reshape / transpose ``ab`` after the matmul
1228
+ out[:] = ab
1229
+ ab = out
1230
+ elif output_order is not None:
1231
+ ab = asanyarray(ab, order=output_order)
1232
+
1233
+ return ab
1234
+
1235
+
1236
+ def _einsum_dispatcher(*operands, out=None, optimize=None, **kwargs):
1237
+ # Arguably we dispatch on more arguments than we really should; see note in
1238
+ # _einsum_path_dispatcher for why.
1239
+ yield from operands
1240
+ yield out
1241
+
1242
+
1243
+ # Rewrite einsum to handle different cases
1244
+ @array_function_dispatch(_einsum_dispatcher, module='numpy')
1245
+ def einsum(*operands, out=None, optimize=False, **kwargs):
1246
+ """
1247
+ einsum(subscripts, *operands, out=None, dtype=None, order='K',
1248
+ casting='safe', optimize=False)
1249
+
1250
+ Evaluates the Einstein summation convention on the operands.
1251
+
1252
+ Using the Einstein summation convention, many common multi-dimensional,
1253
+ linear algebraic array operations can be represented in a simple fashion.
1254
+ In *implicit* mode `einsum` computes these values.
1255
+
1256
+ In *explicit* mode, `einsum` provides further flexibility to compute
1257
+ other array operations that might not be considered classical Einstein
1258
+ summation operations, by disabling, or forcing summation over specified
1259
+ subscript labels.
1260
+
1261
+ See the notes and examples for clarification.
1262
+
1263
+ Parameters
1264
+ ----------
1265
+ subscripts : str
1266
+ Specifies the subscripts for summation as comma separated list of
1267
+ subscript labels. An implicit (classical Einstein summation)
1268
+ calculation is performed unless the explicit indicator '->' is
1269
+ included as well as subscript labels of the precise output form.
1270
+ operands : list of array_like
1271
+ These are the arrays for the operation.
1272
+ out : ndarray, optional
1273
+ If provided, the calculation is done into this array.
1274
+ dtype : {data-type, None}, optional
1275
+ If provided, forces the calculation to use the data type specified.
1276
+ Note that you may have to also give a more liberal `casting`
1277
+ parameter to allow the conversions. Default is None.
1278
+ order : {'C', 'F', 'A', 'K'}, optional
1279
+ Controls the memory layout of the output. 'C' means it should
1280
+ be C contiguous. 'F' means it should be Fortran contiguous,
1281
+ 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
1282
+ 'K' means it should be as close to the layout as the inputs as
1283
+ is possible, including arbitrarily permuted axes.
1284
+ Default is 'K'.
1285
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
1286
+ Controls what kind of data casting may occur. Setting this to
1287
+ 'unsafe' is not recommended, as it can adversely affect accumulations.
1288
+
1289
+ * 'no' means the data types should not be cast at all.
1290
+ * 'equiv' means only byte-order changes are allowed.
1291
+ * 'safe' means only casts which can preserve values are allowed.
1292
+ * 'same_kind' means only safe casts or casts within a kind,
1293
+ like float64 to float32, are allowed.
1294
+ * 'unsafe' means any data conversions may be done.
1295
+
1296
+ Default is 'safe'.
1297
+ optimize : {False, True, 'greedy', 'optimal'}, optional
1298
+ Controls if intermediate optimization should occur. No optimization
1299
+ will occur if False and True will default to the 'greedy' algorithm.
1300
+ Also accepts an explicit contraction list from the ``np.einsum_path``
1301
+ function. See ``np.einsum_path`` for more details. Defaults to False.
1302
+
1303
+ Returns
1304
+ -------
1305
+ output : ndarray
1306
+ The calculation based on the Einstein summation convention.
1307
+
1308
+ See Also
1309
+ --------
1310
+ einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
1311
+ einsum:
1312
+ Similar verbose interface is provided by the
1313
+ `einops <https://github.com/arogozhnikov/einops>`_ package to cover
1314
+ additional operations: transpose, reshape/flatten, repeat/tile,
1315
+ squeeze/unsqueeze and reductions.
1316
+ The `opt_einsum <https://optimized-einsum.readthedocs.io/en/stable/>`_
1317
+ optimizes contraction order for einsum-like expressions
1318
+ in backend-agnostic manner.
1319
+
1320
+ Notes
1321
+ -----
1322
+ The Einstein summation convention can be used to compute
1323
+ many multi-dimensional, linear algebraic array operations. `einsum`
1324
+ provides a succinct way of representing these.
1325
+
1326
+ A non-exhaustive list of these operations,
1327
+ which can be computed by `einsum`, is shown below along with examples:
1328
+
1329
+ * Trace of an array, :py:func:`numpy.trace`.
1330
+ * Return a diagonal, :py:func:`numpy.diag`.
1331
+ * Array axis summations, :py:func:`numpy.sum`.
1332
+ * Transpositions and permutations, :py:func:`numpy.transpose`.
1333
+ * Matrix multiplication and dot product, :py:func:`numpy.matmul`
1334
+ :py:func:`numpy.dot`.
1335
+ * Vector inner and outer products, :py:func:`numpy.inner`
1336
+ :py:func:`numpy.outer`.
1337
+ * Broadcasting, element-wise and scalar multiplication,
1338
+ :py:func:`numpy.multiply`.
1339
+ * Tensor contractions, :py:func:`numpy.tensordot`.
1340
+ * Chained array operations, in efficient calculation order,
1341
+ :py:func:`numpy.einsum_path`.
1342
+
1343
+ The subscripts string is a comma-separated list of subscript labels,
1344
+ where each label refers to a dimension of the corresponding operand.
1345
+ Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
1346
+ is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
1347
+ appears only once, it is not summed, so ``np.einsum('i', a)``
1348
+ produces a view of ``a`` with no changes. A further example
1349
+ ``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
1350
+ and is equivalent to :py:func:`np.matmul(a,b) <numpy.matmul>`.
1351
+ Repeated subscript labels in one operand take the diagonal.
1352
+ For example, ``np.einsum('ii', a)`` is equivalent to
1353
+ :py:func:`np.trace(a) <numpy.trace>`.
1354
+
1355
+ In *implicit mode*, the chosen subscripts are important
1356
+ since the axes of the output are reordered alphabetically. This
1357
+ means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
1358
+ ``np.einsum('ji', a)`` takes its transpose. Additionally,
1359
+ ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
1360
+ ``np.einsum('ij,jh', a, b)`` returns the transpose of the
1361
+ multiplication since subscript 'h' precedes subscript 'i'.
1362
+
1363
+ In *explicit mode* the output can be directly controlled by
1364
+ specifying output subscript labels. This requires the
1365
+ identifier '->' as well as the list of output subscript labels.
1366
+ This feature increases the flexibility of the function since
1367
+ summing can be disabled or forced when required. The call
1368
+ ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
1369
+ if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
1370
+ is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
1371
+ The difference is that `einsum` does not allow broadcasting by default.
1372
+ Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
1373
+ order of the output subscript labels and therefore returns matrix
1374
+ multiplication, unlike the example above in implicit mode.
1375
+
1376
+ To enable and control broadcasting, use an ellipsis. Default
1377
+ NumPy-style broadcasting is done by adding an ellipsis
1378
+ to the left of each term, like ``np.einsum('...ii->...i', a)``.
1379
+ ``np.einsum('...i->...', a)`` is like
1380
+ :py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
1381
+ To take the trace along the first and last axes,
1382
+ you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
1383
+ product with the left-most indices instead of rightmost, one can do
1384
+ ``np.einsum('ij...,jk...->ik...', a, b)``.
1385
+
1386
+ When there is only one operand, no axes are summed, and no output
1387
+ parameter is provided, a view into the operand is returned instead
1388
+ of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
1389
+ produces a view (changed in version 1.10.0).
1390
+
1391
+ `einsum` also provides an alternative way to provide the subscripts and
1392
+ operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
1393
+ If the output shape is not provided in this format `einsum` will be
1394
+ calculated in implicit mode, otherwise it will be performed explicitly.
1395
+ The examples below have corresponding `einsum` calls with the two
1396
+ parameter methods.
1397
+
1398
+ Views returned from einsum are now writeable whenever the input array
1399
+ is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
1400
+ have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
1401
+ and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
1402
+ of a 2D array.
1403
+
1404
+ Added the ``optimize`` argument which will optimize the contraction order
1405
+ of an einsum expression. For a contraction with three or more operands
1406
+ this can greatly increase the computational efficiency at the cost of
1407
+ a larger memory footprint during computation.
1408
+
1409
+ Typically a 'greedy' algorithm is applied which empirical tests have shown
1410
+ returns the optimal path in the majority of cases. In some cases 'optimal'
1411
+ will return the superlative path through a more expensive, exhaustive
1412
+ search. For iterative calculations it may be advisable to calculate
1413
+ the optimal path once and reuse that path by supplying it as an argument.
1414
+ An example is given below.
1415
+
1416
+ See :py:func:`numpy.einsum_path` for more details.
1417
+
1418
+ Examples
1419
+ --------
1420
+ >>> a = np.arange(25).reshape(5,5)
1421
+ >>> b = np.arange(5)
1422
+ >>> c = np.arange(6).reshape(2,3)
1423
+
1424
+ Trace of a matrix:
1425
+
1426
+ >>> np.einsum('ii', a)
1427
+ 60
1428
+ >>> np.einsum(a, [0,0])
1429
+ 60
1430
+ >>> np.trace(a)
1431
+ 60
1432
+
1433
+ Extract the diagonal (requires explicit form):
1434
+
1435
+ >>> np.einsum('ii->i', a)
1436
+ array([ 0, 6, 12, 18, 24])
1437
+ >>> np.einsum(a, [0,0], [0])
1438
+ array([ 0, 6, 12, 18, 24])
1439
+ >>> np.diag(a)
1440
+ array([ 0, 6, 12, 18, 24])
1441
+
1442
+ Sum over an axis (requires explicit form):
1443
+
1444
+ >>> np.einsum('ij->i', a)
1445
+ array([ 10, 35, 60, 85, 110])
1446
+ >>> np.einsum(a, [0,1], [0])
1447
+ array([ 10, 35, 60, 85, 110])
1448
+ >>> np.sum(a, axis=1)
1449
+ array([ 10, 35, 60, 85, 110])
1450
+
1451
+ For higher dimensional arrays summing a single axis can be done
1452
+ with ellipsis:
1453
+
1454
+ >>> np.einsum('...j->...', a)
1455
+ array([ 10, 35, 60, 85, 110])
1456
+ >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
1457
+ array([ 10, 35, 60, 85, 110])
1458
+
1459
+ Compute a matrix transpose, or reorder any number of axes:
1460
+
1461
+ >>> np.einsum('ji', c)
1462
+ array([[0, 3],
1463
+ [1, 4],
1464
+ [2, 5]])
1465
+ >>> np.einsum('ij->ji', c)
1466
+ array([[0, 3],
1467
+ [1, 4],
1468
+ [2, 5]])
1469
+ >>> np.einsum(c, [1,0])
1470
+ array([[0, 3],
1471
+ [1, 4],
1472
+ [2, 5]])
1473
+ >>> np.transpose(c)
1474
+ array([[0, 3],
1475
+ [1, 4],
1476
+ [2, 5]])
1477
+
1478
+ Vector inner products:
1479
+
1480
+ >>> np.einsum('i,i', b, b)
1481
+ 30
1482
+ >>> np.einsum(b, [0], b, [0])
1483
+ 30
1484
+ >>> np.inner(b,b)
1485
+ 30
1486
+
1487
+ Matrix vector multiplication:
1488
+
1489
+ >>> np.einsum('ij,j', a, b)
1490
+ array([ 30, 80, 130, 180, 230])
1491
+ >>> np.einsum(a, [0,1], b, [1])
1492
+ array([ 30, 80, 130, 180, 230])
1493
+ >>> np.dot(a, b)
1494
+ array([ 30, 80, 130, 180, 230])
1495
+ >>> np.einsum('...j,j', a, b)
1496
+ array([ 30, 80, 130, 180, 230])
1497
+
1498
+ Broadcasting and scalar multiplication:
1499
+
1500
+ >>> np.einsum('..., ...', 3, c)
1501
+ array([[ 0, 3, 6],
1502
+ [ 9, 12, 15]])
1503
+ >>> np.einsum(',ij', 3, c)
1504
+ array([[ 0, 3, 6],
1505
+ [ 9, 12, 15]])
1506
+ >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
1507
+ array([[ 0, 3, 6],
1508
+ [ 9, 12, 15]])
1509
+ >>> np.multiply(3, c)
1510
+ array([[ 0, 3, 6],
1511
+ [ 9, 12, 15]])
1512
+
1513
+ Vector outer product:
1514
+
1515
+ >>> np.einsum('i,j', np.arange(2)+1, b)
1516
+ array([[0, 1, 2, 3, 4],
1517
+ [0, 2, 4, 6, 8]])
1518
+ >>> np.einsum(np.arange(2)+1, [0], b, [1])
1519
+ array([[0, 1, 2, 3, 4],
1520
+ [0, 2, 4, 6, 8]])
1521
+ >>> np.outer(np.arange(2)+1, b)
1522
+ array([[0, 1, 2, 3, 4],
1523
+ [0, 2, 4, 6, 8]])
1524
+
1525
+ Tensor contraction:
1526
+
1527
+ >>> a = np.arange(60.).reshape(3,4,5)
1528
+ >>> b = np.arange(24.).reshape(4,3,2)
1529
+ >>> np.einsum('ijk,jil->kl', a, b)
1530
+ array([[4400., 4730.],
1531
+ [4532., 4874.],
1532
+ [4664., 5018.],
1533
+ [4796., 5162.],
1534
+ [4928., 5306.]])
1535
+ >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
1536
+ array([[4400., 4730.],
1537
+ [4532., 4874.],
1538
+ [4664., 5018.],
1539
+ [4796., 5162.],
1540
+ [4928., 5306.]])
1541
+ >>> np.tensordot(a,b, axes=([1,0],[0,1]))
1542
+ array([[4400., 4730.],
1543
+ [4532., 4874.],
1544
+ [4664., 5018.],
1545
+ [4796., 5162.],
1546
+ [4928., 5306.]])
1547
+
1548
+ Writeable returned arrays (since version 1.10.0):
1549
+
1550
+ >>> a = np.zeros((3, 3))
1551
+ >>> np.einsum('ii->i', a)[:] = 1
1552
+ >>> a
1553
+ array([[1., 0., 0.],
1554
+ [0., 1., 0.],
1555
+ [0., 0., 1.]])
1556
+
1557
+ Example of ellipsis use:
1558
+
1559
+ >>> a = np.arange(6).reshape((3,2))
1560
+ >>> b = np.arange(12).reshape((4,3))
1561
+ >>> np.einsum('ki,jk->ij', a, b)
1562
+ array([[10, 28, 46, 64],
1563
+ [13, 40, 67, 94]])
1564
+ >>> np.einsum('ki,...k->i...', a, b)
1565
+ array([[10, 28, 46, 64],
1566
+ [13, 40, 67, 94]])
1567
+ >>> np.einsum('k...,jk', a, b)
1568
+ array([[10, 28, 46, 64],
1569
+ [13, 40, 67, 94]])
1570
+
1571
+ Chained array operations. For more complicated contractions, speed ups
1572
+ might be achieved by repeatedly computing a 'greedy' path or pre-computing
1573
+ the 'optimal' path and repeatedly applying it, using an `einsum_path`
1574
+ insertion (since version 1.12.0). Performance improvements can be
1575
+ particularly significant with larger arrays:
1576
+
1577
+ >>> a = np.ones(64).reshape(2,4,8)
1578
+
1579
+ Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.)
1580
+
1581
+ >>> for iteration in range(500):
1582
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
1583
+
1584
+ Sub-optimal `einsum` (due to repeated path calculation time): ~330ms
1585
+
1586
+ >>> for iteration in range(500):
1587
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
1588
+ ... optimize='optimal')
1589
+
1590
+ Greedy `einsum` (faster optimal path approximation): ~160ms
1591
+
1592
+ >>> for iteration in range(500):
1593
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
1594
+
1595
+ Optimal `einsum` (best usage pattern in some use cases): ~110ms
1596
+
1597
+ >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
1598
+ ... optimize='optimal')[0]
1599
+ >>> for iteration in range(500):
1600
+ ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
1601
+
1602
+ """
1603
+ # Special handling if out is specified
1604
+ specified_out = out is not None
1605
+
1606
+ # If no optimization, run pure einsum
1607
+ if optimize is False:
1608
+ if specified_out:
1609
+ kwargs['out'] = out
1610
+ return c_einsum(*operands, **kwargs)
1611
+
1612
+ # Check the kwargs to avoid a more cryptic error later, without having to
1613
+ # repeat default values here
1614
+ valid_einsum_kwargs = ['dtype', 'order', 'casting']
1615
+ unknown_kwargs = [k for (k, v) in kwargs.items() if
1616
+ k not in valid_einsum_kwargs]
1617
+ if len(unknown_kwargs):
1618
+ raise TypeError(f"Did not understand the following kwargs: {unknown_kwargs}")
1619
+
1620
+ # Build the contraction list and operand
1621
+ operands, contraction_list = einsum_path(*operands, optimize=optimize,
1622
+ einsum_call=True)
1623
+
1624
+ # Start contraction loop
1625
+ for num, contraction in enumerate(contraction_list):
1626
+ inds, einsum_str, _ = contraction
1627
+ tmp_operands = [operands.pop(x) for x in inds]
1628
+
1629
+ # Do we need to deal with the output?
1630
+ handle_out = specified_out and ((num + 1) == len(contraction_list))
1631
+
1632
+ # If out was specified
1633
+ if handle_out:
1634
+ kwargs["out"] = out
1635
+
1636
+ if len(tmp_operands) == 2:
1637
+ # Call (batched) matrix multiplication if possible
1638
+ new_view = bmm_einsum(einsum_str, *tmp_operands, **kwargs)
1639
+ else:
1640
+ # Call einsum
1641
+ new_view = c_einsum(einsum_str, *tmp_operands, **kwargs)
1642
+
1643
+ # Append new items and dereference what we can
1644
+ operands.append(new_view)
1645
+ del tmp_operands, new_view
1646
+
1647
+ if specified_out:
1648
+ return out
1649
+ else:
1650
+ return operands[0]
python/user_packages/Python313/site-packages/numpy/_core/einsumfunc.pyi ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from typing import Any, Literal, TypeAlias, TypeVar, overload
3
+
4
+ import numpy as np
5
+ from numpy import _OrderKACF, number
6
+ from numpy._typing import (
7
+ NDArray,
8
+ _ArrayLikeBool_co,
9
+ _ArrayLikeComplex_co,
10
+ _ArrayLikeFloat_co,
11
+ _ArrayLikeInt_co,
12
+ _ArrayLikeObject_co,
13
+ _ArrayLikeUInt_co,
14
+ _DTypeLikeBool,
15
+ _DTypeLikeComplex,
16
+ _DTypeLikeComplex_co,
17
+ _DTypeLikeFloat,
18
+ _DTypeLikeInt,
19
+ _DTypeLikeObject,
20
+ _DTypeLikeUInt,
21
+ )
22
+
23
+ __all__ = ["einsum", "einsum_path"]
24
+
25
+ _ArrayT = TypeVar(
26
+ "_ArrayT",
27
+ bound=NDArray[np.bool | number],
28
+ )
29
+
30
+ _OptimizeKind: TypeAlias = bool | Literal["greedy", "optimal"] | Sequence[Any] | None
31
+ _CastingSafe: TypeAlias = Literal["no", "equiv", "safe", "same_kind"]
32
+ _CastingUnsafe: TypeAlias = Literal["unsafe"]
33
+
34
+ # TODO: Properly handle the `casting`-based combinatorics
35
+ # TODO: We need to evaluate the content `__subscripts` in order
36
+ # to identify whether or an array or scalar is returned. At a cursory
37
+ # glance this seems like something that can quite easily be done with
38
+ # a mypy plugin.
39
+ # Something like `is_scalar = bool(__subscripts.partition("->")[-1])`
40
+ @overload
41
+ def einsum(
42
+ subscripts: str | _ArrayLikeInt_co,
43
+ /,
44
+ *operands: _ArrayLikeBool_co,
45
+ out: None = None,
46
+ dtype: _DTypeLikeBool | None = ...,
47
+ order: _OrderKACF = ...,
48
+ casting: _CastingSafe = ...,
49
+ optimize: _OptimizeKind = False,
50
+ ) -> Any: ...
51
+ @overload
52
+ def einsum(
53
+ subscripts: str | _ArrayLikeInt_co,
54
+ /,
55
+ *operands: _ArrayLikeUInt_co,
56
+ out: None = None,
57
+ dtype: _DTypeLikeUInt | None = ...,
58
+ order: _OrderKACF = ...,
59
+ casting: _CastingSafe = ...,
60
+ optimize: _OptimizeKind = False,
61
+ ) -> Any: ...
62
+ @overload
63
+ def einsum(
64
+ subscripts: str | _ArrayLikeInt_co,
65
+ /,
66
+ *operands: _ArrayLikeInt_co,
67
+ out: None = None,
68
+ dtype: _DTypeLikeInt | None = ...,
69
+ order: _OrderKACF = ...,
70
+ casting: _CastingSafe = ...,
71
+ optimize: _OptimizeKind = False,
72
+ ) -> Any: ...
73
+ @overload
74
+ def einsum(
75
+ subscripts: str | _ArrayLikeInt_co,
76
+ /,
77
+ *operands: _ArrayLikeFloat_co,
78
+ out: None = None,
79
+ dtype: _DTypeLikeFloat | None = ...,
80
+ order: _OrderKACF = ...,
81
+ casting: _CastingSafe = ...,
82
+ optimize: _OptimizeKind = False,
83
+ ) -> Any: ...
84
+ @overload
85
+ def einsum(
86
+ subscripts: str | _ArrayLikeInt_co,
87
+ /,
88
+ *operands: _ArrayLikeComplex_co,
89
+ out: None = None,
90
+ dtype: _DTypeLikeComplex | None = ...,
91
+ order: _OrderKACF = ...,
92
+ casting: _CastingSafe = ...,
93
+ optimize: _OptimizeKind = False,
94
+ ) -> Any: ...
95
+ @overload
96
+ def einsum(
97
+ subscripts: str | _ArrayLikeInt_co,
98
+ /,
99
+ *operands: Any,
100
+ casting: _CastingUnsafe,
101
+ dtype: _DTypeLikeComplex_co | None = ...,
102
+ out: None = None,
103
+ order: _OrderKACF = ...,
104
+ optimize: _OptimizeKind = False,
105
+ ) -> Any: ...
106
+ @overload
107
+ def einsum(
108
+ subscripts: str | _ArrayLikeInt_co,
109
+ /,
110
+ *operands: _ArrayLikeComplex_co,
111
+ out: _ArrayT,
112
+ dtype: _DTypeLikeComplex_co | None = ...,
113
+ order: _OrderKACF = ...,
114
+ casting: _CastingSafe = ...,
115
+ optimize: _OptimizeKind = False,
116
+ ) -> _ArrayT: ...
117
+ @overload
118
+ def einsum(
119
+ subscripts: str | _ArrayLikeInt_co,
120
+ /,
121
+ *operands: Any,
122
+ out: _ArrayT,
123
+ casting: _CastingUnsafe,
124
+ dtype: _DTypeLikeComplex_co | None = ...,
125
+ order: _OrderKACF = ...,
126
+ optimize: _OptimizeKind = False,
127
+ ) -> _ArrayT: ...
128
+
129
+ @overload
130
+ def einsum(
131
+ subscripts: str | _ArrayLikeInt_co,
132
+ /,
133
+ *operands: _ArrayLikeObject_co,
134
+ out: None = None,
135
+ dtype: _DTypeLikeObject | None = ...,
136
+ order: _OrderKACF = ...,
137
+ casting: _CastingSafe = ...,
138
+ optimize: _OptimizeKind = False,
139
+ ) -> Any: ...
140
+ @overload
141
+ def einsum(
142
+ subscripts: str | _ArrayLikeInt_co,
143
+ /,
144
+ *operands: Any,
145
+ casting: _CastingUnsafe,
146
+ dtype: _DTypeLikeObject | None = ...,
147
+ out: None = None,
148
+ order: _OrderKACF = ...,
149
+ optimize: _OptimizeKind = False,
150
+ ) -> Any: ...
151
+ @overload
152
+ def einsum(
153
+ subscripts: str | _ArrayLikeInt_co,
154
+ /,
155
+ *operands: _ArrayLikeObject_co,
156
+ out: _ArrayT,
157
+ dtype: _DTypeLikeObject | None = ...,
158
+ order: _OrderKACF = ...,
159
+ casting: _CastingSafe = ...,
160
+ optimize: _OptimizeKind = False,
161
+ ) -> _ArrayT: ...
162
+ @overload
163
+ def einsum(
164
+ subscripts: str | _ArrayLikeInt_co,
165
+ /,
166
+ *operands: Any,
167
+ out: _ArrayT,
168
+ casting: _CastingUnsafe,
169
+ dtype: _DTypeLikeObject | None = ...,
170
+ order: _OrderKACF = ...,
171
+ optimize: _OptimizeKind = False,
172
+ ) -> _ArrayT: ...
173
+
174
+ # NOTE: `einsum_call` is a hidden kwarg unavailable for public use.
175
+ # It is therefore excluded from the signatures below.
176
+ # NOTE: In practice the list consists of a `str` (first element)
177
+ # and a variable number of integer tuples.
178
+ def einsum_path(
179
+ subscripts: str | _ArrayLikeInt_co,
180
+ /,
181
+ *operands: _ArrayLikeComplex_co | _DTypeLikeObject,
182
+ optimize: _OptimizeKind = "greedy",
183
+ einsum_call: Literal[False] = False,
184
+ ) -> tuple[list[Any], str]: ...
python/user_packages/Python313/site-packages/numpy/_core/fromnumeric.py ADDED
The diff for this file is too large to render. See raw diff
 
python/user_packages/Python313/site-packages/numpy/_core/fromnumeric.pyi ADDED
@@ -0,0 +1,1735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: ANN401
2
+ from _typeshed import Incomplete
3
+ from collections.abc import Sequence
4
+ from typing import (
5
+ Any,
6
+ Literal,
7
+ Never,
8
+ Protocol,
9
+ SupportsIndex,
10
+ TypeAlias,
11
+ TypedDict,
12
+ TypeVar,
13
+ Unpack,
14
+ overload,
15
+ type_check_only,
16
+ )
17
+
18
+ import numpy as np
19
+ from numpy import (
20
+ _AnyShapeT,
21
+ _CastingKind,
22
+ _ModeKind,
23
+ _OrderACF,
24
+ _OrderKACF,
25
+ _PartitionKind,
26
+ _SortKind,
27
+ _SortSide,
28
+ complexfloating,
29
+ float16,
30
+ floating,
31
+ generic,
32
+ int64,
33
+ int_,
34
+ intp,
35
+ object_,
36
+ timedelta64,
37
+ uint64,
38
+ )
39
+ from numpy._globals import _NoValueType
40
+ from numpy._typing import (
41
+ ArrayLike,
42
+ DTypeLike,
43
+ NDArray,
44
+ _AnyShape,
45
+ _ArrayLike,
46
+ _ArrayLikeBool_co,
47
+ _ArrayLikeComplex_co,
48
+ _ArrayLikeFloat_co,
49
+ _ArrayLikeInt,
50
+ _ArrayLikeInt_co,
51
+ _ArrayLikeObject_co,
52
+ _ArrayLikeUInt_co,
53
+ _BoolLike_co,
54
+ _ComplexLike_co,
55
+ _DTypeLike,
56
+ _IntLike_co,
57
+ _NestedSequence,
58
+ _NumberLike_co,
59
+ _ScalarLike_co,
60
+ _ShapeLike,
61
+ )
62
+
63
+ __all__ = [
64
+ "all",
65
+ "amax",
66
+ "amin",
67
+ "any",
68
+ "argmax",
69
+ "argmin",
70
+ "argpartition",
71
+ "argsort",
72
+ "around",
73
+ "choose",
74
+ "clip",
75
+ "compress",
76
+ "cumprod",
77
+ "cumsum",
78
+ "cumulative_prod",
79
+ "cumulative_sum",
80
+ "diagonal",
81
+ "mean",
82
+ "max",
83
+ "min",
84
+ "matrix_transpose",
85
+ "ndim",
86
+ "nonzero",
87
+ "partition",
88
+ "prod",
89
+ "ptp",
90
+ "put",
91
+ "ravel",
92
+ "repeat",
93
+ "reshape",
94
+ "resize",
95
+ "round",
96
+ "searchsorted",
97
+ "shape",
98
+ "size",
99
+ "sort",
100
+ "squeeze",
101
+ "std",
102
+ "sum",
103
+ "swapaxes",
104
+ "take",
105
+ "trace",
106
+ "transpose",
107
+ "var",
108
+ ]
109
+
110
+ _ScalarT = TypeVar("_ScalarT", bound=generic)
111
+ _NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number | np.object_)
112
+ _ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
113
+ _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
114
+ _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
115
+ _BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[np.integer | np.bool])
116
+
117
+ @type_check_only
118
+ class _SupportsShape(Protocol[_ShapeT_co]):
119
+ # NOTE: it matters that `self` is positional only
120
+ @property
121
+ def shape(self, /) -> _ShapeT_co: ...
122
+
123
+ @type_check_only
124
+ class _UFuncKwargs(TypedDict, total=False):
125
+ where: _ArrayLikeBool_co | None
126
+ order: _OrderKACF
127
+ subok: bool
128
+ signature: str | tuple[str | None, ...]
129
+ casting: _CastingKind
130
+
131
+ # a "sequence" that isn't a string, bytes, bytearray, or memoryview
132
+ _T = TypeVar("_T")
133
+ _PyArray: TypeAlias = list[_T] | tuple[_T, ...]
134
+ # `int` also covers `bool`
135
+ _PyScalar: TypeAlias = complex | bytes | str
136
+
137
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
138
+ @overload
139
+ def take(
140
+ a: _ArrayLike[_ScalarT],
141
+ indices: _IntLike_co,
142
+ axis: None = None,
143
+ out: None = None,
144
+ mode: _ModeKind = "raise",
145
+ ) -> _ScalarT: ...
146
+ @overload
147
+ def take(
148
+ a: ArrayLike,
149
+ indices: _IntLike_co,
150
+ axis: SupportsIndex | None = None,
151
+ out: None = None,
152
+ mode: _ModeKind = "raise",
153
+ ) -> Any: ...
154
+ @overload
155
+ def take(
156
+ a: _ArrayLike[_ScalarT],
157
+ indices: _ArrayLikeInt_co,
158
+ axis: SupportsIndex | None = None,
159
+ out: None = None,
160
+ mode: _ModeKind = "raise",
161
+ ) -> NDArray[_ScalarT]: ...
162
+ @overload
163
+ def take(
164
+ a: ArrayLike,
165
+ indices: _ArrayLikeInt_co,
166
+ axis: SupportsIndex | None = None,
167
+ out: None = None,
168
+ mode: _ModeKind = "raise",
169
+ ) -> NDArray[Any]: ...
170
+ @overload
171
+ def take(
172
+ a: ArrayLike,
173
+ indices: _ArrayLikeInt_co,
174
+ axis: SupportsIndex | None,
175
+ out: _ArrayT,
176
+ mode: _ModeKind = "raise",
177
+ ) -> _ArrayT: ...
178
+ @overload
179
+ def take(
180
+ a: ArrayLike,
181
+ indices: _ArrayLikeInt_co,
182
+ axis: SupportsIndex | None = None,
183
+ *,
184
+ out: _ArrayT,
185
+ mode: _ModeKind = "raise",
186
+ ) -> _ArrayT: ...
187
+
188
+ @overload
189
+ def reshape( # shape: index
190
+ a: _ArrayLike[_ScalarT],
191
+ /,
192
+ shape: SupportsIndex,
193
+ order: _OrderACF = "C",
194
+ *,
195
+ copy: bool | None = None,
196
+ ) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
197
+ @overload
198
+ def reshape( # shape: (int, ...) @ _AnyShapeT
199
+ a: _ArrayLike[_ScalarT],
200
+ /,
201
+ shape: _AnyShapeT,
202
+ order: _OrderACF = "C",
203
+ *,
204
+ copy: bool | None = None,
205
+ ) -> np.ndarray[_AnyShapeT, np.dtype[_ScalarT]]: ...
206
+ @overload # shape: Sequence[index]
207
+ def reshape(
208
+ a: _ArrayLike[_ScalarT],
209
+ /,
210
+ shape: Sequence[SupportsIndex],
211
+ order: _OrderACF = "C",
212
+ *,
213
+ copy: bool | None = None,
214
+ ) -> NDArray[_ScalarT]: ...
215
+ @overload # shape: index
216
+ def reshape(
217
+ a: ArrayLike,
218
+ /,
219
+ shape: SupportsIndex,
220
+ order: _OrderACF = "C",
221
+ *,
222
+ copy: bool | None = None,
223
+ ) -> np.ndarray[tuple[int], np.dtype]: ...
224
+ @overload
225
+ def reshape( # shape: (int, ...) @ _AnyShapeT
226
+ a: ArrayLike,
227
+ /,
228
+ shape: _AnyShapeT,
229
+ order: _OrderACF = "C",
230
+ *,
231
+ copy: bool | None = None,
232
+ ) -> np.ndarray[_AnyShapeT, np.dtype]: ...
233
+ @overload # shape: Sequence[index]
234
+ def reshape(
235
+ a: ArrayLike,
236
+ /,
237
+ shape: Sequence[SupportsIndex],
238
+ order: _OrderACF = "C",
239
+ *,
240
+ copy: bool | None = None,
241
+ ) -> NDArray[Any]: ...
242
+
243
+ @overload
244
+ def choose(
245
+ a: _IntLike_co,
246
+ choices: ArrayLike,
247
+ out: None = None,
248
+ mode: _ModeKind = "raise",
249
+ ) -> Any: ...
250
+ @overload
251
+ def choose(
252
+ a: _ArrayLikeInt_co,
253
+ choices: _ArrayLike[_ScalarT],
254
+ out: None = None,
255
+ mode: _ModeKind = "raise",
256
+ ) -> NDArray[_ScalarT]: ...
257
+ @overload
258
+ def choose(
259
+ a: _ArrayLikeInt_co,
260
+ choices: ArrayLike,
261
+ out: None = None,
262
+ mode: _ModeKind = "raise",
263
+ ) -> NDArray[Any]: ...
264
+ @overload
265
+ def choose(
266
+ a: _ArrayLikeInt_co,
267
+ choices: ArrayLike,
268
+ out: _ArrayT,
269
+ mode: _ModeKind = "raise",
270
+ ) -> _ArrayT: ...
271
+
272
+ # keep in sync with `ma.core.repeat`
273
+ @overload
274
+ def repeat(
275
+ a: _ArrayLike[_ScalarT],
276
+ repeats: _ArrayLikeInt_co,
277
+ axis: None = None,
278
+ ) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
279
+ @overload
280
+ def repeat(
281
+ a: _ArrayLike[_ScalarT],
282
+ repeats: _ArrayLikeInt_co,
283
+ axis: SupportsIndex,
284
+ ) -> NDArray[_ScalarT]: ...
285
+ @overload
286
+ def repeat(
287
+ a: ArrayLike,
288
+ repeats: _ArrayLikeInt_co,
289
+ axis: None = None,
290
+ ) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
291
+ @overload
292
+ def repeat(
293
+ a: ArrayLike,
294
+ repeats: _ArrayLikeInt_co,
295
+ axis: SupportsIndex,
296
+ ) -> NDArray[Any]: ...
297
+
298
+ #
299
+ def put(
300
+ a: NDArray[Any],
301
+ ind: _ArrayLikeInt_co,
302
+ v: ArrayLike,
303
+ mode: _ModeKind = "raise",
304
+ ) -> None: ...
305
+
306
+ # keep in sync with `ndarray.swapaxes` and `ma.core.swapaxes`
307
+ @overload
308
+ def swapaxes(a: _ArrayT, axis1: SupportsIndex, axis2: SupportsIndex) -> _ArrayT: ...
309
+ @overload
310
+ def swapaxes(a: _ArrayLike[_ScalarT], axis1: SupportsIndex, axis2: SupportsIndex) -> NDArray[_ScalarT]: ...
311
+ @overload
312
+ def swapaxes(a: ArrayLike, axis1: SupportsIndex, axis2: SupportsIndex) -> NDArray[Any]: ...
313
+
314
+ @overload
315
+ def transpose(
316
+ a: _ArrayLike[_ScalarT],
317
+ axes: _ShapeLike | None = None,
318
+ ) -> NDArray[_ScalarT]: ...
319
+ @overload
320
+ def transpose(
321
+ a: ArrayLike,
322
+ axes: _ShapeLike | None = None,
323
+ ) -> NDArray[Any]: ...
324
+
325
+ @overload
326
+ def matrix_transpose(x: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ...
327
+ @overload
328
+ def matrix_transpose(x: ArrayLike, /) -> NDArray[Any]: ...
329
+
330
+ #
331
+ @overload
332
+ def partition(
333
+ a: _ArrayLike[_ScalarT],
334
+ kth: _ArrayLikeInt,
335
+ axis: SupportsIndex | None = -1,
336
+ kind: _PartitionKind = "introselect",
337
+ order: None = None,
338
+ ) -> NDArray[_ScalarT]: ...
339
+ @overload
340
+ def partition(
341
+ a: _ArrayLike[np.void],
342
+ kth: _ArrayLikeInt,
343
+ axis: SupportsIndex | None = -1,
344
+ kind: _PartitionKind = "introselect",
345
+ order: str | Sequence[str] | None = None,
346
+ ) -> NDArray[np.void]: ...
347
+ @overload
348
+ def partition(
349
+ a: ArrayLike,
350
+ kth: _ArrayLikeInt,
351
+ axis: SupportsIndex | None = -1,
352
+ kind: _PartitionKind = "introselect",
353
+ order: str | Sequence[str] | None = None,
354
+ ) -> NDArray[Any]: ...
355
+
356
+ #
357
+ def argpartition(
358
+ a: ArrayLike,
359
+ kth: _ArrayLikeInt,
360
+ axis: SupportsIndex | None = -1,
361
+ kind: _PartitionKind = "introselect",
362
+ order: str | Sequence[str] | None = None,
363
+ ) -> NDArray[intp]: ...
364
+
365
+ #
366
+ @overload
367
+ def sort(
368
+ a: _ArrayLike[_ScalarT],
369
+ axis: SupportsIndex | None = -1,
370
+ kind: _SortKind | None = None,
371
+ order: str | Sequence[str] | None = None,
372
+ *,
373
+ stable: bool | None = None,
374
+ ) -> NDArray[_ScalarT]: ...
375
+ @overload
376
+ def sort(
377
+ a: ArrayLike,
378
+ axis: SupportsIndex | None = -1,
379
+ kind: _SortKind | None = None,
380
+ order: str | Sequence[str] | None = None,
381
+ *,
382
+ stable: bool | None = None,
383
+ ) -> NDArray[Any]: ...
384
+
385
+ def argsort(
386
+ a: ArrayLike,
387
+ axis: SupportsIndex | None = -1,
388
+ kind: _SortKind | None = None,
389
+ order: str | Sequence[str] | None = None,
390
+ *,
391
+ stable: bool | None = None,
392
+ ) -> NDArray[intp]: ...
393
+
394
+ @overload
395
+ def argmax(
396
+ a: ArrayLike,
397
+ axis: None = None,
398
+ out: None = None,
399
+ *,
400
+ keepdims: Literal[False] | _NoValueType = ...,
401
+ ) -> intp: ...
402
+ @overload
403
+ def argmax(
404
+ a: ArrayLike,
405
+ axis: SupportsIndex | None = None,
406
+ out: None = None,
407
+ *,
408
+ keepdims: bool | _NoValueType = ...,
409
+ ) -> Any: ...
410
+ @overload
411
+ def argmax(
412
+ a: ArrayLike,
413
+ axis: SupportsIndex | None,
414
+ out: _BoolOrIntArrayT,
415
+ *,
416
+ keepdims: bool | _NoValueType = ...,
417
+ ) -> _BoolOrIntArrayT: ...
418
+ @overload
419
+ def argmax(
420
+ a: ArrayLike,
421
+ axis: SupportsIndex | None = None,
422
+ *,
423
+ out: _BoolOrIntArrayT,
424
+ keepdims: bool | _NoValueType = ...,
425
+ ) -> _BoolOrIntArrayT: ...
426
+
427
+ @overload
428
+ def argmin(
429
+ a: ArrayLike,
430
+ axis: None = None,
431
+ out: None = None,
432
+ *,
433
+ keepdims: Literal[False] | _NoValueType = ...,
434
+ ) -> intp: ...
435
+ @overload
436
+ def argmin(
437
+ a: ArrayLike,
438
+ axis: SupportsIndex | None = None,
439
+ out: None = None,
440
+ *,
441
+ keepdims: bool | _NoValueType = ...,
442
+ ) -> Any: ...
443
+ @overload
444
+ def argmin(
445
+ a: ArrayLike,
446
+ axis: SupportsIndex | None,
447
+ out: _BoolOrIntArrayT,
448
+ *,
449
+ keepdims: bool | _NoValueType = ...,
450
+ ) -> _BoolOrIntArrayT: ...
451
+ @overload
452
+ def argmin(
453
+ a: ArrayLike,
454
+ axis: SupportsIndex | None = None,
455
+ *,
456
+ out: _BoolOrIntArrayT,
457
+ keepdims: bool | _NoValueType = ...,
458
+ ) -> _BoolOrIntArrayT: ...
459
+
460
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
461
+ @overload
462
+ def searchsorted(
463
+ a: ArrayLike,
464
+ v: _ScalarLike_co,
465
+ side: _SortSide = "left",
466
+ sorter: _ArrayLikeInt_co | None = None, # 1D int array
467
+ ) -> intp: ...
468
+ @overload
469
+ def searchsorted(
470
+ a: ArrayLike,
471
+ v: ArrayLike,
472
+ side: _SortSide = "left",
473
+ sorter: _ArrayLikeInt_co | None = None, # 1D int array
474
+ ) -> NDArray[intp]: ...
475
+
476
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
477
+ @overload
478
+ def resize(a: _ArrayLike[_ScalarT], new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
479
+ @overload
480
+ def resize(a: _ArrayLike[_ScalarT], new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype[_ScalarT]]: ...
481
+ @overload
482
+ def resize(a: _ArrayLike[_ScalarT], new_shape: _ShapeLike) -> NDArray[_ScalarT]: ...
483
+ @overload
484
+ def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype]: ...
485
+ @overload
486
+ def resize(a: ArrayLike, new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype]: ...
487
+ @overload
488
+ def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ...
489
+
490
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
491
+ @overload
492
+ def squeeze(
493
+ a: _ScalarT,
494
+ axis: _ShapeLike | None = None,
495
+ ) -> _ScalarT: ...
496
+ @overload
497
+ def squeeze(
498
+ a: _ArrayLike[_ScalarT],
499
+ axis: _ShapeLike | None = None,
500
+ ) -> NDArray[_ScalarT]: ...
501
+ @overload
502
+ def squeeze(
503
+ a: ArrayLike,
504
+ axis: _ShapeLike | None = None,
505
+ ) -> NDArray[Any]: ...
506
+
507
+ # keep in sync with `ma.core.diagonal`
508
+ @overload
509
+ def diagonal(
510
+ a: _ArrayLike[_ScalarT],
511
+ offset: SupportsIndex = 0,
512
+ axis1: SupportsIndex = 0,
513
+ axis2: SupportsIndex = 1, # >= 2D array
514
+ ) -> NDArray[_ScalarT]: ...
515
+ @overload
516
+ def diagonal(
517
+ a: ArrayLike,
518
+ offset: SupportsIndex = 0,
519
+ axis1: SupportsIndex = 0,
520
+ axis2: SupportsIndex = 1, # >= 2D array
521
+ ) -> NDArray[Any]: ...
522
+
523
+ # keep in sync with `ma.core.trace`
524
+ @overload
525
+ def trace(
526
+ a: ArrayLike, # >= 2D array
527
+ offset: SupportsIndex = 0,
528
+ axis1: SupportsIndex = 0,
529
+ axis2: SupportsIndex = 1,
530
+ dtype: DTypeLike | None = None,
531
+ out: None = None,
532
+ ) -> Any: ...
533
+ @overload
534
+ def trace(
535
+ a: ArrayLike, # >= 2D array
536
+ offset: SupportsIndex,
537
+ axis1: SupportsIndex,
538
+ axis2: SupportsIndex,
539
+ dtype: DTypeLike | None,
540
+ out: _ArrayT,
541
+ ) -> _ArrayT: ...
542
+ @overload
543
+ def trace(
544
+ a: ArrayLike, # >= 2D array
545
+ offset: SupportsIndex = 0,
546
+ axis1: SupportsIndex = 0,
547
+ axis2: SupportsIndex = 1,
548
+ dtype: DTypeLike | None = None,
549
+ *,
550
+ out: _ArrayT,
551
+ ) -> _ArrayT: ...
552
+
553
+ _Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
554
+
555
+ @overload
556
+ def ravel(a: _ArrayLike[_ScalarT], order: _OrderKACF = "C") -> _Array1D[_ScalarT]: ...
557
+ @overload
558
+ def ravel(a: bytes | _NestedSequence[bytes], order: _OrderKACF = "C") -> _Array1D[np.bytes_]: ...
559
+ @overload
560
+ def ravel(a: str | _NestedSequence[str], order: _OrderKACF = "C") -> _Array1D[np.str_]: ...
561
+ @overload
562
+ def ravel(a: bool | _NestedSequence[bool], order: _OrderKACF = "C") -> _Array1D[np.bool]: ...
563
+ @overload
564
+ def ravel(a: int | _NestedSequence[int], order: _OrderKACF = "C") -> _Array1D[np.int_ | Any]: ...
565
+ @overload
566
+ def ravel(a: float | _NestedSequence[float], order: _OrderKACF = "C") -> _Array1D[np.float64 | Any]: ...
567
+ @overload
568
+ def ravel(a: complex | _NestedSequence[complex], order: _OrderKACF = "C") -> _Array1D[np.complex128 | Any]: ...
569
+ @overload
570
+ def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype]: ...
571
+
572
+ def nonzero(a: _ArrayLike[Any]) -> tuple[np.ndarray[tuple[int], np.dtype[intp]], ...]: ...
573
+
574
+ # this prevents `Any` from being returned with Pyright
575
+ @overload
576
+ def shape(a: _SupportsShape[Never]) -> _AnyShape: ...
577
+ @overload
578
+ def shape(a: _SupportsShape[_ShapeT]) -> _ShapeT: ...
579
+ @overload
580
+ def shape(a: _PyScalar) -> tuple[()]: ...
581
+ # `collections.abc.Sequence` can't be used hesre, since `bytes` and `str` are
582
+ # subtypes of it, which would make the return types incompatible.
583
+ @overload
584
+ def shape(a: _PyArray[_PyScalar]) -> tuple[int]: ...
585
+ @overload
586
+ def shape(a: _PyArray[_PyArray[_PyScalar]]) -> tuple[int, int]: ...
587
+ # this overload will be skipped by typecheckers that don't support PEP 688
588
+ @overload
589
+ def shape(a: memoryview | bytearray) -> tuple[int]: ...
590
+ @overload
591
+ def shape(a: ArrayLike) -> _AnyShape: ...
592
+
593
+ @overload
594
+ def compress(
595
+ condition: _ArrayLikeBool_co, # 1D bool array
596
+ a: _ArrayLike[_ScalarT],
597
+ axis: SupportsIndex | None = None,
598
+ out: None = None,
599
+ ) -> NDArray[_ScalarT]: ...
600
+ @overload
601
+ def compress(
602
+ condition: _ArrayLikeBool_co, # 1D bool array
603
+ a: ArrayLike,
604
+ axis: SupportsIndex | None = None,
605
+ out: None = None,
606
+ ) -> NDArray[Any]: ...
607
+ @overload
608
+ def compress(
609
+ condition: _ArrayLikeBool_co, # 1D bool array
610
+ a: ArrayLike,
611
+ axis: SupportsIndex | None,
612
+ out: _ArrayT,
613
+ ) -> _ArrayT: ...
614
+ @overload
615
+ def compress(
616
+ condition: _ArrayLikeBool_co, # 1D bool array
617
+ a: ArrayLike,
618
+ axis: SupportsIndex | None = None,
619
+ *,
620
+ out: _ArrayT,
621
+ ) -> _ArrayT: ...
622
+
623
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
624
+ @overload
625
+ def clip(
626
+ a: _ScalarT,
627
+ a_min: ArrayLike | _NoValueType | None = ...,
628
+ a_max: ArrayLike | _NoValueType | None = ...,
629
+ out: None = None,
630
+ *,
631
+ min: ArrayLike | _NoValueType | None = ...,
632
+ max: ArrayLike | _NoValueType | None = ...,
633
+ dtype: None = None,
634
+ **kwargs: Unpack[_UFuncKwargs],
635
+ ) -> _ScalarT: ...
636
+ @overload
637
+ def clip(
638
+ a: _ScalarLike_co,
639
+ a_min: ArrayLike | _NoValueType | None = ...,
640
+ a_max: ArrayLike | _NoValueType | None = ...,
641
+ out: None = None,
642
+ *,
643
+ min: ArrayLike | _NoValueType | None = ...,
644
+ max: ArrayLike | _NoValueType | None = ...,
645
+ dtype: None = None,
646
+ **kwargs: Unpack[_UFuncKwargs],
647
+ ) -> Any: ...
648
+ @overload
649
+ def clip(
650
+ a: _ArrayLike[_ScalarT],
651
+ a_min: ArrayLike | _NoValueType | None = ...,
652
+ a_max: ArrayLike | _NoValueType | None = ...,
653
+ out: None = None,
654
+ *,
655
+ min: ArrayLike | _NoValueType | None = ...,
656
+ max: ArrayLike | _NoValueType | None = ...,
657
+ dtype: None = None,
658
+ **kwargs: Unpack[_UFuncKwargs],
659
+ ) -> NDArray[_ScalarT]: ...
660
+ @overload
661
+ def clip(
662
+ a: ArrayLike,
663
+ a_min: ArrayLike | _NoValueType | None = ...,
664
+ a_max: ArrayLike | _NoValueType | None = ...,
665
+ out: None = None,
666
+ *,
667
+ min: ArrayLike | _NoValueType | None = ...,
668
+ max: ArrayLike | _NoValueType | None = ...,
669
+ dtype: None = None,
670
+ **kwargs: Unpack[_UFuncKwargs],
671
+ ) -> NDArray[Any]: ...
672
+ @overload
673
+ def clip(
674
+ a: ArrayLike,
675
+ a_min: ArrayLike | None,
676
+ a_max: ArrayLike | None,
677
+ out: _ArrayT,
678
+ *,
679
+ min: ArrayLike | _NoValueType | None = ...,
680
+ max: ArrayLike | _NoValueType | None = ...,
681
+ dtype: DTypeLike | None = None,
682
+ **kwargs: Unpack[_UFuncKwargs],
683
+ ) -> _ArrayT: ...
684
+ @overload
685
+ def clip(
686
+ a: ArrayLike,
687
+ a_min: ArrayLike | _NoValueType | None = ...,
688
+ a_max: ArrayLike | _NoValueType | None = ...,
689
+ *,
690
+ out: _ArrayT,
691
+ min: ArrayLike | _NoValueType | None = ...,
692
+ max: ArrayLike | _NoValueType | None = ...,
693
+ dtype: DTypeLike | None = None,
694
+ **kwargs: Unpack[_UFuncKwargs],
695
+ ) -> _ArrayT: ...
696
+ @overload
697
+ def clip(
698
+ a: ArrayLike,
699
+ a_min: ArrayLike | _NoValueType | None = ...,
700
+ a_max: ArrayLike | _NoValueType | None = ...,
701
+ out: None = None,
702
+ *,
703
+ min: ArrayLike | _NoValueType | None = ...,
704
+ max: ArrayLike | _NoValueType | None = ...,
705
+ dtype: DTypeLike | None = None,
706
+ **kwargs: Unpack[_UFuncKwargs],
707
+ ) -> Any: ...
708
+
709
+ @overload
710
+ def sum(
711
+ a: _ArrayLike[_ScalarT],
712
+ axis: None = None,
713
+ dtype: None = None,
714
+ out: None = None,
715
+ keepdims: Literal[False] | _NoValueType = ...,
716
+ initial: _NumberLike_co | _NoValueType = ...,
717
+ where: _ArrayLikeBool_co | _NoValueType = ...,
718
+ ) -> _ScalarT: ...
719
+ @overload
720
+ def sum(
721
+ a: _ArrayLike[_ScalarT],
722
+ axis: None = None,
723
+ dtype: None = None,
724
+ out: None = None,
725
+ keepdims: bool | _NoValueType = ...,
726
+ initial: _NumberLike_co | _NoValueType = ...,
727
+ where: _ArrayLikeBool_co | _NoValueType = ...,
728
+ ) -> _ScalarT | NDArray[_ScalarT]: ...
729
+ @overload
730
+ def sum(
731
+ a: ArrayLike,
732
+ axis: None,
733
+ dtype: _DTypeLike[_ScalarT],
734
+ out: None = None,
735
+ keepdims: Literal[False] | _NoValueType = ...,
736
+ initial: _NumberLike_co | _NoValueType = ...,
737
+ where: _ArrayLikeBool_co | _NoValueType = ...,
738
+ ) -> _ScalarT: ...
739
+ @overload
740
+ def sum(
741
+ a: ArrayLike,
742
+ axis: None = None,
743
+ *,
744
+ dtype: _DTypeLike[_ScalarT],
745
+ out: None = None,
746
+ keepdims: Literal[False] | _NoValueType = ...,
747
+ initial: _NumberLike_co | _NoValueType = ...,
748
+ where: _ArrayLikeBool_co | _NoValueType = ...,
749
+ ) -> _ScalarT: ...
750
+ @overload
751
+ def sum(
752
+ a: ArrayLike,
753
+ axis: _ShapeLike | None,
754
+ dtype: _DTypeLike[_ScalarT],
755
+ out: None = None,
756
+ keepdims: bool | _NoValueType = ...,
757
+ initial: _NumberLike_co | _NoValueType = ...,
758
+ where: _ArrayLikeBool_co | _NoValueType = ...,
759
+ ) -> _ScalarT | NDArray[_ScalarT]: ...
760
+ @overload
761
+ def sum(
762
+ a: ArrayLike,
763
+ axis: _ShapeLike | None = None,
764
+ *,
765
+ dtype: _DTypeLike[_ScalarT],
766
+ out: None = None,
767
+ keepdims: bool | _NoValueType = ...,
768
+ initial: _NumberLike_co | _NoValueType = ...,
769
+ where: _ArrayLikeBool_co | _NoValueType = ...,
770
+ ) -> _ScalarT | NDArray[_ScalarT]: ...
771
+ @overload
772
+ def sum(
773
+ a: ArrayLike,
774
+ axis: _ShapeLike | None = None,
775
+ dtype: DTypeLike | None = None,
776
+ out: None = None,
777
+ keepdims: bool | _NoValueType = ...,
778
+ initial: _NumberLike_co | _NoValueType = ...,
779
+ where: _ArrayLikeBool_co | _NoValueType = ...,
780
+ ) -> Any: ...
781
+ @overload
782
+ def sum(
783
+ a: ArrayLike,
784
+ axis: _ShapeLike | None,
785
+ dtype: DTypeLike | None,
786
+ out: _ArrayT,
787
+ keepdims: bool | _NoValueType = ...,
788
+ initial: _NumberLike_co | _NoValueType = ...,
789
+ where: _ArrayLikeBool_co | _NoValueType = ...,
790
+ ) -> _ArrayT: ...
791
+ @overload
792
+ def sum(
793
+ a: ArrayLike,
794
+ axis: _ShapeLike | None = None,
795
+ dtype: DTypeLike | None = None,
796
+ *,
797
+ out: _ArrayT,
798
+ keepdims: bool | _NoValueType = ...,
799
+ initial: _NumberLike_co | _NoValueType = ...,
800
+ where: _ArrayLikeBool_co | _NoValueType = ...,
801
+ ) -> _ArrayT: ...
802
+
803
+ # keep in sync with `any`
804
+ @overload
805
+ def all(
806
+ a: ArrayLike | None,
807
+ axis: None = None,
808
+ out: None = None,
809
+ keepdims: Literal[False, 0] | _NoValueType = ...,
810
+ *,
811
+ where: _ArrayLikeBool_co | _NoValueType = ...,
812
+ ) -> np.bool: ...
813
+ @overload
814
+ def all(
815
+ a: ArrayLike | None,
816
+ axis: int | tuple[int, ...] | None = None,
817
+ out: None = None,
818
+ keepdims: _BoolLike_co | _NoValueType = ...,
819
+ *,
820
+ where: _ArrayLikeBool_co | _NoValueType = ...,
821
+ ) -> Incomplete: ...
822
+ @overload
823
+ def all(
824
+ a: ArrayLike | None,
825
+ axis: int | tuple[int, ...] | None,
826
+ out: _ArrayT,
827
+ keepdims: _BoolLike_co | _NoValueType = ...,
828
+ *,
829
+ where: _ArrayLikeBool_co | _NoValueType = ...,
830
+ ) -> _ArrayT: ...
831
+ @overload
832
+ def all(
833
+ a: ArrayLike | None,
834
+ axis: int | tuple[int, ...] | None = None,
835
+ *,
836
+ out: _ArrayT,
837
+ keepdims: _BoolLike_co | _NoValueType = ...,
838
+ where: _ArrayLikeBool_co | _NoValueType = ...,
839
+ ) -> _ArrayT: ...
840
+
841
+ # keep in sync with `all`
842
+ @overload
843
+ def any(
844
+ a: ArrayLike | None,
845
+ axis: None = None,
846
+ out: None = None,
847
+ keepdims: Literal[False, 0] | _NoValueType = ...,
848
+ *,
849
+ where: _ArrayLikeBool_co | _NoValueType = ...,
850
+ ) -> np.bool: ...
851
+ @overload
852
+ def any(
853
+ a: ArrayLike | None,
854
+ axis: int | tuple[int, ...] | None = None,
855
+ out: None = None,
856
+ keepdims: _BoolLike_co | _NoValueType = ...,
857
+ *,
858
+ where: _ArrayLikeBool_co | _NoValueType = ...,
859
+ ) -> Incomplete: ...
860
+ @overload
861
+ def any(
862
+ a: ArrayLike | None,
863
+ axis: int | tuple[int, ...] | None,
864
+ out: _ArrayT,
865
+ keepdims: _BoolLike_co | _NoValueType = ...,
866
+ *,
867
+ where: _ArrayLikeBool_co | _NoValueType = ...,
868
+ ) -> _ArrayT: ...
869
+ @overload
870
+ def any(
871
+ a: ArrayLike | None,
872
+ axis: int | tuple[int, ...] | None = None,
873
+ *,
874
+ out: _ArrayT,
875
+ keepdims: _BoolLike_co | _NoValueType = ...,
876
+ where: _ArrayLikeBool_co | _NoValueType = ...,
877
+ ) -> _ArrayT: ...
878
+
879
+ #
880
+ @overload
881
+ def cumsum(
882
+ a: _ArrayLike[_ScalarT],
883
+ axis: SupportsIndex | None = None,
884
+ dtype: None = None,
885
+ out: None = None,
886
+ ) -> NDArray[_ScalarT]: ...
887
+ @overload
888
+ def cumsum(
889
+ a: ArrayLike,
890
+ axis: SupportsIndex | None = None,
891
+ dtype: None = None,
892
+ out: None = None,
893
+ ) -> NDArray[Any]: ...
894
+ @overload
895
+ def cumsum(
896
+ a: ArrayLike,
897
+ axis: SupportsIndex | None,
898
+ dtype: _DTypeLike[_ScalarT],
899
+ out: None = None,
900
+ ) -> NDArray[_ScalarT]: ...
901
+ @overload
902
+ def cumsum(
903
+ a: ArrayLike,
904
+ axis: SupportsIndex | None = None,
905
+ *,
906
+ dtype: _DTypeLike[_ScalarT],
907
+ out: None = None,
908
+ ) -> NDArray[_ScalarT]: ...
909
+ @overload
910
+ def cumsum(
911
+ a: ArrayLike,
912
+ axis: SupportsIndex | None = None,
913
+ dtype: DTypeLike | None = None,
914
+ out: None = None,
915
+ ) -> NDArray[Any]: ...
916
+ @overload
917
+ def cumsum(
918
+ a: ArrayLike,
919
+ axis: SupportsIndex | None,
920
+ dtype: DTypeLike | None,
921
+ out: _ArrayT,
922
+ ) -> _ArrayT: ...
923
+ @overload
924
+ def cumsum(
925
+ a: ArrayLike,
926
+ axis: SupportsIndex | None = None,
927
+ dtype: DTypeLike | None = None,
928
+ *,
929
+ out: _ArrayT,
930
+ ) -> _ArrayT: ...
931
+
932
+ @overload
933
+ def cumulative_sum(
934
+ x: _ArrayLike[_ScalarT],
935
+ /,
936
+ *,
937
+ axis: SupportsIndex | None = None,
938
+ dtype: None = None,
939
+ out: None = None,
940
+ include_initial: bool = False,
941
+ ) -> NDArray[_ScalarT]: ...
942
+ @overload
943
+ def cumulative_sum(
944
+ x: ArrayLike,
945
+ /,
946
+ *,
947
+ axis: SupportsIndex | None = None,
948
+ dtype: None = None,
949
+ out: None = None,
950
+ include_initial: bool = False,
951
+ ) -> NDArray[Any]: ...
952
+ @overload
953
+ def cumulative_sum(
954
+ x: ArrayLike,
955
+ /,
956
+ *,
957
+ axis: SupportsIndex | None = None,
958
+ dtype: _DTypeLike[_ScalarT],
959
+ out: None = None,
960
+ include_initial: bool = False,
961
+ ) -> NDArray[_ScalarT]: ...
962
+ @overload
963
+ def cumulative_sum(
964
+ x: ArrayLike,
965
+ /,
966
+ *,
967
+ axis: SupportsIndex | None = None,
968
+ dtype: DTypeLike | None = None,
969
+ out: None = None,
970
+ include_initial: bool = False,
971
+ ) -> NDArray[Any]: ...
972
+ @overload
973
+ def cumulative_sum(
974
+ x: ArrayLike,
975
+ /,
976
+ *,
977
+ axis: SupportsIndex | None = None,
978
+ dtype: DTypeLike | None = None,
979
+ out: _ArrayT,
980
+ include_initial: bool = False,
981
+ ) -> _ArrayT: ...
982
+
983
+ @overload
984
+ def ptp(
985
+ a: _ArrayLike[_ScalarT],
986
+ axis: None = None,
987
+ out: None = None,
988
+ keepdims: Literal[False] | _NoValueType = ...,
989
+ ) -> _ScalarT: ...
990
+ @overload
991
+ def ptp(
992
+ a: ArrayLike,
993
+ axis: _ShapeLike | None = None,
994
+ out: None = None,
995
+ keepdims: bool | _NoValueType = ...,
996
+ ) -> Any: ...
997
+ @overload
998
+ def ptp(
999
+ a: ArrayLike,
1000
+ axis: _ShapeLike | None,
1001
+ out: _ArrayT,
1002
+ keepdims: bool | _NoValueType = ...,
1003
+ ) -> _ArrayT: ...
1004
+ @overload
1005
+ def ptp(
1006
+ a: ArrayLike,
1007
+ axis: _ShapeLike | None = None,
1008
+ *,
1009
+ out: _ArrayT,
1010
+ keepdims: bool | _NoValueType = ...,
1011
+ ) -> _ArrayT: ...
1012
+
1013
+ @overload
1014
+ def amax(
1015
+ a: _ArrayLike[_ScalarT],
1016
+ axis: None = None,
1017
+ out: None = None,
1018
+ keepdims: Literal[False] | _NoValueType = ...,
1019
+ initial: _NumberLike_co | _NoValueType = ...,
1020
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1021
+ ) -> _ScalarT: ...
1022
+ @overload
1023
+ def amax(
1024
+ a: ArrayLike,
1025
+ axis: _ShapeLike | None = None,
1026
+ out: None = None,
1027
+ keepdims: bool | _NoValueType = ...,
1028
+ initial: _NumberLike_co | _NoValueType = ...,
1029
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1030
+ ) -> Any: ...
1031
+ @overload
1032
+ def amax(
1033
+ a: ArrayLike,
1034
+ axis: _ShapeLike | None,
1035
+ out: _ArrayT,
1036
+ keepdims: bool | _NoValueType = ...,
1037
+ initial: _NumberLike_co | _NoValueType = ...,
1038
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1039
+ ) -> _ArrayT: ...
1040
+ @overload
1041
+ def amax(
1042
+ a: ArrayLike,
1043
+ axis: _ShapeLike | None = None,
1044
+ *,
1045
+ out: _ArrayT,
1046
+ keepdims: bool | _NoValueType = ...,
1047
+ initial: _NumberLike_co | _NoValueType = ...,
1048
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1049
+ ) -> _ArrayT: ...
1050
+
1051
+ @overload
1052
+ def amin(
1053
+ a: _ArrayLike[_ScalarT],
1054
+ axis: None = None,
1055
+ out: None = None,
1056
+ keepdims: Literal[False] | _NoValueType = ...,
1057
+ initial: _NumberLike_co | _NoValueType = ...,
1058
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1059
+ ) -> _ScalarT: ...
1060
+ @overload
1061
+ def amin(
1062
+ a: ArrayLike,
1063
+ axis: _ShapeLike | None = None,
1064
+ out: None = None,
1065
+ keepdims: bool | _NoValueType = ...,
1066
+ initial: _NumberLike_co | _NoValueType = ...,
1067
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1068
+ ) -> Any: ...
1069
+ @overload
1070
+ def amin(
1071
+ a: ArrayLike,
1072
+ axis: _ShapeLike | None,
1073
+ out: _ArrayT,
1074
+ keepdims: bool | _NoValueType = ...,
1075
+ initial: _NumberLike_co | _NoValueType = ...,
1076
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1077
+ ) -> _ArrayT: ...
1078
+ @overload
1079
+ def amin(
1080
+ a: ArrayLike,
1081
+ axis: _ShapeLike | None = None,
1082
+ *,
1083
+ out: _ArrayT,
1084
+ keepdims: bool | _NoValueType = ...,
1085
+ initial: _NumberLike_co | _NoValueType = ...,
1086
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1087
+ ) -> _ArrayT: ...
1088
+
1089
+ # TODO: `np.prod()``: For object arrays `initial` does not necessarily
1090
+ # have to be a numerical scalar.
1091
+ # The only requirement is that it is compatible
1092
+ # with the `.__mul__()` method(s) of the passed array's elements.
1093
+ # Note that the same situation holds for all wrappers around
1094
+ # `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`).
1095
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
1096
+ @overload
1097
+ def prod(
1098
+ a: _ArrayLikeBool_co,
1099
+ axis: None = None,
1100
+ dtype: None = None,
1101
+ out: None = None,
1102
+ keepdims: Literal[False] | _NoValueType = ...,
1103
+ initial: _NumberLike_co | _NoValueType = ...,
1104
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1105
+ ) -> int_: ...
1106
+ @overload
1107
+ def prod(
1108
+ a: _ArrayLikeUInt_co,
1109
+ axis: None = None,
1110
+ dtype: None = None,
1111
+ out: None = None,
1112
+ keepdims: Literal[False] | _NoValueType = ...,
1113
+ initial: _NumberLike_co | _NoValueType = ...,
1114
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1115
+ ) -> uint64: ...
1116
+ @overload
1117
+ def prod(
1118
+ a: _ArrayLikeInt_co,
1119
+ axis: None = None,
1120
+ dtype: None = None,
1121
+ out: None = None,
1122
+ keepdims: Literal[False] | _NoValueType = ...,
1123
+ initial: _NumberLike_co | _NoValueType = ...,
1124
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1125
+ ) -> int64: ...
1126
+ @overload
1127
+ def prod(
1128
+ a: _ArrayLikeFloat_co,
1129
+ axis: None = None,
1130
+ dtype: None = None,
1131
+ out: None = None,
1132
+ keepdims: Literal[False] | _NoValueType = ...,
1133
+ initial: _NumberLike_co | _NoValueType = ...,
1134
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1135
+ ) -> floating: ...
1136
+ @overload
1137
+ def prod(
1138
+ a: _ArrayLikeComplex_co,
1139
+ axis: None = None,
1140
+ dtype: None = None,
1141
+ out: None = None,
1142
+ keepdims: Literal[False] | _NoValueType = ...,
1143
+ initial: _NumberLike_co | _NoValueType = ...,
1144
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1145
+ ) -> complexfloating: ...
1146
+ @overload
1147
+ def prod(
1148
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1149
+ axis: _ShapeLike | None = None,
1150
+ dtype: None = None,
1151
+ out: None = None,
1152
+ keepdims: bool | _NoValueType = ...,
1153
+ initial: _NumberLike_co | _NoValueType = ...,
1154
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1155
+ ) -> Any: ...
1156
+ @overload
1157
+ def prod(
1158
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1159
+ axis: None,
1160
+ dtype: _DTypeLike[_ScalarT],
1161
+ out: None = None,
1162
+ keepdims: Literal[False] | _NoValueType = ...,
1163
+ initial: _NumberLike_co | _NoValueType = ...,
1164
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1165
+ ) -> _ScalarT: ...
1166
+ @overload
1167
+ def prod(
1168
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1169
+ axis: None = None,
1170
+ *,
1171
+ dtype: _DTypeLike[_ScalarT],
1172
+ out: None = None,
1173
+ keepdims: Literal[False] | _NoValueType = ...,
1174
+ initial: _NumberLike_co | _NoValueType = ...,
1175
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1176
+ ) -> _ScalarT: ...
1177
+ @overload
1178
+ def prod(
1179
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1180
+ axis: _ShapeLike | None = None,
1181
+ dtype: DTypeLike | None = None,
1182
+ out: None = None,
1183
+ keepdims: bool | _NoValueType = ...,
1184
+ initial: _NumberLike_co | _NoValueType = ...,
1185
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1186
+ ) -> Any: ...
1187
+ @overload
1188
+ def prod(
1189
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1190
+ axis: _ShapeLike | None,
1191
+ dtype: DTypeLike | None,
1192
+ out: _ArrayT,
1193
+ keepdims: bool | _NoValueType = ...,
1194
+ initial: _NumberLike_co | _NoValueType = ...,
1195
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1196
+ ) -> _ArrayT: ...
1197
+ @overload
1198
+ def prod(
1199
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1200
+ axis: _ShapeLike | None = None,
1201
+ dtype: DTypeLike | None = None,
1202
+ *,
1203
+ out: _ArrayT,
1204
+ keepdims: bool | _NoValueType = ...,
1205
+ initial: _NumberLike_co | _NoValueType = ...,
1206
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1207
+ ) -> _ArrayT: ...
1208
+
1209
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
1210
+ @overload
1211
+ def cumprod(
1212
+ a: _ArrayLikeBool_co,
1213
+ axis: SupportsIndex | None = None,
1214
+ dtype: None = None,
1215
+ out: None = None,
1216
+ ) -> NDArray[int_]: ...
1217
+ @overload
1218
+ def cumprod(
1219
+ a: _ArrayLikeUInt_co,
1220
+ axis: SupportsIndex | None = None,
1221
+ dtype: None = None,
1222
+ out: None = None,
1223
+ ) -> NDArray[uint64]: ...
1224
+ @overload
1225
+ def cumprod(
1226
+ a: _ArrayLikeInt_co,
1227
+ axis: SupportsIndex | None = None,
1228
+ dtype: None = None,
1229
+ out: None = None,
1230
+ ) -> NDArray[int64]: ...
1231
+ @overload
1232
+ def cumprod(
1233
+ a: _ArrayLikeFloat_co,
1234
+ axis: SupportsIndex | None = None,
1235
+ dtype: None = None,
1236
+ out: None = None,
1237
+ ) -> NDArray[floating]: ...
1238
+ @overload
1239
+ def cumprod(
1240
+ a: _ArrayLikeComplex_co,
1241
+ axis: SupportsIndex | None = None,
1242
+ dtype: None = None,
1243
+ out: None = None,
1244
+ ) -> NDArray[complexfloating]: ...
1245
+ @overload
1246
+ def cumprod(
1247
+ a: _ArrayLikeObject_co,
1248
+ axis: SupportsIndex | None = None,
1249
+ dtype: None = None,
1250
+ out: None = None,
1251
+ ) -> NDArray[object_]: ...
1252
+ @overload
1253
+ def cumprod(
1254
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1255
+ axis: SupportsIndex | None,
1256
+ dtype: _DTypeLike[_ScalarT],
1257
+ out: None = None,
1258
+ ) -> NDArray[_ScalarT]: ...
1259
+ @overload
1260
+ def cumprod(
1261
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1262
+ axis: SupportsIndex | None = None,
1263
+ *,
1264
+ dtype: _DTypeLike[_ScalarT],
1265
+ out: None = None,
1266
+ ) -> NDArray[_ScalarT]: ...
1267
+ @overload
1268
+ def cumprod(
1269
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1270
+ axis: SupportsIndex | None = None,
1271
+ dtype: DTypeLike | None = None,
1272
+ out: None = None,
1273
+ ) -> NDArray[Any]: ...
1274
+ @overload
1275
+ def cumprod(
1276
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1277
+ axis: SupportsIndex | None,
1278
+ dtype: DTypeLike | None,
1279
+ out: _ArrayT,
1280
+ ) -> _ArrayT: ...
1281
+ @overload
1282
+ def cumprod(
1283
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1284
+ axis: SupportsIndex | None = None,
1285
+ dtype: DTypeLike | None = None,
1286
+ *,
1287
+ out: _ArrayT,
1288
+ ) -> _ArrayT: ...
1289
+
1290
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
1291
+ @overload
1292
+ def cumulative_prod(
1293
+ x: _ArrayLikeBool_co,
1294
+ /,
1295
+ *,
1296
+ axis: SupportsIndex | None = None,
1297
+ dtype: None = None,
1298
+ out: None = None,
1299
+ include_initial: bool = False,
1300
+ ) -> NDArray[int_]: ...
1301
+ @overload
1302
+ def cumulative_prod(
1303
+ x: _ArrayLikeUInt_co,
1304
+ /,
1305
+ *,
1306
+ axis: SupportsIndex | None = None,
1307
+ dtype: None = None,
1308
+ out: None = None,
1309
+ include_initial: bool = False,
1310
+ ) -> NDArray[uint64]: ...
1311
+ @overload
1312
+ def cumulative_prod(
1313
+ x: _ArrayLikeInt_co,
1314
+ /,
1315
+ *,
1316
+ axis: SupportsIndex | None = None,
1317
+ dtype: None = None,
1318
+ out: None = None,
1319
+ include_initial: bool = False,
1320
+ ) -> NDArray[int64]: ...
1321
+ @overload
1322
+ def cumulative_prod(
1323
+ x: _ArrayLikeFloat_co,
1324
+ /,
1325
+ *,
1326
+ axis: SupportsIndex | None = None,
1327
+ dtype: None = None,
1328
+ out: None = None,
1329
+ include_initial: bool = False,
1330
+ ) -> NDArray[floating]: ...
1331
+ @overload
1332
+ def cumulative_prod(
1333
+ x: _ArrayLikeComplex_co,
1334
+ /,
1335
+ *,
1336
+ axis: SupportsIndex | None = None,
1337
+ dtype: None = None,
1338
+ out: None = None,
1339
+ include_initial: bool = False,
1340
+ ) -> NDArray[complexfloating]: ...
1341
+ @overload
1342
+ def cumulative_prod(
1343
+ x: _ArrayLikeObject_co,
1344
+ /,
1345
+ *,
1346
+ axis: SupportsIndex | None = None,
1347
+ dtype: None = None,
1348
+ out: None = None,
1349
+ include_initial: bool = False,
1350
+ ) -> NDArray[object_]: ...
1351
+ @overload
1352
+ def cumulative_prod(
1353
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1354
+ /,
1355
+ *,
1356
+ axis: SupportsIndex | None = None,
1357
+ dtype: _DTypeLike[_ScalarT],
1358
+ out: None = None,
1359
+ include_initial: bool = False,
1360
+ ) -> NDArray[_ScalarT]: ...
1361
+ @overload
1362
+ def cumulative_prod(
1363
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1364
+ /,
1365
+ *,
1366
+ axis: SupportsIndex | None = None,
1367
+ dtype: DTypeLike | None = None,
1368
+ out: None = None,
1369
+ include_initial: bool = False,
1370
+ ) -> NDArray[Any]: ...
1371
+ @overload
1372
+ def cumulative_prod(
1373
+ x: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1374
+ /,
1375
+ *,
1376
+ axis: SupportsIndex | None = None,
1377
+ dtype: DTypeLike | None = None,
1378
+ out: _ArrayT,
1379
+ include_initial: bool = False,
1380
+ ) -> _ArrayT: ...
1381
+
1382
+ def ndim(a: ArrayLike) -> int: ...
1383
+
1384
+ def size(a: ArrayLike, axis: int | tuple[int, ...] | None = None) -> int: ...
1385
+
1386
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
1387
+ @overload
1388
+ def around(
1389
+ a: _BoolLike_co,
1390
+ decimals: SupportsIndex = 0,
1391
+ out: None = None,
1392
+ ) -> float16: ...
1393
+ @overload
1394
+ def around(
1395
+ a: _NumberOrObjectT,
1396
+ decimals: SupportsIndex = 0,
1397
+ out: None = None,
1398
+ ) -> _NumberOrObjectT: ...
1399
+ @overload
1400
+ def around(
1401
+ a: _ComplexLike_co | object_,
1402
+ decimals: SupportsIndex = 0,
1403
+ out: None = None,
1404
+ ) -> Any: ...
1405
+ @overload
1406
+ def around(
1407
+ a: _ArrayLikeBool_co,
1408
+ decimals: SupportsIndex = 0,
1409
+ out: None = None,
1410
+ ) -> NDArray[float16]: ...
1411
+ @overload
1412
+ def around(
1413
+ a: _ArrayLike[_NumberOrObjectT],
1414
+ decimals: SupportsIndex = 0,
1415
+ out: None = None,
1416
+ ) -> NDArray[_NumberOrObjectT]: ...
1417
+ @overload
1418
+ def around(
1419
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1420
+ decimals: SupportsIndex = 0,
1421
+ out: None = None,
1422
+ ) -> NDArray[Any]: ...
1423
+ @overload
1424
+ def around(
1425
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1426
+ decimals: SupportsIndex,
1427
+ out: _ArrayT,
1428
+ ) -> _ArrayT: ...
1429
+ @overload
1430
+ def around(
1431
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1432
+ decimals: SupportsIndex = 0,
1433
+ *,
1434
+ out: _ArrayT,
1435
+ ) -> _ArrayT: ...
1436
+
1437
+ # TODO: Fix overlapping overloads: https://github.com/numpy/numpy/issues/27032
1438
+ @overload
1439
+ def mean(
1440
+ a: _ArrayLikeFloat_co,
1441
+ axis: None = None,
1442
+ dtype: None = None,
1443
+ out: None = None,
1444
+ keepdims: Literal[False] | _NoValueType = ...,
1445
+ *,
1446
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1447
+ ) -> floating: ...
1448
+ @overload
1449
+ def mean(
1450
+ a: _ArrayLikeComplex_co,
1451
+ axis: None = None,
1452
+ dtype: None = None,
1453
+ out: None = None,
1454
+ keepdims: Literal[False] | _NoValueType = ...,
1455
+ *,
1456
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1457
+ ) -> complexfloating: ...
1458
+ @overload
1459
+ def mean(
1460
+ a: _ArrayLike[np.timedelta64],
1461
+ axis: None = None,
1462
+ dtype: None = None,
1463
+ out: None = None,
1464
+ keepdims: Literal[False] | _NoValueType = ...,
1465
+ *,
1466
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1467
+ ) -> timedelta64: ...
1468
+ @overload
1469
+ def mean(
1470
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1471
+ axis: _ShapeLike | None,
1472
+ dtype: DTypeLike | None,
1473
+ out: _ArrayT,
1474
+ keepdims: bool | _NoValueType = ...,
1475
+ *,
1476
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1477
+ ) -> _ArrayT: ...
1478
+ @overload
1479
+ def mean(
1480
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1481
+ axis: _ShapeLike | None = None,
1482
+ dtype: DTypeLike | None = None,
1483
+ *,
1484
+ out: _ArrayT,
1485
+ keepdims: bool | _NoValueType = ...,
1486
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1487
+ ) -> _ArrayT: ...
1488
+ @overload
1489
+ def mean(
1490
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1491
+ axis: None,
1492
+ dtype: _DTypeLike[_ScalarT],
1493
+ out: None = None,
1494
+ keepdims: Literal[False] | _NoValueType = ...,
1495
+ *,
1496
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1497
+ ) -> _ScalarT: ...
1498
+ @overload
1499
+ def mean(
1500
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1501
+ axis: None = None,
1502
+ *,
1503
+ dtype: _DTypeLike[_ScalarT],
1504
+ out: None = None,
1505
+ keepdims: Literal[False] | _NoValueType = ...,
1506
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1507
+ ) -> _ScalarT: ...
1508
+ @overload
1509
+ def mean(
1510
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1511
+ axis: _ShapeLike | None,
1512
+ dtype: _DTypeLike[_ScalarT],
1513
+ out: None,
1514
+ keepdims: Literal[True, 1],
1515
+ *,
1516
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1517
+ ) -> NDArray[_ScalarT]: ...
1518
+ @overload
1519
+ def mean(
1520
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1521
+ axis: _ShapeLike | None,
1522
+ dtype: _DTypeLike[_ScalarT],
1523
+ out: None = None,
1524
+ *,
1525
+ keepdims: bool | _NoValueType = ...,
1526
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1527
+ ) -> _ScalarT | NDArray[_ScalarT]: ...
1528
+ @overload
1529
+ def mean(
1530
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1531
+ axis: _ShapeLike | None = None,
1532
+ *,
1533
+ dtype: _DTypeLike[_ScalarT],
1534
+ out: None = None,
1535
+ keepdims: bool | _NoValueType = ...,
1536
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1537
+ ) -> _ScalarT | NDArray[_ScalarT]: ...
1538
+ @overload
1539
+ def mean(
1540
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1541
+ axis: _ShapeLike | None = None,
1542
+ dtype: DTypeLike | None = None,
1543
+ out: None = None,
1544
+ keepdims: bool | _NoValueType = ...,
1545
+ *,
1546
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1547
+ ) -> Incomplete: ...
1548
+
1549
+ @overload
1550
+ def std(
1551
+ a: _ArrayLikeComplex_co,
1552
+ axis: None = None,
1553
+ dtype: None = None,
1554
+ out: None = None,
1555
+ ddof: float = 0,
1556
+ keepdims: Literal[False] | _NoValueType = ...,
1557
+ *,
1558
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1559
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
1560
+ correction: float | _NoValueType = ...,
1561
+ ) -> floating: ...
1562
+ @overload
1563
+ def std(
1564
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1565
+ axis: _ShapeLike | None = None,
1566
+ dtype: None = None,
1567
+ out: None = None,
1568
+ ddof: float = 0,
1569
+ keepdims: bool | _NoValueType = ...,
1570
+ *,
1571
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1572
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1573
+ correction: float | _NoValueType = ...,
1574
+ ) -> Any: ...
1575
+ @overload
1576
+ def std(
1577
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1578
+ axis: None,
1579
+ dtype: _DTypeLike[_ScalarT],
1580
+ out: None = None,
1581
+ ddof: float = 0,
1582
+ keepdims: Literal[False] | _NoValueType = ...,
1583
+ *,
1584
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1585
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1586
+ correction: float | _NoValueType = ...,
1587
+ ) -> _ScalarT: ...
1588
+ @overload
1589
+ def std(
1590
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1591
+ axis: None = None,
1592
+ *,
1593
+ dtype: _DTypeLike[_ScalarT],
1594
+ out: None = None,
1595
+ ddof: float = 0,
1596
+ keepdims: Literal[False] | _NoValueType = ...,
1597
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1598
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1599
+ correction: float | _NoValueType = ...,
1600
+ ) -> _ScalarT: ...
1601
+ @overload
1602
+ def std(
1603
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1604
+ axis: _ShapeLike | None = None,
1605
+ dtype: DTypeLike | None = None,
1606
+ out: None = None,
1607
+ ddof: float = 0,
1608
+ keepdims: bool | _NoValueType = ...,
1609
+ *,
1610
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1611
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1612
+ correction: float | _NoValueType = ...,
1613
+ ) -> Any: ...
1614
+ @overload
1615
+ def std(
1616
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1617
+ axis: _ShapeLike | None,
1618
+ dtype: DTypeLike | None,
1619
+ out: _ArrayT,
1620
+ ddof: float = 0,
1621
+ keepdims: bool | _NoValueType = ...,
1622
+ *,
1623
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1624
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1625
+ correction: float | _NoValueType = ...,
1626
+ ) -> _ArrayT: ...
1627
+ @overload
1628
+ def std(
1629
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1630
+ axis: _ShapeLike | None = None,
1631
+ dtype: DTypeLike | None = None,
1632
+ *,
1633
+ out: _ArrayT,
1634
+ ddof: float = 0,
1635
+ keepdims: bool | _NoValueType = ...,
1636
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1637
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1638
+ correction: float | _NoValueType = ...,
1639
+ ) -> _ArrayT: ...
1640
+
1641
+ @overload
1642
+ def var(
1643
+ a: _ArrayLikeComplex_co,
1644
+ axis: None = None,
1645
+ dtype: None = None,
1646
+ out: None = None,
1647
+ ddof: float = 0,
1648
+ keepdims: Literal[False] | _NoValueType = ...,
1649
+ *,
1650
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1651
+ mean: _ArrayLikeComplex_co | _NoValueType = ...,
1652
+ correction: float | _NoValueType = ...,
1653
+ ) -> floating: ...
1654
+ @overload
1655
+ def var(
1656
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1657
+ axis: _ShapeLike | None = None,
1658
+ dtype: None = None,
1659
+ out: None = None,
1660
+ ddof: float = 0,
1661
+ keepdims: bool | _NoValueType = ...,
1662
+ *,
1663
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1664
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1665
+ correction: float | _NoValueType = ...,
1666
+ ) -> Any: ...
1667
+ @overload
1668
+ def var(
1669
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1670
+ axis: None,
1671
+ dtype: _DTypeLike[_ScalarT],
1672
+ out: None = None,
1673
+ ddof: float = 0,
1674
+ keepdims: Literal[False] | _NoValueType = ...,
1675
+ *,
1676
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1677
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1678
+ correction: float | _NoValueType = ...,
1679
+ ) -> _ScalarT: ...
1680
+ @overload
1681
+ def var(
1682
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1683
+ axis: None = None,
1684
+ *,
1685
+ dtype: _DTypeLike[_ScalarT],
1686
+ out: None = None,
1687
+ ddof: float = 0,
1688
+ keepdims: Literal[False] | _NoValueType = ...,
1689
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1690
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1691
+ correction: float | _NoValueType = ...,
1692
+ ) -> _ScalarT: ...
1693
+ @overload
1694
+ def var(
1695
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1696
+ axis: _ShapeLike | None = None,
1697
+ dtype: DTypeLike | None = None,
1698
+ out: None = None,
1699
+ ddof: float = 0,
1700
+ keepdims: bool | _NoValueType = ...,
1701
+ *,
1702
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1703
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1704
+ correction: float | _NoValueType = ...,
1705
+ ) -> Any: ...
1706
+ @overload
1707
+ def var(
1708
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1709
+ axis: _ShapeLike | None,
1710
+ dtype: DTypeLike | None,
1711
+ out: _ArrayT,
1712
+ ddof: float = 0,
1713
+ keepdims: bool | _NoValueType = ...,
1714
+ *,
1715
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1716
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1717
+ correction: float | _NoValueType = ...,
1718
+ ) -> _ArrayT: ...
1719
+ @overload
1720
+ def var(
1721
+ a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
1722
+ axis: _ShapeLike | None = None,
1723
+ dtype: DTypeLike | None = None,
1724
+ *,
1725
+ out: _ArrayT,
1726
+ ddof: float = 0,
1727
+ keepdims: bool | _NoValueType = ...,
1728
+ where: _ArrayLikeBool_co | _NoValueType = ...,
1729
+ mean: _ArrayLikeComplex_co | _ArrayLikeObject_co | _NoValueType = ...,
1730
+ correction: float | _NoValueType = ...,
1731
+ ) -> _ArrayT: ...
1732
+
1733
+ max = amax
1734
+ min = amin
1735
+ round = around
python/user_packages/Python313/site-packages/numpy/_core/function_base.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import operator
4
+ import types
5
+ import warnings
6
+
7
+ import numpy as np
8
+ from numpy._core import overrides
9
+ from numpy._core._multiarray_umath import _array_converter
10
+ from numpy._core.multiarray import add_docstring
11
+
12
+ from . import numeric as _nx
13
+ from .numeric import asanyarray, nan, ndim, result_type
14
+
15
+ __all__ = ['logspace', 'linspace', 'geomspace']
16
+
17
+
18
+ array_function_dispatch = functools.partial(
19
+ overrides.array_function_dispatch, module='numpy')
20
+
21
+
22
+ def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None,
23
+ dtype=None, axis=None, *, device=None):
24
+ return (start, stop)
25
+
26
+
27
+ @array_function_dispatch(_linspace_dispatcher)
28
+ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
29
+ axis=0, *, device=None):
30
+ """
31
+ Return evenly spaced numbers over a specified interval.
32
+
33
+ Returns `num` evenly spaced samples, calculated over the
34
+ interval [`start`, `stop`].
35
+
36
+ The endpoint of the interval can optionally be excluded.
37
+
38
+ .. versionchanged:: 1.20.0
39
+ Values are rounded towards ``-inf`` instead of ``0`` when an
40
+ integer ``dtype`` is specified. The old behavior can
41
+ still be obtained with ``np.linspace(start, stop, num).astype(int)``
42
+
43
+ Parameters
44
+ ----------
45
+ start : array_like
46
+ The starting value of the sequence.
47
+ stop : array_like
48
+ The end value of the sequence, unless `endpoint` is set to False.
49
+ In that case, the sequence consists of all but the last of ``num + 1``
50
+ evenly spaced samples, so that `stop` is excluded. Note that the step
51
+ size changes when `endpoint` is False.
52
+ num : int, optional
53
+ Number of samples to generate. Default is 50. Must be non-negative.
54
+ endpoint : bool, optional
55
+ If True, `stop` is the last sample. Otherwise, it is not included.
56
+ Default is True.
57
+ retstep : bool, optional
58
+ If True, return (`samples`, `step`), where `step` is the spacing
59
+ between samples.
60
+ dtype : dtype, optional
61
+ The type of the output array. If `dtype` is not given, the data type
62
+ is inferred from `start` and `stop`. The inferred dtype will never be
63
+ an integer; `float` is chosen even if the arguments would produce an
64
+ array of integers.
65
+ axis : int, optional
66
+ The axis in the result to store the samples. Relevant only if start
67
+ or stop are array-like. By default (0), the samples will be along a
68
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
69
+ device : str, optional
70
+ The device on which to place the created array. Default: None.
71
+ For Array-API interoperability only, so must be ``"cpu"`` if passed.
72
+
73
+ .. versionadded:: 2.0.0
74
+
75
+ Returns
76
+ -------
77
+ samples : ndarray
78
+ There are `num` equally spaced samples in the closed interval
79
+ ``[start, stop]`` or the half-open interval ``[start, stop)``
80
+ (depending on whether `endpoint` is True or False).
81
+ step : float, optional
82
+ Only returned if `retstep` is True
83
+
84
+ Size of spacing between samples.
85
+
86
+
87
+ See Also
88
+ --------
89
+ arange : Similar to `linspace`, but uses a step size (instead of the
90
+ number of samples).
91
+ geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
92
+ scale (a geometric progression).
93
+ logspace : Similar to `geomspace`, but with the end points specified as
94
+ logarithms.
95
+ :ref:`how-to-partition`
96
+
97
+ Examples
98
+ --------
99
+ >>> import numpy as np
100
+ >>> np.linspace(2.0, 3.0, num=5)
101
+ array([2. , 2.25, 2.5 , 2.75, 3. ])
102
+ >>> np.linspace(2.0, 3.0, num=5, endpoint=False)
103
+ array([2. , 2.2, 2.4, 2.6, 2.8])
104
+ >>> np.linspace(2.0, 3.0, num=5, retstep=True)
105
+ (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
106
+
107
+ Graphical illustration:
108
+
109
+ >>> import matplotlib.pyplot as plt
110
+ >>> N = 8
111
+ >>> y = np.zeros(N)
112
+ >>> x1 = np.linspace(0, 10, N, endpoint=True)
113
+ >>> x2 = np.linspace(0, 10, N, endpoint=False)
114
+ >>> plt.plot(x1, y, 'o')
115
+ [<matplotlib.lines.Line2D object at 0x...>]
116
+ >>> plt.plot(x2, y + 0.5, 'o')
117
+ [<matplotlib.lines.Line2D object at 0x...>]
118
+ >>> plt.ylim([-0.5, 1])
119
+ (-0.5, 1)
120
+ >>> plt.show()
121
+
122
+ """
123
+ num = operator.index(num)
124
+ if num < 0:
125
+ raise ValueError(
126
+ f"Number of samples, {num}, must be non-negative."
127
+ )
128
+ div = (num - 1) if endpoint else num
129
+
130
+ conv = _array_converter(start, stop)
131
+ start, stop = conv.as_arrays()
132
+ dt = conv.result_type(ensure_inexact=True)
133
+
134
+ if dtype is None:
135
+ dtype = dt
136
+ integer_dtype = False
137
+ else:
138
+ integer_dtype = _nx.issubdtype(dtype, _nx.integer)
139
+
140
+ # Use `dtype=type(dt)` to enforce a floating point evaluation:
141
+ delta = np.subtract(stop, start, dtype=type(dt))
142
+ y = _nx.arange(
143
+ 0, num, dtype=dt, device=device
144
+ ).reshape((-1,) + (1,) * ndim(delta))
145
+
146
+ # In-place multiplication y *= delta/div is faster, but prevents
147
+ # the multiplicant from overriding what class is produced, and thus
148
+ # prevents, e.g. use of Quantities, see gh-7142. Hence, we multiply
149
+ # in place only for standard scalar types.
150
+ if div > 0:
151
+ _mult_inplace = _nx.isscalar(delta)
152
+ step = delta / div
153
+ any_step_zero = (
154
+ step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any())
155
+ if any_step_zero:
156
+ # Special handling for denormal numbers, gh-5437
157
+ y /= div
158
+ if _mult_inplace:
159
+ y *= delta
160
+ else:
161
+ y = y * delta
162
+ elif _mult_inplace:
163
+ y *= step
164
+ else:
165
+ y = y * step
166
+ else:
167
+ # sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
168
+ # have an undefined step
169
+ step = nan
170
+ # Multiply with delta to allow possible override of output class.
171
+ y = y * delta
172
+
173
+ y += start
174
+
175
+ if endpoint and num > 1:
176
+ y[-1, ...] = stop
177
+
178
+ if axis != 0:
179
+ y = _nx.moveaxis(y, 0, axis)
180
+
181
+ if integer_dtype:
182
+ _nx.floor(y, out=y)
183
+
184
+ y = conv.wrap(y.astype(dtype, copy=False))
185
+ if retstep:
186
+ return y, step
187
+ else:
188
+ return y
189
+
190
+
191
+ def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None,
192
+ dtype=None, axis=None):
193
+ return (start, stop, base)
194
+
195
+
196
+ @array_function_dispatch(_logspace_dispatcher)
197
+ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
198
+ axis=0):
199
+ """
200
+ Return numbers spaced evenly on a log scale.
201
+
202
+ In linear space, the sequence starts at ``base ** start``
203
+ (`base` to the power of `start`) and ends with ``base ** stop``
204
+ (see `endpoint` below).
205
+
206
+ .. versionchanged:: 1.25.0
207
+ Non-scalar 'base` is now supported
208
+
209
+ Parameters
210
+ ----------
211
+ start : array_like
212
+ ``base ** start`` is the starting value of the sequence.
213
+ stop : array_like
214
+ ``base ** stop`` is the final value of the sequence, unless `endpoint`
215
+ is False. In that case, ``num + 1`` values are spaced over the
216
+ interval in log-space, of which all but the last (a sequence of
217
+ length `num`) are returned.
218
+ num : integer, optional
219
+ Number of samples to generate. Default is 50.
220
+ endpoint : boolean, optional
221
+ If true, `stop` is the last sample. Otherwise, it is not included.
222
+ Default is True.
223
+ base : array_like, optional
224
+ The base of the log space. The step size between the elements in
225
+ ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
226
+ Default is 10.0.
227
+ dtype : dtype
228
+ The type of the output array. If `dtype` is not given, the data type
229
+ is inferred from `start` and `stop`. The inferred type will never be
230
+ an integer; `float` is chosen even if the arguments would produce an
231
+ array of integers.
232
+ axis : int, optional
233
+ The axis in the result to store the samples. Relevant only if start,
234
+ stop, or base are array-like. By default (0), the samples will be
235
+ along a new axis inserted at the beginning. Use -1 to get an axis at
236
+ the end.
237
+
238
+ Returns
239
+ -------
240
+ samples : ndarray
241
+ `num` samples, equally spaced on a log scale.
242
+
243
+ See Also
244
+ --------
245
+ arange : Similar to linspace, with the step size specified instead of the
246
+ number of samples. Note that, when used with a float endpoint, the
247
+ endpoint may or may not be included.
248
+ linspace : Similar to logspace, but with the samples uniformly distributed
249
+ in linear space, instead of log space.
250
+ geomspace : Similar to logspace, but with endpoints specified directly.
251
+ :ref:`how-to-partition`
252
+
253
+ Notes
254
+ -----
255
+ If base is a scalar, logspace is equivalent to the code
256
+
257
+ >>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
258
+ ... # doctest: +SKIP
259
+ >>> power(base, y).astype(dtype)
260
+ ... # doctest: +SKIP
261
+
262
+ Examples
263
+ --------
264
+ >>> import numpy as np
265
+ >>> np.logspace(2.0, 3.0, num=4)
266
+ array([ 100. , 215.443469 , 464.15888336, 1000. ])
267
+ >>> np.logspace(2.0, 3.0, num=4, endpoint=False)
268
+ array([100. , 177.827941 , 316.22776602, 562.34132519])
269
+ >>> np.logspace(2.0, 3.0, num=4, base=2.0)
270
+ array([4. , 5.0396842 , 6.34960421, 8. ])
271
+ >>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
272
+ array([[ 4. , 5.0396842 , 6.34960421, 8. ],
273
+ [ 9. , 12.98024613, 18.72075441, 27. ]])
274
+
275
+ Graphical illustration:
276
+
277
+ >>> import matplotlib.pyplot as plt
278
+ >>> N = 10
279
+ >>> x1 = np.logspace(0.1, 1, N, endpoint=True)
280
+ >>> x2 = np.logspace(0.1, 1, N, endpoint=False)
281
+ >>> y = np.zeros(N)
282
+ >>> plt.plot(x1, y, 'o')
283
+ [<matplotlib.lines.Line2D object at 0x...>]
284
+ >>> plt.plot(x2, y + 0.5, 'o')
285
+ [<matplotlib.lines.Line2D object at 0x...>]
286
+ >>> plt.ylim([-0.5, 1])
287
+ (-0.5, 1)
288
+ >>> plt.show()
289
+
290
+ """
291
+ if not isinstance(base, (float, int)) and np.ndim(base):
292
+ # If base is non-scalar, broadcast it with the others, since it
293
+ # may influence how axis is interpreted.
294
+ ndmax = np.broadcast(start, stop, base).ndim
295
+ start, stop, base = (
296
+ np.array(a, copy=None, subok=True, ndmin=ndmax)
297
+ for a in (start, stop, base)
298
+ )
299
+ base = np.expand_dims(base, axis=axis)
300
+ y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
301
+ if dtype is None:
302
+ return _nx.power(base, y)
303
+ return _nx.power(base, y).astype(dtype, copy=False)
304
+
305
+
306
+ def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
307
+ axis=None):
308
+ return (start, stop)
309
+
310
+
311
+ @array_function_dispatch(_geomspace_dispatcher)
312
+ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
313
+ """
314
+ Return numbers spaced evenly on a log scale (a geometric progression).
315
+
316
+ This is similar to `logspace`, but with endpoints specified directly.
317
+ Each output sample is a constant multiple of the previous.
318
+
319
+ Parameters
320
+ ----------
321
+ start : array_like
322
+ The starting value of the sequence.
323
+ stop : array_like
324
+ The final value of the sequence, unless `endpoint` is False.
325
+ In that case, ``num + 1`` values are spaced over the
326
+ interval in log-space, of which all but the last (a sequence of
327
+ length `num`) are returned.
328
+ num : integer, optional
329
+ Number of samples to generate. Default is 50.
330
+ endpoint : boolean, optional
331
+ If true, `stop` is the last sample. Otherwise, it is not included.
332
+ Default is True.
333
+ dtype : dtype
334
+ The type of the output array. If `dtype` is not given, the data type
335
+ is inferred from `start` and `stop`. The inferred dtype will never be
336
+ an integer; `float` is chosen even if the arguments would produce an
337
+ array of integers.
338
+ axis : int, optional
339
+ The axis in the result to store the samples. Relevant only if start
340
+ or stop are array-like. By default (0), the samples will be along a
341
+ new axis inserted at the beginning. Use -1 to get an axis at the end.
342
+
343
+ Returns
344
+ -------
345
+ samples : ndarray
346
+ `num` samples, equally spaced on a log scale.
347
+
348
+ See Also
349
+ --------
350
+ logspace : Similar to geomspace, but with endpoints specified using log
351
+ and base.
352
+ linspace : Similar to geomspace, but with arithmetic instead of geometric
353
+ progression.
354
+ arange : Similar to linspace, with the step size specified instead of the
355
+ number of samples.
356
+ :ref:`how-to-partition`
357
+
358
+ Notes
359
+ -----
360
+ If the inputs or dtype are complex, the output will follow a logarithmic
361
+ spiral in the complex plane. (There are an infinite number of spirals
362
+ passing through two points; the output will follow the shortest such path.)
363
+
364
+ Examples
365
+ --------
366
+ >>> import numpy as np
367
+ >>> np.geomspace(1, 1000, num=4)
368
+ array([ 1., 10., 100., 1000.])
369
+ >>> np.geomspace(1, 1000, num=3, endpoint=False)
370
+ array([ 1., 10., 100.])
371
+ >>> np.geomspace(1, 1000, num=4, endpoint=False)
372
+ array([ 1. , 5.62341325, 31.6227766 , 177.827941 ])
373
+ >>> np.geomspace(1, 256, num=9)
374
+ array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.])
375
+
376
+ Note that the above may not produce exact integers:
377
+
378
+ >>> np.geomspace(1, 256, num=9, dtype=int)
379
+ array([ 1, 2, 4, 7, 16, 32, 63, 127, 256])
380
+ >>> np.around(np.geomspace(1, 256, num=9)).astype(int)
381
+ array([ 1, 2, 4, 8, 16, 32, 64, 128, 256])
382
+
383
+ Negative, decreasing, and complex inputs are allowed:
384
+
385
+ >>> np.geomspace(1000, 1, num=4)
386
+ array([1000., 100., 10., 1.])
387
+ >>> np.geomspace(-1000, -1, num=4)
388
+ array([-1000., -100., -10., -1.])
389
+ >>> np.geomspace(1j, 1000j, num=4) # Straight line
390
+ array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j])
391
+ >>> np.geomspace(-1+0j, 1+0j, num=5) # Circle
392
+ array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
393
+ 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,
394
+ 1.00000000e+00+0.00000000e+00j])
395
+
396
+ Graphical illustration of `endpoint` parameter:
397
+
398
+ >>> import matplotlib.pyplot as plt
399
+ >>> N = 10
400
+ >>> y = np.zeros(N)
401
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
402
+ [<matplotlib.lines.Line2D object at 0x...>]
403
+ >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
404
+ [<matplotlib.lines.Line2D object at 0x...>]
405
+ >>> plt.axis([0.5, 2000, 0, 3])
406
+ [0.5, 2000, 0, 3]
407
+ >>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
408
+ >>> plt.show()
409
+
410
+ """
411
+ start = asanyarray(start)
412
+ stop = asanyarray(stop)
413
+ if _nx.any(start == 0) or _nx.any(stop == 0):
414
+ raise ValueError('Geometric sequence cannot include zero')
415
+
416
+ dt = result_type(start, stop, float(num), _nx.zeros((), dtype))
417
+ if dtype is None:
418
+ dtype = dt
419
+ else:
420
+ # complex to dtype('complex128'), for instance
421
+ dtype = _nx.dtype(dtype)
422
+
423
+ # Promote both arguments to the same dtype in case, for instance, one is
424
+ # complex and another is negative and log would produce NaN otherwise.
425
+ # Copy since we may change things in-place further down.
426
+ start = start.astype(dt, copy=True)
427
+ stop = stop.astype(dt, copy=True)
428
+
429
+ # Allow negative real values and ensure a consistent result for complex
430
+ # (including avoiding negligible real or imaginary parts in output) by
431
+ # rotating start to positive real, calculating, then undoing rotation.
432
+ out_sign = _nx.sign(start)
433
+ start /= out_sign
434
+ stop = stop / out_sign
435
+
436
+ log_start = _nx.log10(start)
437
+ log_stop = _nx.log10(stop)
438
+ result = logspace(log_start, log_stop, num=num,
439
+ endpoint=endpoint, base=10.0, dtype=dt)
440
+
441
+ # Make sure the endpoints match the start and stop arguments. This is
442
+ # necessary because np.exp(np.log(x)) is not necessarily equal to x.
443
+ if num > 0:
444
+ result[0] = start
445
+ if num > 1 and endpoint:
446
+ result[-1] = stop
447
+
448
+ result *= out_sign
449
+
450
+ if axis != 0:
451
+ result = _nx.moveaxis(result, 0, axis)
452
+
453
+ return result.astype(dtype, copy=False)
454
+
455
+
456
+ def _needs_add_docstring(obj):
457
+ """
458
+ Returns true if the only way to set the docstring of `obj` from python is
459
+ via add_docstring.
460
+
461
+ This function errs on the side of being overly conservative.
462
+ """
463
+ Py_TPFLAGS_HEAPTYPE = 1 << 9
464
+
465
+ if isinstance(obj, (types.FunctionType, types.MethodType, property)):
466
+ return False
467
+
468
+ if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE:
469
+ return False
470
+
471
+ return True
472
+
473
+
474
+ def _add_docstring(obj, doc, warn_on_python):
475
+ if warn_on_python and not _needs_add_docstring(obj):
476
+ warnings.warn(
477
+ f"add_newdoc was used on a pure-python object {obj}. "
478
+ "Prefer to attach it directly to the source.",
479
+ UserWarning,
480
+ stacklevel=3)
481
+
482
+ doc = inspect.cleandoc(doc)
483
+
484
+ try:
485
+ add_docstring(obj, doc)
486
+ except Exception:
487
+ pass
488
+
489
+
490
+ def add_newdoc(place, obj, doc, warn_on_python=True):
491
+ """
492
+ Add documentation to an existing object, typically one defined in C
493
+
494
+ The purpose is to allow easier editing of the docstrings without requiring
495
+ a re-compile. This exists primarily for internal use within numpy itself.
496
+
497
+ Parameters
498
+ ----------
499
+ place : str
500
+ The absolute name of the module to import from
501
+ obj : str | None
502
+ The name of the object to add documentation to, typically a class or
503
+ function name.
504
+ doc : str | tuple[str, str] | list[tuple[str, str]]
505
+ If a string, the documentation to apply to `obj`
506
+
507
+ If a tuple, then the first element is interpreted as an attribute
508
+ of `obj` and the second as the docstring to apply -
509
+ ``(method, docstring)``
510
+
511
+ If a list, then each element of the list should be a tuple of length
512
+ two - ``[(method1, docstring1), (method2, docstring2), ...]``
513
+ warn_on_python : bool
514
+ If True, the default, emit `UserWarning` if this is used to attach
515
+ documentation to a pure-python object.
516
+
517
+ Notes
518
+ -----
519
+ This routine never raises an error if the docstring can't be written, but
520
+ will raise an error if the object being documented does not exist.
521
+
522
+ This routine cannot modify read-only docstrings, as appear
523
+ in new-style classes or built-in functions. Because this
524
+ routine never raises an error the caller must check manually
525
+ that the docstrings were changed.
526
+
527
+ Since this function grabs the ``char *`` from a c-level str object and puts
528
+ it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
529
+ C-API best-practices, by:
530
+
531
+ - modifying a `PyTypeObject` after calling `PyType_Ready`
532
+ - calling `Py_INCREF` on the str and losing the reference, so the str
533
+ will never be released
534
+
535
+ If possible it should be avoided.
536
+ """
537
+ new = getattr(__import__(place, globals(), {}, [obj]), obj)
538
+ if isinstance(doc, str):
539
+ if "${ARRAY_FUNCTION_LIKE}" in doc:
540
+ doc = overrides.get_array_function_like_doc(new, doc)
541
+ _add_docstring(new, doc, warn_on_python)
542
+ elif isinstance(doc, tuple):
543
+ attr, docstring = doc
544
+ _add_docstring(getattr(new, attr), docstring, warn_on_python)
545
+ elif isinstance(doc, list):
546
+ for attr, docstring in doc:
547
+ _add_docstring(getattr(new, attr), docstring, warn_on_python)
python/user_packages/Python313/site-packages/numpy/_core/function_base.pyi ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import Incomplete
2
+ from typing import Literal as L, SupportsIndex, TypeAlias, TypeVar, overload
3
+
4
+ import numpy as np
5
+ from numpy._typing import (
6
+ DTypeLike,
7
+ NDArray,
8
+ _ArrayLikeComplex_co,
9
+ _ArrayLikeFloat_co,
10
+ _DTypeLike,
11
+ )
12
+ from numpy._typing._array_like import _DualArrayLike
13
+
14
+ __all__ = ["geomspace", "linspace", "logspace"]
15
+
16
+ _ScalarT = TypeVar("_ScalarT", bound=np.generic)
17
+
18
+ _ToArrayFloat64: TypeAlias = _DualArrayLike[np.dtype[np.float64 | np.integer | np.bool], float]
19
+
20
+ @overload
21
+ def linspace(
22
+ start: _ToArrayFloat64,
23
+ stop: _ToArrayFloat64,
24
+ num: SupportsIndex = 50,
25
+ endpoint: bool = True,
26
+ retstep: L[False] = False,
27
+ dtype: None = None,
28
+ axis: SupportsIndex = 0,
29
+ *,
30
+ device: L["cpu"] | None = None,
31
+ ) -> NDArray[np.float64]: ...
32
+ @overload
33
+ def linspace(
34
+ start: _ArrayLikeFloat_co,
35
+ stop: _ArrayLikeFloat_co,
36
+ num: SupportsIndex = 50,
37
+ endpoint: bool = True,
38
+ retstep: L[False] = False,
39
+ dtype: None = None,
40
+ axis: SupportsIndex = 0,
41
+ *,
42
+ device: L["cpu"] | None = None,
43
+ ) -> NDArray[np.floating]: ...
44
+ @overload
45
+ def linspace(
46
+ start: _ArrayLikeComplex_co,
47
+ stop: _ArrayLikeComplex_co,
48
+ num: SupportsIndex = 50,
49
+ endpoint: bool = True,
50
+ retstep: L[False] = False,
51
+ dtype: None = None,
52
+ axis: SupportsIndex = 0,
53
+ *,
54
+ device: L["cpu"] | None = None,
55
+ ) -> NDArray[np.complexfloating]: ...
56
+ @overload
57
+ def linspace(
58
+ start: _ArrayLikeComplex_co,
59
+ stop: _ArrayLikeComplex_co,
60
+ num: SupportsIndex,
61
+ endpoint: bool,
62
+ retstep: L[False],
63
+ dtype: _DTypeLike[_ScalarT],
64
+ axis: SupportsIndex = 0,
65
+ *,
66
+ device: L["cpu"] | None = None,
67
+ ) -> NDArray[_ScalarT]: ...
68
+ @overload
69
+ def linspace(
70
+ start: _ArrayLikeComplex_co,
71
+ stop: _ArrayLikeComplex_co,
72
+ num: SupportsIndex = 50,
73
+ endpoint: bool = True,
74
+ retstep: L[False] = False,
75
+ *,
76
+ dtype: _DTypeLike[_ScalarT],
77
+ axis: SupportsIndex = 0,
78
+ device: L["cpu"] | None = None,
79
+ ) -> NDArray[_ScalarT]: ...
80
+ @overload
81
+ def linspace(
82
+ start: _ArrayLikeComplex_co,
83
+ stop: _ArrayLikeComplex_co,
84
+ num: SupportsIndex = 50,
85
+ endpoint: bool = True,
86
+ retstep: L[False] = False,
87
+ dtype: DTypeLike | None = None,
88
+ axis: SupportsIndex = 0,
89
+ *,
90
+ device: L["cpu"] | None = None,
91
+ ) -> NDArray[Incomplete]: ...
92
+ @overload
93
+ def linspace(
94
+ start: _ToArrayFloat64,
95
+ stop: _ToArrayFloat64,
96
+ num: SupportsIndex = 50,
97
+ endpoint: bool = True,
98
+ *,
99
+ retstep: L[True],
100
+ dtype: None = None,
101
+ axis: SupportsIndex = 0,
102
+ device: L["cpu"] | None = None,
103
+ ) -> tuple[NDArray[np.float64], np.float64]: ...
104
+ @overload
105
+ def linspace(
106
+ start: _ArrayLikeFloat_co,
107
+ stop: _ArrayLikeFloat_co,
108
+ num: SupportsIndex = 50,
109
+ endpoint: bool = True,
110
+ *,
111
+ retstep: L[True],
112
+ dtype: None = None,
113
+ axis: SupportsIndex = 0,
114
+ device: L["cpu"] | None = None,
115
+ ) -> tuple[NDArray[np.floating], np.floating]: ...
116
+ @overload
117
+ def linspace(
118
+ start: _ArrayLikeComplex_co,
119
+ stop: _ArrayLikeComplex_co,
120
+ num: SupportsIndex = 50,
121
+ endpoint: bool = True,
122
+ *,
123
+ retstep: L[True],
124
+ dtype: None = None,
125
+ axis: SupportsIndex = 0,
126
+ device: L["cpu"] | None = None,
127
+ ) -> tuple[NDArray[np.complexfloating], np.complexfloating]: ...
128
+ @overload
129
+ def linspace(
130
+ start: _ArrayLikeComplex_co,
131
+ stop: _ArrayLikeComplex_co,
132
+ num: SupportsIndex = 50,
133
+ endpoint: bool = True,
134
+ *,
135
+ retstep: L[True],
136
+ dtype: _DTypeLike[_ScalarT],
137
+ axis: SupportsIndex = 0,
138
+ device: L["cpu"] | None = None,
139
+ ) -> tuple[NDArray[_ScalarT], _ScalarT]: ...
140
+ @overload
141
+ def linspace(
142
+ start: _ArrayLikeComplex_co,
143
+ stop: _ArrayLikeComplex_co,
144
+ num: SupportsIndex = 50,
145
+ endpoint: bool = True,
146
+ *,
147
+ retstep: L[True],
148
+ dtype: DTypeLike | None = None,
149
+ axis: SupportsIndex = 0,
150
+ device: L["cpu"] | None = None,
151
+ ) -> tuple[NDArray[Incomplete], Incomplete]: ...
152
+
153
+ @overload
154
+ def logspace(
155
+ start: _ToArrayFloat64,
156
+ stop: _ToArrayFloat64,
157
+ num: SupportsIndex = 50,
158
+ endpoint: bool = True,
159
+ base: _ToArrayFloat64 = 10.0,
160
+ dtype: None = None,
161
+ axis: SupportsIndex = 0,
162
+ ) -> NDArray[np.float64]: ...
163
+ @overload
164
+ def logspace(
165
+ start: _ArrayLikeFloat_co,
166
+ stop: _ArrayLikeFloat_co,
167
+ num: SupportsIndex = 50,
168
+ endpoint: bool = True,
169
+ base: _ArrayLikeFloat_co = 10.0,
170
+ dtype: None = None,
171
+ axis: SupportsIndex = 0,
172
+ ) -> NDArray[np.floating]: ...
173
+ @overload
174
+ def logspace(
175
+ start: _ArrayLikeComplex_co,
176
+ stop: _ArrayLikeComplex_co,
177
+ num: SupportsIndex = 50,
178
+ endpoint: bool = True,
179
+ base: _ArrayLikeComplex_co = 10.0,
180
+ dtype: None = None,
181
+ axis: SupportsIndex = 0,
182
+ ) -> NDArray[np.complexfloating]: ...
183
+ @overload
184
+ def logspace(
185
+ start: _ArrayLikeComplex_co,
186
+ stop: _ArrayLikeComplex_co,
187
+ num: SupportsIndex,
188
+ endpoint: bool,
189
+ base: _ArrayLikeComplex_co,
190
+ dtype: _DTypeLike[_ScalarT],
191
+ axis: SupportsIndex = 0,
192
+ ) -> NDArray[_ScalarT]: ...
193
+ @overload
194
+ def logspace(
195
+ start: _ArrayLikeComplex_co,
196
+ stop: _ArrayLikeComplex_co,
197
+ num: SupportsIndex = 50,
198
+ endpoint: bool = True,
199
+ base: _ArrayLikeComplex_co = 10.0,
200
+ *,
201
+ dtype: _DTypeLike[_ScalarT],
202
+ axis: SupportsIndex = 0,
203
+ ) -> NDArray[_ScalarT]: ...
204
+ @overload
205
+ def logspace(
206
+ start: _ArrayLikeComplex_co,
207
+ stop: _ArrayLikeComplex_co,
208
+ num: SupportsIndex = 50,
209
+ endpoint: bool = True,
210
+ base: _ArrayLikeComplex_co = 10.0,
211
+ dtype: DTypeLike | None = None,
212
+ axis: SupportsIndex = 0,
213
+ ) -> NDArray[Incomplete]: ...
214
+
215
+ @overload
216
+ def geomspace(
217
+ start: _ToArrayFloat64,
218
+ stop: _ToArrayFloat64,
219
+ num: SupportsIndex = 50,
220
+ endpoint: bool = True,
221
+ dtype: None = None,
222
+ axis: SupportsIndex = 0,
223
+ ) -> NDArray[np.float64]: ...
224
+ @overload
225
+ def geomspace(
226
+ start: _ArrayLikeFloat_co,
227
+ stop: _ArrayLikeFloat_co,
228
+ num: SupportsIndex = 50,
229
+ endpoint: bool = True,
230
+ dtype: None = None,
231
+ axis: SupportsIndex = 0,
232
+ ) -> NDArray[np.floating]: ...
233
+ @overload
234
+ def geomspace(
235
+ start: _ArrayLikeComplex_co,
236
+ stop: _ArrayLikeComplex_co,
237
+ num: SupportsIndex = 50,
238
+ endpoint: bool = True,
239
+ dtype: None = None,
240
+ axis: SupportsIndex = 0,
241
+ ) -> NDArray[np.complexfloating]: ...
242
+ @overload
243
+ def geomspace(
244
+ start: _ArrayLikeComplex_co,
245
+ stop: _ArrayLikeComplex_co,
246
+ num: SupportsIndex,
247
+ endpoint: bool,
248
+ dtype: _DTypeLike[_ScalarT],
249
+ axis: SupportsIndex = 0,
250
+ ) -> NDArray[_ScalarT]: ...
251
+ @overload
252
+ def geomspace(
253
+ start: _ArrayLikeComplex_co,
254
+ stop: _ArrayLikeComplex_co,
255
+ num: SupportsIndex = 50,
256
+ endpoint: bool = True,
257
+ *,
258
+ dtype: _DTypeLike[_ScalarT],
259
+ axis: SupportsIndex = 0,
260
+ ) -> NDArray[_ScalarT]: ...
261
+ @overload
262
+ def geomspace(
263
+ start: _ArrayLikeComplex_co,
264
+ stop: _ArrayLikeComplex_co,
265
+ num: SupportsIndex = 50,
266
+ endpoint: bool = True,
267
+ dtype: DTypeLike | None = None,
268
+ axis: SupportsIndex = 0,
269
+ ) -> NDArray[Incomplete]: ...
270
+
271
+ def add_newdoc(
272
+ place: str,
273
+ obj: str,
274
+ doc: str | tuple[str, str] | list[tuple[str, str]],
275
+ warn_on_python: bool = True,
276
+ ) -> None: ...
python/user_packages/Python313/site-packages/numpy/_core/getlimits.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Machine limits for Float32 and Float64 and (long double) if available...
2
+
3
+ """
4
+ __all__ = ['finfo', 'iinfo']
5
+
6
+ import math
7
+ import types
8
+ import warnings
9
+ from functools import cached_property
10
+
11
+ from numpy._utils import set_module
12
+
13
+ from . import numeric, numerictypes as ntypes
14
+ from ._multiarray_umath import _populate_finfo_constants
15
+
16
+
17
+ def _fr0(a):
18
+ """fix rank-0 --> rank-1"""
19
+ if a.ndim == 0:
20
+ a = a.copy()
21
+ a.shape = (1,)
22
+ return a
23
+
24
+
25
+ def _fr1(a):
26
+ """fix rank > 0 --> rank-0"""
27
+ if a.size == 1:
28
+ a = a.copy()
29
+ a.shape = ()
30
+ return a
31
+
32
+
33
+ _convert_to_float = {
34
+ ntypes.csingle: ntypes.single,
35
+ ntypes.complex128: ntypes.float64,
36
+ ntypes.clongdouble: ntypes.longdouble
37
+ }
38
+
39
+ # Parameters for creating MachAr / MachAr-like objects
40
+ _title_fmt = 'numpy {} precision floating point number'
41
+ _MACHAR_PARAMS = {
42
+ ntypes.double: {
43
+ 'itype': ntypes.int64,
44
+ 'fmt': '%24.16e',
45
+ 'title': _title_fmt.format('double')},
46
+ ntypes.single: {
47
+ 'itype': ntypes.int32,
48
+ 'fmt': '%15.7e',
49
+ 'title': _title_fmt.format('single')},
50
+ ntypes.longdouble: {
51
+ 'itype': ntypes.longlong,
52
+ 'fmt': '%s',
53
+ 'title': _title_fmt.format('long double')},
54
+ ntypes.half: {
55
+ 'itype': ntypes.int16,
56
+ 'fmt': '%12.5e',
57
+ 'title': _title_fmt.format('half')}}
58
+
59
+
60
+ @set_module('numpy')
61
+ class finfo:
62
+ """
63
+ finfo(dtype)
64
+
65
+ Machine limits for floating point types.
66
+
67
+ Attributes
68
+ ----------
69
+ bits : int
70
+ The number of bits occupied by the type.
71
+ dtype : dtype
72
+ Returns the dtype for which `finfo` returns information. For complex
73
+ input, the returned dtype is the associated ``float*`` dtype for its
74
+ real and complex components.
75
+ eps : float
76
+ The difference between 1.0 and the next smallest representable float
77
+ larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
78
+ standard, ``eps = 2**-52``, approximately 2.22e-16.
79
+ epsneg : float
80
+ The difference between 1.0 and the next smallest representable float
81
+ less than 1.0. For example, for 64-bit binary floats in the IEEE-754
82
+ standard, ``epsneg = 2**-53``, approximately 1.11e-16.
83
+ iexp : int
84
+ The number of bits in the exponent portion of the floating point
85
+ representation.
86
+ machep : int
87
+ The exponent that yields `eps`.
88
+ max : floating point number of the appropriate type
89
+ The largest representable number.
90
+ maxexp : int
91
+ The smallest positive power of the base (2) that causes overflow.
92
+ Corresponds to the C standard MAX_EXP.
93
+ min : floating point number of the appropriate type
94
+ The smallest representable number, typically ``-max``.
95
+ minexp : int
96
+ The most negative power of the base (2) consistent with there
97
+ being no leading 0's in the mantissa. Corresponds to the C
98
+ standard MIN_EXP - 1.
99
+ negep : int
100
+ The exponent that yields `epsneg`.
101
+ nexp : int
102
+ The number of bits in the exponent including its sign and bias.
103
+ nmant : int
104
+ The number of explicit bits in the mantissa (excluding the implicit
105
+ leading bit for normalized numbers).
106
+ precision : int
107
+ The approximate number of decimal digits to which this kind of
108
+ float is precise.
109
+ resolution : floating point number of the appropriate type
110
+ The approximate decimal resolution of this type, i.e.,
111
+ ``10**-precision``.
112
+ tiny : float
113
+ An alias for `smallest_normal`, kept for backwards compatibility.
114
+ smallest_normal : float
115
+ The smallest positive floating point number with 1 as leading bit in
116
+ the mantissa following IEEE-754 (see Notes).
117
+ smallest_subnormal : float
118
+ The smallest positive floating point number with 0 as leading bit in
119
+ the mantissa following IEEE-754.
120
+
121
+ Parameters
122
+ ----------
123
+ dtype : float, dtype, or instance
124
+ Kind of floating point or complex floating point
125
+ data-type about which to get information.
126
+
127
+ See Also
128
+ --------
129
+ iinfo : The equivalent for integer data types.
130
+ spacing : The distance between a value and the nearest adjacent number
131
+ nextafter : The next floating point value after x1 towards x2
132
+
133
+ Notes
134
+ -----
135
+ For developers of NumPy: do not instantiate this at the module level.
136
+ The initial calculation of these parameters is expensive and negatively
137
+ impacts import times. These objects are cached, so calling ``finfo()``
138
+ repeatedly inside your functions is not a problem.
139
+
140
+ Note that ``smallest_normal`` is not actually the smallest positive
141
+ representable value in a NumPy floating point type. As in the IEEE-754
142
+ standard [1]_, NumPy floating point types make use of subnormal numbers to
143
+ fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
144
+ may have significantly reduced precision [2]_.
145
+
146
+ For ``longdouble``, the representation varies across platforms. On most
147
+ platforms it is IEEE 754 binary128 (quad precision) or binary64-extended
148
+ (80-bit extended precision). On PowerPC systems, it may use the IBM
149
+ double-double format (a pair of float64 values), which has special
150
+ characteristics for precision and range.
151
+
152
+ This function can also be used for complex data types as well. If used,
153
+ the output will be the same as the corresponding real float type
154
+ (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
155
+ However, the output is true for the real and imaginary components.
156
+
157
+ References
158
+ ----------
159
+ .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
160
+ pp.1-70, 2008, https://doi.org/10.1109/IEEESTD.2008.4610935
161
+ .. [2] Wikipedia, "Denormal Numbers",
162
+ https://en.wikipedia.org/wiki/Denormal_number
163
+
164
+ Examples
165
+ --------
166
+ >>> import numpy as np
167
+ >>> np.finfo(np.float64).dtype
168
+ dtype('float64')
169
+ >>> np.finfo(np.complex64).dtype
170
+ dtype('float32')
171
+
172
+ """
173
+
174
+ _finfo_cache = {}
175
+
176
+ __class_getitem__ = classmethod(types.GenericAlias)
177
+
178
+ def __new__(cls, dtype):
179
+ try:
180
+ obj = cls._finfo_cache.get(dtype) # most common path
181
+ if obj is not None:
182
+ return obj
183
+ except TypeError:
184
+ pass
185
+
186
+ if dtype is None:
187
+ # Deprecated in NumPy 1.25, 2023-01-16
188
+ warnings.warn(
189
+ "finfo() dtype cannot be None. This behavior will "
190
+ "raise an error in the future. (Deprecated in NumPy 1.25)",
191
+ DeprecationWarning,
192
+ stacklevel=2
193
+ )
194
+
195
+ try:
196
+ dtype = numeric.dtype(dtype)
197
+ except TypeError:
198
+ # In case a float instance was given
199
+ dtype = numeric.dtype(type(dtype))
200
+
201
+ obj = cls._finfo_cache.get(dtype)
202
+ if obj is not None:
203
+ return obj
204
+ dtypes = [dtype]
205
+ newdtype = ntypes.obj2sctype(dtype)
206
+ if newdtype is not dtype:
207
+ dtypes.append(newdtype)
208
+ dtype = newdtype
209
+ if not issubclass(dtype, numeric.inexact):
210
+ raise ValueError(f"data type {dtype!r} not inexact")
211
+ obj = cls._finfo_cache.get(dtype)
212
+ if obj is not None:
213
+ return obj
214
+ if not issubclass(dtype, numeric.floating):
215
+ newdtype = _convert_to_float[dtype]
216
+ if newdtype is not dtype:
217
+ # dtype changed, for example from complex128 to float64
218
+ dtypes.append(newdtype)
219
+ dtype = newdtype
220
+
221
+ obj = cls._finfo_cache.get(dtype, None)
222
+ if obj is not None:
223
+ # the original dtype was not in the cache, but the new
224
+ # dtype is in the cache. we add the original dtypes to
225
+ # the cache and return the result
226
+ for dt in dtypes:
227
+ cls._finfo_cache[dt] = obj
228
+ return obj
229
+ obj = object.__new__(cls)._init(dtype)
230
+ for dt in dtypes:
231
+ cls._finfo_cache[dt] = obj
232
+ return obj
233
+
234
+ def _init(self, dtype):
235
+ self.dtype = numeric.dtype(dtype)
236
+ self.bits = self.dtype.itemsize * 8
237
+ self._fmt = None
238
+ self._repr = None
239
+ _populate_finfo_constants(self, self.dtype)
240
+ return self
241
+
242
+ @cached_property
243
+ def epsneg(self):
244
+ # Assume typical floating point logic. Could also use nextafter.
245
+ return self.eps / self._radix
246
+
247
+ @cached_property
248
+ def resolution(self):
249
+ return self.dtype.type(10)**-self.precision
250
+
251
+ @cached_property
252
+ def machep(self):
253
+ return int(math.log2(self.eps))
254
+
255
+ @cached_property
256
+ def negep(self):
257
+ return int(math.log2(self.epsneg))
258
+
259
+ @cached_property
260
+ def nexp(self):
261
+ # considering all ones (inf/nan) and all zeros (subnormal/zero)
262
+ return math.ceil(math.log2(self.maxexp - self.minexp + 2))
263
+
264
+ @cached_property
265
+ def iexp(self):
266
+ # Calculate exponent bits from it's range:
267
+ return math.ceil(math.log2(self.maxexp - self.minexp))
268
+
269
+ def __str__(self):
270
+ if (fmt := getattr(self, "_fmt", None)) is not None:
271
+ return fmt
272
+
273
+ def get_str(name, pad=None):
274
+ if (val := getattr(self, name, None)) is None:
275
+ return "<undefined>"
276
+ if pad is not None:
277
+ s = str(val).ljust(pad)
278
+ return str(val)
279
+
280
+ precision = get_str("precision", 3)
281
+ machep = get_str("machep", 6)
282
+ negep = get_str("negep", 6)
283
+ minexp = get_str("minexp", 6)
284
+ maxexp = get_str("maxexp", 6)
285
+ resolution = get_str("resolution")
286
+ eps = get_str("eps")
287
+ epsneg = get_str("epsneg")
288
+ tiny = get_str("tiny")
289
+ smallest_normal = get_str("smallest_normal")
290
+ smallest_subnormal = get_str("smallest_subnormal")
291
+ nexp = get_str("nexp", 6)
292
+ max_ = get_str("max")
293
+ if hasattr(self, "min") and hasattr(self, "max") and -self.min == self.max:
294
+ min_ = "-max"
295
+ else:
296
+ min_ = get_str("min")
297
+
298
+ fmt = (
299
+ f'Machine parameters for {self.dtype}\n'
300
+ f'---------------------------------------------------------------\n'
301
+ f'precision = {precision} resolution = {resolution}\n'
302
+ f'machep = {machep} eps = {eps}\n'
303
+ f'negep = {negep} epsneg = {epsneg}\n'
304
+ f'minexp = {minexp} tiny = {tiny}\n'
305
+ f'maxexp = {maxexp} max = {max_}\n'
306
+ f'nexp = {nexp} min = {min_}\n'
307
+ f'smallest_normal = {smallest_normal} '
308
+ f'smallest_subnormal = {smallest_subnormal}\n'
309
+ f'---------------------------------------------------------------\n'
310
+ )
311
+ self._fmt = fmt
312
+ return fmt
313
+
314
+ def __repr__(self):
315
+ if (repr_str := getattr(self, "_repr", None)) is not None:
316
+ return repr_str
317
+
318
+ c = self.__class__.__name__
319
+
320
+ # Use precision+1 digits in exponential notation
321
+ fmt_str = _MACHAR_PARAMS.get(self.dtype.type, {}).get('fmt', '%s')
322
+ if fmt_str != '%s' and hasattr(self, 'max') and hasattr(self, 'min'):
323
+ max_str = (fmt_str % self.max).strip()
324
+ min_str = (fmt_str % self.min).strip()
325
+ else:
326
+ max_str = str(self.max)
327
+ min_str = str(self.min)
328
+
329
+ resolution_str = str(self.resolution)
330
+
331
+ repr_str = (f"{c}(resolution={resolution_str}, min={min_str},"
332
+ f" max={max_str}, dtype={self.dtype})")
333
+ self._repr = repr_str
334
+ return repr_str
335
+
336
+ @cached_property
337
+ def tiny(self):
338
+ """Return the value for tiny, alias of smallest_normal.
339
+
340
+ Returns
341
+ -------
342
+ tiny : float
343
+ Value for the smallest normal, alias of smallest_normal.
344
+
345
+ Warns
346
+ -----
347
+ UserWarning
348
+ If the calculated value for the smallest normal is requested for
349
+ double-double.
350
+ """
351
+ return self.smallest_normal
352
+
353
+
354
+ @set_module('numpy')
355
+ class iinfo:
356
+ """
357
+ iinfo(type)
358
+
359
+ Machine limits for integer types.
360
+
361
+ Attributes
362
+ ----------
363
+ bits : int
364
+ The number of bits occupied by the type.
365
+ dtype : dtype
366
+ Returns the dtype for which `iinfo` returns information.
367
+ min : int
368
+ The smallest integer expressible by the type.
369
+ max : int
370
+ The largest integer expressible by the type.
371
+
372
+ Parameters
373
+ ----------
374
+ int_type : integer type, dtype, or instance
375
+ The kind of integer data type to get information about.
376
+
377
+ See Also
378
+ --------
379
+ finfo : The equivalent for floating point data types.
380
+
381
+ Examples
382
+ --------
383
+ With types:
384
+
385
+ >>> import numpy as np
386
+ >>> ii16 = np.iinfo(np.int16)
387
+ >>> ii16.min
388
+ -32768
389
+ >>> ii16.max
390
+ 32767
391
+ >>> ii32 = np.iinfo(np.int32)
392
+ >>> ii32.min
393
+ -2147483648
394
+ >>> ii32.max
395
+ 2147483647
396
+
397
+ With instances:
398
+
399
+ >>> ii32 = np.iinfo(np.int32(10))
400
+ >>> ii32.min
401
+ -2147483648
402
+ >>> ii32.max
403
+ 2147483647
404
+
405
+ """
406
+
407
+ _min_vals = {}
408
+ _max_vals = {}
409
+
410
+ __class_getitem__ = classmethod(types.GenericAlias)
411
+
412
+ def __init__(self, int_type):
413
+ try:
414
+ self.dtype = numeric.dtype(int_type)
415
+ except TypeError:
416
+ self.dtype = numeric.dtype(type(int_type))
417
+ self.kind = self.dtype.kind
418
+ self.bits = self.dtype.itemsize * 8
419
+ self.key = "%s%d" % (self.kind, self.bits)
420
+ if self.kind not in 'iu':
421
+ raise ValueError(f"Invalid integer data type {self.kind!r}.")
422
+
423
+ @property
424
+ def min(self):
425
+ """Minimum value of given dtype."""
426
+ if self.kind == 'u':
427
+ return 0
428
+ else:
429
+ try:
430
+ val = iinfo._min_vals[self.key]
431
+ except KeyError:
432
+ val = int(-(1 << (self.bits - 1)))
433
+ iinfo._min_vals[self.key] = val
434
+ return val
435
+
436
+ @property
437
+ def max(self):
438
+ """Maximum value of given dtype."""
439
+ try:
440
+ val = iinfo._max_vals[self.key]
441
+ except KeyError:
442
+ if self.kind == 'u':
443
+ val = int((1 << self.bits) - 1)
444
+ else:
445
+ val = int((1 << (self.bits - 1)) - 1)
446
+ iinfo._max_vals[self.key] = val
447
+ return val
448
+
449
+ def __str__(self):
450
+ """String representation."""
451
+ fmt = (
452
+ 'Machine parameters for %(dtype)s\n'
453
+ '---------------------------------------------------------------\n'
454
+ 'min = %(min)s\n'
455
+ 'max = %(max)s\n'
456
+ '---------------------------------------------------------------\n'
457
+ )
458
+ return fmt % {'dtype': self.dtype, 'min': self.min, 'max': self.max}
459
+
460
+ def __repr__(self):
461
+ return "%s(min=%s, max=%s, dtype=%s)" % (self.__class__.__name__,
462
+ self.min, self.max, self.dtype)