Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/numpy/core/__init__.py +180 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__init__.pyi +2 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs_scalars.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_asarray.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype_ctypes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_exceptions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_internal.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_machar.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_methods.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_string_helpers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_type_aliases.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_ufunc_config.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/cversions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/defchararray.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/einsumfunc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/fromnumeric.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/function_base.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/getlimits.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/memmap.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/multiarray.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/numerictypes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/overrides.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/records.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/shape_base.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/umath.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/umath_tests.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_asarray.pyi +42 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_dtype.py +369 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_dtype_ctypes.py +117 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_internal.py +935 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_internal.pyi +30 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_methods.py +234 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_type_aliases.py +245 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_type_aliases.pyi +13 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_ufunc_config.py +466 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/_umath_tests.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/arrayprint.pyi +142 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/cversions.py +13 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/defchararray.py +2914 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/einsumfunc.pyi +187 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/fromnumeric.py +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/fromnumeric.pyi +1060 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/function_base.py +551 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/function_base.pyi +187 -0
- env-llmeval/lib/python3.10/site-packages/numpy/core/lib/libnpymath.a +0 -0
env-llmeval/lib/python3.10/site-packages/numpy/core/__init__.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import warnings
|
11 |
+
|
12 |
+
from numpy.version import version as __version__
|
13 |
+
|
14 |
+
|
15 |
+
# disables OpenBLAS affinity setting of the main thread that limits
|
16 |
+
# python threads or processes to one core
|
17 |
+
env_added = []
|
18 |
+
for envkey in ['OPENBLAS_MAIN_FREE', 'GOTOBLAS_MAIN_FREE']:
|
19 |
+
if envkey not in os.environ:
|
20 |
+
os.environ[envkey] = '1'
|
21 |
+
env_added.append(envkey)
|
22 |
+
|
23 |
+
try:
|
24 |
+
from . import multiarray
|
25 |
+
except ImportError as exc:
|
26 |
+
import sys
|
27 |
+
msg = """
|
28 |
+
|
29 |
+
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
|
30 |
+
|
31 |
+
Importing the numpy C-extensions failed. This error can happen for
|
32 |
+
many reasons, often due to issues with your setup or how NumPy was
|
33 |
+
installed.
|
34 |
+
|
35 |
+
We have compiled some common reasons and troubleshooting tips at:
|
36 |
+
|
37 |
+
https://numpy.org/devdocs/user/troubleshooting-importerror.html
|
38 |
+
|
39 |
+
Please note and check the following:
|
40 |
+
|
41 |
+
* The Python version is: Python%d.%d from "%s"
|
42 |
+
* The NumPy version is: "%s"
|
43 |
+
|
44 |
+
and make sure that they are the versions you expect.
|
45 |
+
Please carefully study the documentation linked above for further help.
|
46 |
+
|
47 |
+
Original error was: %s
|
48 |
+
""" % (sys.version_info[0], sys.version_info[1], sys.executable,
|
49 |
+
__version__, exc)
|
50 |
+
raise ImportError(msg)
|
51 |
+
finally:
|
52 |
+
for envkey in env_added:
|
53 |
+
del os.environ[envkey]
|
54 |
+
del envkey
|
55 |
+
del env_added
|
56 |
+
del os
|
57 |
+
|
58 |
+
from . import umath
|
59 |
+
|
60 |
+
# Check that multiarray,umath are pure python modules wrapping
|
61 |
+
# _multiarray_umath and not either of the old c-extension modules
|
62 |
+
if not (hasattr(multiarray, '_multiarray_umath') and
|
63 |
+
hasattr(umath, '_multiarray_umath')):
|
64 |
+
import sys
|
65 |
+
path = sys.modules['numpy'].__path__
|
66 |
+
msg = ("Something is wrong with the numpy installation. "
|
67 |
+
"While importing we detected an older version of "
|
68 |
+
"numpy in {}. One method of fixing this is to repeatedly uninstall "
|
69 |
+
"numpy until none is found, then reinstall this version.")
|
70 |
+
raise ImportError(msg.format(path))
|
71 |
+
|
72 |
+
from . import numerictypes as nt
|
73 |
+
multiarray.set_typeDict(nt.sctypeDict)
|
74 |
+
from . import numeric
|
75 |
+
from .numeric import *
|
76 |
+
from . import fromnumeric
|
77 |
+
from .fromnumeric import *
|
78 |
+
from . import defchararray as char
|
79 |
+
from . import records
|
80 |
+
from . import records as rec
|
81 |
+
from .records import record, recarray, format_parser
|
82 |
+
# Note: module name memmap is overwritten by a class with same name
|
83 |
+
from .memmap import *
|
84 |
+
from .defchararray import chararray
|
85 |
+
from . import function_base
|
86 |
+
from .function_base import *
|
87 |
+
from . import _machar
|
88 |
+
from . import getlimits
|
89 |
+
from .getlimits import *
|
90 |
+
from . import shape_base
|
91 |
+
from .shape_base import *
|
92 |
+
from . import einsumfunc
|
93 |
+
from .einsumfunc import *
|
94 |
+
del nt
|
95 |
+
|
96 |
+
from .numeric import absolute as abs
|
97 |
+
|
98 |
+
# do this after everything else, to minimize the chance of this misleadingly
|
99 |
+
# appearing in an import-time traceback
|
100 |
+
from . import _add_newdocs
|
101 |
+
from . import _add_newdocs_scalars
|
102 |
+
# add these for module-freeze analysis (like PyInstaller)
|
103 |
+
from . import _dtype_ctypes
|
104 |
+
from . import _internal
|
105 |
+
from . import _dtype
|
106 |
+
from . import _methods
|
107 |
+
|
108 |
+
__all__ = ['char', 'rec', 'memmap']
|
109 |
+
__all__ += numeric.__all__
|
110 |
+
__all__ += ['record', 'recarray', 'format_parser']
|
111 |
+
__all__ += ['chararray']
|
112 |
+
__all__ += function_base.__all__
|
113 |
+
__all__ += getlimits.__all__
|
114 |
+
__all__ += shape_base.__all__
|
115 |
+
__all__ += einsumfunc.__all__
|
116 |
+
|
117 |
+
# We used to use `np.core._ufunc_reconstruct` to unpickle. This is unnecessary,
|
118 |
+
# but old pickles saved before 1.20 will be using it, and there is no reason
|
119 |
+
# to break loading them.
|
120 |
+
def _ufunc_reconstruct(module, name):
|
121 |
+
# The `fromlist` kwarg is required to ensure that `mod` points to the
|
122 |
+
# inner-most module rather than the parent package when module name is
|
123 |
+
# nested. This makes it possible to pickle non-toplevel ufuncs such as
|
124 |
+
# scipy.special.expit for instance.
|
125 |
+
mod = __import__(module, fromlist=[name])
|
126 |
+
return getattr(mod, name)
|
127 |
+
|
128 |
+
|
129 |
+
def _ufunc_reduce(func):
|
130 |
+
# Report the `__name__`. pickle will try to find the module. Note that
|
131 |
+
# pickle supports for this `__name__` to be a `__qualname__`. It may
|
132 |
+
# make sense to add a `__qualname__` to ufuncs, to allow this more
|
133 |
+
# explicitly (Numba has ufuncs as attributes).
|
134 |
+
# See also: https://github.com/dask/distributed/issues/3450
|
135 |
+
return func.__name__
|
136 |
+
|
137 |
+
|
138 |
+
def _DType_reconstruct(scalar_type):
|
139 |
+
# This is a work-around to pickle type(np.dtype(np.float64)), etc.
|
140 |
+
# and it should eventually be replaced with a better solution, e.g. when
|
141 |
+
# DTypes become HeapTypes.
|
142 |
+
return type(dtype(scalar_type))
|
143 |
+
|
144 |
+
|
145 |
+
def _DType_reduce(DType):
|
146 |
+
# As types/classes, most DTypes can simply be pickled by their name:
|
147 |
+
if not DType._legacy or DType.__module__ == "numpy.dtypes":
|
148 |
+
return DType.__name__
|
149 |
+
|
150 |
+
# However, user defined legacy dtypes (like rational) do not end up in
|
151 |
+
# `numpy.dtypes` as module and do not have a public class at all.
|
152 |
+
# For these, we pickle them by reconstructing them from the scalar type:
|
153 |
+
scalar_type = DType.type
|
154 |
+
return _DType_reconstruct, (scalar_type,)
|
155 |
+
|
156 |
+
|
157 |
+
def __getattr__(name):
|
158 |
+
# Deprecated 2022-11-22, NumPy 1.25.
|
159 |
+
if name == "MachAr":
|
160 |
+
warnings.warn(
|
161 |
+
"The `np.core.MachAr` is considered private API (NumPy 1.24)",
|
162 |
+
DeprecationWarning, stacklevel=2,
|
163 |
+
)
|
164 |
+
return _machar.MachAr
|
165 |
+
raise AttributeError(f"Module {__name__!r} has no attribute {name!r}")
|
166 |
+
|
167 |
+
|
168 |
+
import copyreg
|
169 |
+
|
170 |
+
copyreg.pickle(ufunc, _ufunc_reduce)
|
171 |
+
copyreg.pickle(type(dtype), _DType_reduce, _DType_reconstruct)
|
172 |
+
|
173 |
+
# Unclutter namespace (must keep _*_reconstruct for unpickling)
|
174 |
+
del copyreg
|
175 |
+
del _ufunc_reduce
|
176 |
+
del _DType_reduce
|
177 |
+
|
178 |
+
from numpy._pytesttester import PytestTester
|
179 |
+
test = PytestTester(__name__)
|
180 |
+
del PytestTester
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__init__.pyi
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# NOTE: The `np.core` namespace is deliberately kept empty due to it
|
2 |
+
# being private (despite the lack of leading underscore)
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (4.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs.cpython-310.pyc
ADDED
Binary file (192 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs_scalars.cpython-310.pyc
ADDED
Binary file (11 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_asarray.cpython-310.pyc
ADDED
Binary file (3.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype.cpython-310.pyc
ADDED
Binary file (8.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype_ctypes.cpython-310.pyc
ADDED
Binary file (3.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_exceptions.cpython-310.pyc
ADDED
Binary file (5.82 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_internal.cpython-310.pyc
ADDED
Binary file (23.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_machar.cpython-310.pyc
ADDED
Binary file (8.32 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_methods.cpython-310.pyc
ADDED
Binary file (5.73 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_string_helpers.cpython-310.pyc
ADDED
Binary file (3.03 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_type_aliases.cpython-310.pyc
ADDED
Binary file (5.36 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/_ufunc_config.cpython-310.pyc
ADDED
Binary file (14.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/cversions.cpython-310.pyc
ADDED
Binary file (557 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/defchararray.cpython-310.pyc
ADDED
Binary file (71 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/einsumfunc.cpython-310.pyc
ADDED
Binary file (39.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/fromnumeric.cpython-310.pyc
ADDED
Binary file (126 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/function_base.cpython-310.pyc
ADDED
Binary file (17.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/getlimits.cpython-310.pyc
ADDED
Binary file (19.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/memmap.cpython-310.pyc
ADDED
Binary file (10.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/multiarray.cpython-310.pyc
ADDED
Binary file (54.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/numerictypes.cpython-310.pyc
ADDED
Binary file (17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/overrides.cpython-310.pyc
ADDED
Binary file (6.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/records.cpython-310.pyc
ADDED
Binary file (30.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/shape_base.cpython-310.pyc
ADDED
Binary file (26.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/umath.cpython-310.pyc
ADDED
Binary file (1.73 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/__pycache__/umath_tests.cpython-310.pyc
ADDED
Binary file (524 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_asarray.pyi
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections.abc import Iterable
|
2 |
+
from typing import Any, TypeVar, Union, overload, Literal
|
3 |
+
|
4 |
+
from numpy import ndarray
|
5 |
+
from numpy._typing import DTypeLike, _SupportsArrayFunc
|
6 |
+
|
7 |
+
_ArrayType = TypeVar("_ArrayType", bound=ndarray[Any, Any])
|
8 |
+
|
9 |
+
_Requirements = Literal[
|
10 |
+
"C", "C_CONTIGUOUS", "CONTIGUOUS",
|
11 |
+
"F", "F_CONTIGUOUS", "FORTRAN",
|
12 |
+
"A", "ALIGNED",
|
13 |
+
"W", "WRITEABLE",
|
14 |
+
"O", "OWNDATA"
|
15 |
+
]
|
16 |
+
_E = Literal["E", "ENSUREARRAY"]
|
17 |
+
_RequirementsWithE = Union[_Requirements, _E]
|
18 |
+
|
19 |
+
@overload
|
20 |
+
def require(
|
21 |
+
a: _ArrayType,
|
22 |
+
dtype: None = ...,
|
23 |
+
requirements: None | _Requirements | Iterable[_Requirements] = ...,
|
24 |
+
*,
|
25 |
+
like: _SupportsArrayFunc = ...
|
26 |
+
) -> _ArrayType: ...
|
27 |
+
@overload
|
28 |
+
def require(
|
29 |
+
a: object,
|
30 |
+
dtype: DTypeLike = ...,
|
31 |
+
requirements: _E | Iterable[_RequirementsWithE] = ...,
|
32 |
+
*,
|
33 |
+
like: _SupportsArrayFunc = ...
|
34 |
+
) -> ndarray[Any, Any]: ...
|
35 |
+
@overload
|
36 |
+
def require(
|
37 |
+
a: object,
|
38 |
+
dtype: DTypeLike = ...,
|
39 |
+
requirements: None | _Requirements | Iterable[_Requirements] = ...,
|
40 |
+
*,
|
41 |
+
like: _SupportsArrayFunc = ...
|
42 |
+
) -> ndarray[Any, Any]: ...
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_dtype.py
ADDED
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
9 |
+
_kind_to_stem = {
|
10 |
+
'u': 'uint',
|
11 |
+
'i': 'int',
|
12 |
+
'c': 'complex',
|
13 |
+
'f': 'float',
|
14 |
+
'b': 'bool',
|
15 |
+
'V': 'void',
|
16 |
+
'O': 'object',
|
17 |
+
'M': 'datetime',
|
18 |
+
'm': 'timedelta',
|
19 |
+
'S': 'bytes',
|
20 |
+
'U': 'str',
|
21 |
+
}
|
22 |
+
|
23 |
+
|
24 |
+
def _kind_name(dtype):
|
25 |
+
try:
|
26 |
+
return _kind_to_stem[dtype.kind]
|
27 |
+
except KeyError as e:
|
28 |
+
raise RuntimeError(
|
29 |
+
"internal dtype error, unknown kind {!r}"
|
30 |
+
.format(dtype.kind)
|
31 |
+
) from None
|
32 |
+
|
33 |
+
|
34 |
+
def __str__(dtype):
|
35 |
+
if dtype.fields is not None:
|
36 |
+
return _struct_str(dtype, include_align=True)
|
37 |
+
elif dtype.subdtype:
|
38 |
+
return _subarray_str(dtype)
|
39 |
+
elif issubclass(dtype.type, np.flexible) or not dtype.isnative:
|
40 |
+
return dtype.str
|
41 |
+
else:
|
42 |
+
return dtype.name
|
43 |
+
|
44 |
+
|
45 |
+
def __repr__(dtype):
|
46 |
+
arg_str = _construction_repr(dtype, include_align=False)
|
47 |
+
if dtype.isalignedstruct:
|
48 |
+
arg_str = arg_str + ", align=True"
|
49 |
+
return "dtype({})".format(arg_str)
|
50 |
+
|
51 |
+
|
52 |
+
def _unpack_field(dtype, offset, title=None):
|
53 |
+
"""
|
54 |
+
Helper function to normalize the items in dtype.fields.
|
55 |
+
|
56 |
+
Call as:
|
57 |
+
|
58 |
+
dtype, offset, title = _unpack_field(*dtype.fields[name])
|
59 |
+
"""
|
60 |
+
return dtype, offset, title
|
61 |
+
|
62 |
+
|
63 |
+
def _isunsized(dtype):
|
64 |
+
# PyDataType_ISUNSIZED
|
65 |
+
return dtype.itemsize == 0
|
66 |
+
|
67 |
+
|
68 |
+
def _construction_repr(dtype, include_align=False, short=False):
|
69 |
+
"""
|
70 |
+
Creates a string repr of the dtype, excluding the 'dtype()' part
|
71 |
+
surrounding the object. This object may be a string, a list, or
|
72 |
+
a dict depending on the nature of the dtype. This
|
73 |
+
is the object passed as the first parameter to the dtype
|
74 |
+
constructor, and if no additional constructor parameters are
|
75 |
+
given, will reproduce the exact memory layout.
|
76 |
+
|
77 |
+
Parameters
|
78 |
+
----------
|
79 |
+
short : bool
|
80 |
+
If true, this creates a shorter repr using 'kind' and 'itemsize', instead
|
81 |
+
of the longer type name.
|
82 |
+
|
83 |
+
include_align : bool
|
84 |
+
If true, this includes the 'align=True' parameter
|
85 |
+
inside the struct dtype construction dict when needed. Use this flag
|
86 |
+
if you want a proper repr string without the 'dtype()' part around it.
|
87 |
+
|
88 |
+
If false, this does not preserve the
|
89 |
+
'align=True' parameter or sticky NPY_ALIGNED_STRUCT flag for
|
90 |
+
struct arrays like the regular repr does, because the 'align'
|
91 |
+
flag is not part of first dtype constructor parameter. This
|
92 |
+
mode is intended for a full 'repr', where the 'align=True' is
|
93 |
+
provided as the second parameter.
|
94 |
+
"""
|
95 |
+
if dtype.fields is not None:
|
96 |
+
return _struct_str(dtype, include_align=include_align)
|
97 |
+
elif dtype.subdtype:
|
98 |
+
return _subarray_str(dtype)
|
99 |
+
else:
|
100 |
+
return _scalar_str(dtype, short=short)
|
101 |
+
|
102 |
+
|
103 |
+
def _scalar_str(dtype, short):
|
104 |
+
byteorder = _byte_order_str(dtype)
|
105 |
+
|
106 |
+
if dtype.type == np.bool_:
|
107 |
+
if short:
|
108 |
+
return "'?'"
|
109 |
+
else:
|
110 |
+
return "'bool'"
|
111 |
+
|
112 |
+
elif dtype.type == np.object_:
|
113 |
+
# The object reference may be different sizes on different
|
114 |
+
# platforms, so it should never include the itemsize here.
|
115 |
+
return "'O'"
|
116 |
+
|
117 |
+
elif dtype.type == np.bytes_:
|
118 |
+
if _isunsized(dtype):
|
119 |
+
return "'S'"
|
120 |
+
else:
|
121 |
+
return "'S%d'" % dtype.itemsize
|
122 |
+
|
123 |
+
elif dtype.type == np.str_:
|
124 |
+
if _isunsized(dtype):
|
125 |
+
return "'%sU'" % byteorder
|
126 |
+
else:
|
127 |
+
return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
|
128 |
+
|
129 |
+
# unlike the other types, subclasses of void are preserved - but
|
130 |
+
# historically the repr does not actually reveal the subclass
|
131 |
+
elif issubclass(dtype.type, np.void):
|
132 |
+
if _isunsized(dtype):
|
133 |
+
return "'V'"
|
134 |
+
else:
|
135 |
+
return "'V%d'" % dtype.itemsize
|
136 |
+
|
137 |
+
elif dtype.type == np.datetime64:
|
138 |
+
return "'%sM8%s'" % (byteorder, _datetime_metadata_str(dtype))
|
139 |
+
|
140 |
+
elif dtype.type == np.timedelta64:
|
141 |
+
return "'%sm8%s'" % (byteorder, _datetime_metadata_str(dtype))
|
142 |
+
|
143 |
+
elif np.issubdtype(dtype, np.number):
|
144 |
+
# Short repr with endianness, like '<f8'
|
145 |
+
if short or dtype.byteorder not in ('=', '|'):
|
146 |
+
return "'%s%c%d'" % (byteorder, dtype.kind, dtype.itemsize)
|
147 |
+
|
148 |
+
# Longer repr, like 'float64'
|
149 |
+
else:
|
150 |
+
return "'%s%d'" % (_kind_name(dtype), 8*dtype.itemsize)
|
151 |
+
|
152 |
+
elif dtype.isbuiltin == 2:
|
153 |
+
return dtype.type.__name__
|
154 |
+
|
155 |
+
else:
|
156 |
+
raise RuntimeError(
|
157 |
+
"Internal error: NumPy dtype unrecognized type number")
|
158 |
+
|
159 |
+
|
160 |
+
def _byte_order_str(dtype):
|
161 |
+
""" Normalize byteorder to '<' or '>' """
|
162 |
+
# hack to obtain the native and swapped byte order characters
|
163 |
+
swapped = np.dtype(int).newbyteorder('S')
|
164 |
+
native = swapped.newbyteorder('S')
|
165 |
+
|
166 |
+
byteorder = dtype.byteorder
|
167 |
+
if byteorder == '=':
|
168 |
+
return native.byteorder
|
169 |
+
if byteorder == 'S':
|
170 |
+
# TODO: this path can never be reached
|
171 |
+
return swapped.byteorder
|
172 |
+
elif byteorder == '|':
|
173 |
+
return ''
|
174 |
+
else:
|
175 |
+
return byteorder
|
176 |
+
|
177 |
+
|
178 |
+
def _datetime_metadata_str(dtype):
|
179 |
+
# TODO: this duplicates the C metastr_to_unicode functionality
|
180 |
+
unit, count = np.datetime_data(dtype)
|
181 |
+
if unit == 'generic':
|
182 |
+
return ''
|
183 |
+
elif count == 1:
|
184 |
+
return '[{}]'.format(unit)
|
185 |
+
else:
|
186 |
+
return '[{}{}]'.format(count, unit)
|
187 |
+
|
188 |
+
|
189 |
+
def _struct_dict_str(dtype, includealignedflag):
|
190 |
+
# unpack the fields dictionary into ls
|
191 |
+
names = dtype.names
|
192 |
+
fld_dtypes = []
|
193 |
+
offsets = []
|
194 |
+
titles = []
|
195 |
+
for name in names:
|
196 |
+
fld_dtype, offset, title = _unpack_field(*dtype.fields[name])
|
197 |
+
fld_dtypes.append(fld_dtype)
|
198 |
+
offsets.append(offset)
|
199 |
+
titles.append(title)
|
200 |
+
|
201 |
+
# Build up a string to make the dictionary
|
202 |
+
|
203 |
+
if np.core.arrayprint._get_legacy_print_mode() <= 121:
|
204 |
+
colon = ":"
|
205 |
+
fieldsep = ","
|
206 |
+
else:
|
207 |
+
colon = ": "
|
208 |
+
fieldsep = ", "
|
209 |
+
|
210 |
+
# First, the names
|
211 |
+
ret = "{'names'%s[" % colon
|
212 |
+
ret += fieldsep.join(repr(name) for name in names)
|
213 |
+
|
214 |
+
# Second, the formats
|
215 |
+
ret += "], 'formats'%s[" % colon
|
216 |
+
ret += fieldsep.join(
|
217 |
+
_construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
|
218 |
+
|
219 |
+
# Third, the offsets
|
220 |
+
ret += "], 'offsets'%s[" % colon
|
221 |
+
ret += fieldsep.join("%d" % offset for offset in offsets)
|
222 |
+
|
223 |
+
# Fourth, the titles
|
224 |
+
if any(title is not None for title in titles):
|
225 |
+
ret += "], 'titles'%s[" % colon
|
226 |
+
ret += fieldsep.join(repr(title) for title in titles)
|
227 |
+
|
228 |
+
# Fifth, the itemsize
|
229 |
+
ret += "], 'itemsize'%s%d" % (colon, dtype.itemsize)
|
230 |
+
|
231 |
+
if (includealignedflag and dtype.isalignedstruct):
|
232 |
+
# Finally, the aligned flag
|
233 |
+
ret += ", 'aligned'%sTrue}" % colon
|
234 |
+
else:
|
235 |
+
ret += "}"
|
236 |
+
|
237 |
+
return ret
|
238 |
+
|
239 |
+
|
240 |
+
def _aligned_offset(offset, alignment):
|
241 |
+
# round up offset:
|
242 |
+
return - (-offset // alignment) * alignment
|
243 |
+
|
244 |
+
|
245 |
+
def _is_packed(dtype):
|
246 |
+
"""
|
247 |
+
Checks whether the structured data type in 'dtype'
|
248 |
+
has a simple layout, where all the fields are in order,
|
249 |
+
and follow each other with no alignment padding.
|
250 |
+
|
251 |
+
When this returns true, the dtype can be reconstructed
|
252 |
+
from a list of the field names and dtypes with no additional
|
253 |
+
dtype parameters.
|
254 |
+
|
255 |
+
Duplicates the C `is_dtype_struct_simple_unaligned_layout` function.
|
256 |
+
"""
|
257 |
+
align = dtype.isalignedstruct
|
258 |
+
max_alignment = 1
|
259 |
+
total_offset = 0
|
260 |
+
for name in dtype.names:
|
261 |
+
fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
|
262 |
+
|
263 |
+
if align:
|
264 |
+
total_offset = _aligned_offset(total_offset, fld_dtype.alignment)
|
265 |
+
max_alignment = max(max_alignment, fld_dtype.alignment)
|
266 |
+
|
267 |
+
if fld_offset != total_offset:
|
268 |
+
return False
|
269 |
+
total_offset += fld_dtype.itemsize
|
270 |
+
|
271 |
+
if align:
|
272 |
+
total_offset = _aligned_offset(total_offset, max_alignment)
|
273 |
+
|
274 |
+
if total_offset != dtype.itemsize:
|
275 |
+
return False
|
276 |
+
return True
|
277 |
+
|
278 |
+
|
279 |
+
def _struct_list_str(dtype):
|
280 |
+
items = []
|
281 |
+
for name in dtype.names:
|
282 |
+
fld_dtype, fld_offset, title = _unpack_field(*dtype.fields[name])
|
283 |
+
|
284 |
+
item = "("
|
285 |
+
if title is not None:
|
286 |
+
item += "({!r}, {!r}), ".format(title, name)
|
287 |
+
else:
|
288 |
+
item += "{!r}, ".format(name)
|
289 |
+
# Special case subarray handling here
|
290 |
+
if fld_dtype.subdtype is not None:
|
291 |
+
base, shape = fld_dtype.subdtype
|
292 |
+
item += "{}, {}".format(
|
293 |
+
_construction_repr(base, short=True),
|
294 |
+
shape
|
295 |
+
)
|
296 |
+
else:
|
297 |
+
item += _construction_repr(fld_dtype, short=True)
|
298 |
+
|
299 |
+
item += ")"
|
300 |
+
items.append(item)
|
301 |
+
|
302 |
+
return "[" + ", ".join(items) + "]"
|
303 |
+
|
304 |
+
|
305 |
+
def _struct_str(dtype, include_align):
|
306 |
+
# The list str representation can't include the 'align=' flag,
|
307 |
+
# so if it is requested and the struct has the aligned flag set,
|
308 |
+
# we must use the dict str instead.
|
309 |
+
if not (include_align and dtype.isalignedstruct) and _is_packed(dtype):
|
310 |
+
sub = _struct_list_str(dtype)
|
311 |
+
|
312 |
+
else:
|
313 |
+
sub = _struct_dict_str(dtype, include_align)
|
314 |
+
|
315 |
+
# If the data type isn't the default, void, show it
|
316 |
+
if dtype.type != np.void:
|
317 |
+
return "({t.__module__}.{t.__name__}, {f})".format(t=dtype.type, f=sub)
|
318 |
+
else:
|
319 |
+
return sub
|
320 |
+
|
321 |
+
|
322 |
+
def _subarray_str(dtype):
|
323 |
+
base, shape = dtype.subdtype
|
324 |
+
return "({}, {})".format(
|
325 |
+
_construction_repr(base, short=True),
|
326 |
+
shape
|
327 |
+
)
|
328 |
+
|
329 |
+
|
330 |
+
def _name_includes_bit_suffix(dtype):
|
331 |
+
if dtype.type == np.object_:
|
332 |
+
# pointer size varies by system, best to omit it
|
333 |
+
return False
|
334 |
+
elif dtype.type == np.bool_:
|
335 |
+
# implied
|
336 |
+
return False
|
337 |
+
elif dtype.type is None:
|
338 |
+
return True
|
339 |
+
elif np.issubdtype(dtype, np.flexible) and _isunsized(dtype):
|
340 |
+
# unspecified
|
341 |
+
return False
|
342 |
+
else:
|
343 |
+
return True
|
344 |
+
|
345 |
+
|
346 |
+
def _name_get(dtype):
|
347 |
+
# provides dtype.name.__get__, documented as returning a "bit name"
|
348 |
+
|
349 |
+
if dtype.isbuiltin == 2:
|
350 |
+
# user dtypes don't promise to do anything special
|
351 |
+
return dtype.type.__name__
|
352 |
+
|
353 |
+
if dtype.kind == '\x00':
|
354 |
+
name = type(dtype).__name__
|
355 |
+
elif issubclass(dtype.type, np.void):
|
356 |
+
# historically, void subclasses preserve their name, eg `record64`
|
357 |
+
name = dtype.type.__name__
|
358 |
+
else:
|
359 |
+
name = _kind_name(dtype)
|
360 |
+
|
361 |
+
# append bit counts
|
362 |
+
if _name_includes_bit_suffix(dtype):
|
363 |
+
name += "{}".format(dtype.itemsize * 8)
|
364 |
+
|
365 |
+
# append metadata to datetimes
|
366 |
+
if dtype.type in (np.datetime64, np.timedelta64):
|
367 |
+
name += _datetime_metadata_str(dtype)
|
368 |
+
|
369 |
+
return name
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_dtype_ctypes.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 for some types.
|
52 |
+
effective_pack = min(t._pack_, ctypes.alignment(ftyp))
|
53 |
+
current_offset = ((current_offset + effective_pack - 1) // effective_pack) * effective_pack
|
54 |
+
offsets.append(current_offset)
|
55 |
+
current_offset += ctypes.sizeof(ftyp)
|
56 |
+
|
57 |
+
return np.dtype(dict(
|
58 |
+
formats=formats,
|
59 |
+
offsets=offsets,
|
60 |
+
names=names,
|
61 |
+
itemsize=ctypes.sizeof(t)))
|
62 |
+
else:
|
63 |
+
fields = []
|
64 |
+
for fname, ftyp in t._fields_:
|
65 |
+
fields.append((fname, dtype_from_ctypes_type(ftyp)))
|
66 |
+
|
67 |
+
# by default, ctypes structs are aligned
|
68 |
+
return np.dtype(fields, align=True)
|
69 |
+
|
70 |
+
|
71 |
+
def _from_ctypes_scalar(t):
|
72 |
+
"""
|
73 |
+
Return the dtype type with endianness included if it's the case
|
74 |
+
"""
|
75 |
+
if getattr(t, '__ctype_be__', None) is t:
|
76 |
+
return np.dtype('>' + t._type_)
|
77 |
+
elif getattr(t, '__ctype_le__', None) is t:
|
78 |
+
return np.dtype('<' + t._type_)
|
79 |
+
else:
|
80 |
+
return np.dtype(t._type_)
|
81 |
+
|
82 |
+
|
83 |
+
def _from_ctypes_union(t):
|
84 |
+
import ctypes
|
85 |
+
formats = []
|
86 |
+
offsets = []
|
87 |
+
names = []
|
88 |
+
for fname, ftyp in t._fields_:
|
89 |
+
names.append(fname)
|
90 |
+
formats.append(dtype_from_ctypes_type(ftyp))
|
91 |
+
offsets.append(0) # Union fields are offset to 0
|
92 |
+
|
93 |
+
return np.dtype(dict(
|
94 |
+
formats=formats,
|
95 |
+
offsets=offsets,
|
96 |
+
names=names,
|
97 |
+
itemsize=ctypes.sizeof(t)))
|
98 |
+
|
99 |
+
|
100 |
+
def dtype_from_ctypes_type(t):
|
101 |
+
"""
|
102 |
+
Construct a dtype object from a ctypes type
|
103 |
+
"""
|
104 |
+
import _ctypes
|
105 |
+
if issubclass(t, _ctypes.Array):
|
106 |
+
return _from_ctypes_array(t)
|
107 |
+
elif issubclass(t, _ctypes._Pointer):
|
108 |
+
raise TypeError("ctypes pointers have no dtype equivalent")
|
109 |
+
elif issubclass(t, _ctypes.Structure):
|
110 |
+
return _from_ctypes_structure(t)
|
111 |
+
elif issubclass(t, _ctypes.Union):
|
112 |
+
return _from_ctypes_union(t)
|
113 |
+
elif isinstance(getattr(t, '_type_', None), str):
|
114 |
+
return _from_ctypes_scalar(t)
|
115 |
+
else:
|
116 |
+
raise NotImplementedError(
|
117 |
+
"Unknown ctypes type {}".format(t.__name__))
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_internal.py
ADDED
@@ -0,0 +1,935 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A place for internal code
|
3 |
+
|
4 |
+
Some things are more easily handled Python.
|
5 |
+
|
6 |
+
"""
|
7 |
+
import ast
|
8 |
+
import re
|
9 |
+
import sys
|
10 |
+
import warnings
|
11 |
+
|
12 |
+
from ..exceptions import DTypePromotionError
|
13 |
+
from .multiarray import dtype, array, ndarray, promote_types
|
14 |
+
try:
|
15 |
+
import ctypes
|
16 |
+
except ImportError:
|
17 |
+
ctypes = None
|
18 |
+
|
19 |
+
IS_PYPY = sys.implementation.name == 'pypy'
|
20 |
+
|
21 |
+
if sys.byteorder == 'little':
|
22 |
+
_nbo = '<'
|
23 |
+
else:
|
24 |
+
_nbo = '>'
|
25 |
+
|
26 |
+
def _makenames_list(adict, align):
|
27 |
+
allfields = []
|
28 |
+
|
29 |
+
for fname, obj in adict.items():
|
30 |
+
n = len(obj)
|
31 |
+
if not isinstance(obj, tuple) or n not in (2, 3):
|
32 |
+
raise ValueError("entry not a 2- or 3- tuple")
|
33 |
+
if n > 2 and obj[2] == fname:
|
34 |
+
continue
|
35 |
+
num = int(obj[1])
|
36 |
+
if num < 0:
|
37 |
+
raise ValueError("invalid offset.")
|
38 |
+
format = dtype(obj[0], align=align)
|
39 |
+
if n > 2:
|
40 |
+
title = obj[2]
|
41 |
+
else:
|
42 |
+
title = None
|
43 |
+
allfields.append((fname, format, num, title))
|
44 |
+
# sort by offsets
|
45 |
+
allfields.sort(key=lambda x: x[2])
|
46 |
+
names = [x[0] for x in allfields]
|
47 |
+
formats = [x[1] for x in allfields]
|
48 |
+
offsets = [x[2] for x in allfields]
|
49 |
+
titles = [x[3] for x in allfields]
|
50 |
+
|
51 |
+
return names, formats, offsets, titles
|
52 |
+
|
53 |
+
# Called in PyArray_DescrConverter function when
|
54 |
+
# a dictionary without "names" and "formats"
|
55 |
+
# fields is used as a data-type descriptor.
|
56 |
+
def _usefields(adict, align):
|
57 |
+
try:
|
58 |
+
names = adict[-1]
|
59 |
+
except KeyError:
|
60 |
+
names = None
|
61 |
+
if names is None:
|
62 |
+
names, formats, offsets, titles = _makenames_list(adict, align)
|
63 |
+
else:
|
64 |
+
formats = []
|
65 |
+
offsets = []
|
66 |
+
titles = []
|
67 |
+
for name in names:
|
68 |
+
res = adict[name]
|
69 |
+
formats.append(res[0])
|
70 |
+
offsets.append(res[1])
|
71 |
+
if len(res) > 2:
|
72 |
+
titles.append(res[2])
|
73 |
+
else:
|
74 |
+
titles.append(None)
|
75 |
+
|
76 |
+
return dtype({"names": names,
|
77 |
+
"formats": formats,
|
78 |
+
"offsets": offsets,
|
79 |
+
"titles": titles}, align)
|
80 |
+
|
81 |
+
|
82 |
+
# construct an array_protocol descriptor list
|
83 |
+
# from the fields attribute of a descriptor
|
84 |
+
# This calls itself recursively but should eventually hit
|
85 |
+
# a descriptor that has no fields and then return
|
86 |
+
# a simple typestring
|
87 |
+
|
88 |
+
def _array_descr(descriptor):
|
89 |
+
fields = descriptor.fields
|
90 |
+
if fields is None:
|
91 |
+
subdtype = descriptor.subdtype
|
92 |
+
if subdtype is None:
|
93 |
+
if descriptor.metadata is None:
|
94 |
+
return descriptor.str
|
95 |
+
else:
|
96 |
+
new = descriptor.metadata.copy()
|
97 |
+
if new:
|
98 |
+
return (descriptor.str, new)
|
99 |
+
else:
|
100 |
+
return descriptor.str
|
101 |
+
else:
|
102 |
+
return (_array_descr(subdtype[0]), subdtype[1])
|
103 |
+
|
104 |
+
names = descriptor.names
|
105 |
+
ordered_fields = [fields[x] + (x,) for x in names]
|
106 |
+
result = []
|
107 |
+
offset = 0
|
108 |
+
for field in ordered_fields:
|
109 |
+
if field[1] > offset:
|
110 |
+
num = field[1] - offset
|
111 |
+
result.append(('', f'|V{num}'))
|
112 |
+
offset += num
|
113 |
+
elif field[1] < offset:
|
114 |
+
raise ValueError(
|
115 |
+
"dtype.descr is not defined for types with overlapping or "
|
116 |
+
"out-of-order fields")
|
117 |
+
if len(field) > 3:
|
118 |
+
name = (field[2], field[3])
|
119 |
+
else:
|
120 |
+
name = field[2]
|
121 |
+
if field[0].subdtype:
|
122 |
+
tup = (name, _array_descr(field[0].subdtype[0]),
|
123 |
+
field[0].subdtype[1])
|
124 |
+
else:
|
125 |
+
tup = (name, _array_descr(field[0]))
|
126 |
+
offset += field[0].itemsize
|
127 |
+
result.append(tup)
|
128 |
+
|
129 |
+
if descriptor.itemsize > offset:
|
130 |
+
num = descriptor.itemsize - offset
|
131 |
+
result.append(('', f'|V{num}'))
|
132 |
+
|
133 |
+
return result
|
134 |
+
|
135 |
+
# Build a new array from the information in a pickle.
|
136 |
+
# Note that the name numpy.core._internal._reconstruct is embedded in
|
137 |
+
# pickles of ndarrays made with NumPy before release 1.0
|
138 |
+
# so don't remove the name here, or you'll
|
139 |
+
# break backward compatibility.
|
140 |
+
def _reconstruct(subtype, shape, dtype):
|
141 |
+
return ndarray.__new__(subtype, shape, dtype)
|
142 |
+
|
143 |
+
|
144 |
+
# format_re was originally from numarray by J. Todd Miller
|
145 |
+
|
146 |
+
format_re = re.compile(r'(?P<order1>[<>|=]?)'
|
147 |
+
r'(?P<repeats> *[(]?[ ,0-9]*[)]? *)'
|
148 |
+
r'(?P<order2>[<>|=]?)'
|
149 |
+
r'(?P<dtype>[A-Za-z0-9.?]*(?:\[[a-zA-Z0-9,.]+\])?)')
|
150 |
+
sep_re = re.compile(r'\s*,\s*')
|
151 |
+
space_re = re.compile(r'\s+$')
|
152 |
+
|
153 |
+
# astr is a string (perhaps comma separated)
|
154 |
+
|
155 |
+
_convorder = {'=': _nbo}
|
156 |
+
|
157 |
+
def _commastring(astr):
|
158 |
+
startindex = 0
|
159 |
+
result = []
|
160 |
+
while startindex < len(astr):
|
161 |
+
mo = format_re.match(astr, pos=startindex)
|
162 |
+
try:
|
163 |
+
(order1, repeats, order2, dtype) = mo.groups()
|
164 |
+
except (TypeError, AttributeError):
|
165 |
+
raise ValueError(
|
166 |
+
f'format number {len(result)+1} of "{astr}" is not recognized'
|
167 |
+
) from None
|
168 |
+
startindex = mo.end()
|
169 |
+
# Separator or ending padding
|
170 |
+
if startindex < len(astr):
|
171 |
+
if space_re.match(astr, pos=startindex):
|
172 |
+
startindex = len(astr)
|
173 |
+
else:
|
174 |
+
mo = sep_re.match(astr, pos=startindex)
|
175 |
+
if not mo:
|
176 |
+
raise ValueError(
|
177 |
+
'format number %d of "%s" is not recognized' %
|
178 |
+
(len(result)+1, astr))
|
179 |
+
startindex = mo.end()
|
180 |
+
|
181 |
+
if order2 == '':
|
182 |
+
order = order1
|
183 |
+
elif order1 == '':
|
184 |
+
order = order2
|
185 |
+
else:
|
186 |
+
order1 = _convorder.get(order1, order1)
|
187 |
+
order2 = _convorder.get(order2, order2)
|
188 |
+
if (order1 != order2):
|
189 |
+
raise ValueError(
|
190 |
+
'inconsistent byte-order specification %s and %s' %
|
191 |
+
(order1, order2))
|
192 |
+
order = order1
|
193 |
+
|
194 |
+
if order in ('|', '=', _nbo):
|
195 |
+
order = ''
|
196 |
+
dtype = order + dtype
|
197 |
+
if (repeats == ''):
|
198 |
+
newitem = dtype
|
199 |
+
else:
|
200 |
+
newitem = (dtype, ast.literal_eval(repeats))
|
201 |
+
result.append(newitem)
|
202 |
+
|
203 |
+
return result
|
204 |
+
|
205 |
+
class dummy_ctype:
|
206 |
+
def __init__(self, cls):
|
207 |
+
self._cls = cls
|
208 |
+
def __mul__(self, other):
|
209 |
+
return self
|
210 |
+
def __call__(self, *other):
|
211 |
+
return self._cls(other)
|
212 |
+
def __eq__(self, other):
|
213 |
+
return self._cls == other._cls
|
214 |
+
def __ne__(self, other):
|
215 |
+
return self._cls != other._cls
|
216 |
+
|
217 |
+
def _getintp_ctype():
|
218 |
+
val = _getintp_ctype.cache
|
219 |
+
if val is not None:
|
220 |
+
return val
|
221 |
+
if ctypes is None:
|
222 |
+
import numpy as np
|
223 |
+
val = dummy_ctype(np.intp)
|
224 |
+
else:
|
225 |
+
char = dtype('p').char
|
226 |
+
if char == 'i':
|
227 |
+
val = ctypes.c_int
|
228 |
+
elif char == 'l':
|
229 |
+
val = ctypes.c_long
|
230 |
+
elif char == 'q':
|
231 |
+
val = ctypes.c_longlong
|
232 |
+
else:
|
233 |
+
val = ctypes.c_long
|
234 |
+
_getintp_ctype.cache = val
|
235 |
+
return val
|
236 |
+
_getintp_ctype.cache = None
|
237 |
+
|
238 |
+
# Used for .ctypes attribute of ndarray
|
239 |
+
|
240 |
+
class _missing_ctypes:
|
241 |
+
def cast(self, num, obj):
|
242 |
+
return num.value
|
243 |
+
|
244 |
+
class c_void_p:
|
245 |
+
def __init__(self, ptr):
|
246 |
+
self.value = ptr
|
247 |
+
|
248 |
+
|
249 |
+
class _ctypes:
|
250 |
+
def __init__(self, array, ptr=None):
|
251 |
+
self._arr = array
|
252 |
+
|
253 |
+
if ctypes:
|
254 |
+
self._ctypes = ctypes
|
255 |
+
self._data = self._ctypes.c_void_p(ptr)
|
256 |
+
else:
|
257 |
+
# fake a pointer-like object that holds onto the reference
|
258 |
+
self._ctypes = _missing_ctypes()
|
259 |
+
self._data = self._ctypes.c_void_p(ptr)
|
260 |
+
self._data._objects = array
|
261 |
+
|
262 |
+
if self._arr.ndim == 0:
|
263 |
+
self._zerod = True
|
264 |
+
else:
|
265 |
+
self._zerod = False
|
266 |
+
|
267 |
+
def data_as(self, obj):
|
268 |
+
"""
|
269 |
+
Return the data pointer cast to a particular c-types object.
|
270 |
+
For example, calling ``self._as_parameter_`` is equivalent to
|
271 |
+
``self.data_as(ctypes.c_void_p)``. Perhaps you want to use the data as a
|
272 |
+
pointer to a ctypes array of floating-point data:
|
273 |
+
``self.data_as(ctypes.POINTER(ctypes.c_double))``.
|
274 |
+
|
275 |
+
The returned pointer will keep a reference to the array.
|
276 |
+
"""
|
277 |
+
# _ctypes.cast function causes a circular reference of self._data in
|
278 |
+
# self._data._objects. Attributes of self._data cannot be released
|
279 |
+
# until gc.collect is called. Make a copy of the pointer first then let
|
280 |
+
# it hold the array reference. This is a workaround to circumvent the
|
281 |
+
# CPython bug https://bugs.python.org/issue12836
|
282 |
+
ptr = self._ctypes.cast(self._data, obj)
|
283 |
+
ptr._arr = self._arr
|
284 |
+
return ptr
|
285 |
+
|
286 |
+
def shape_as(self, obj):
|
287 |
+
"""
|
288 |
+
Return the shape tuple as an array of some other c-types
|
289 |
+
type. For example: ``self.shape_as(ctypes.c_short)``.
|
290 |
+
"""
|
291 |
+
if self._zerod:
|
292 |
+
return None
|
293 |
+
return (obj*self._arr.ndim)(*self._arr.shape)
|
294 |
+
|
295 |
+
def strides_as(self, obj):
|
296 |
+
"""
|
297 |
+
Return the strides tuple as an array of some other
|
298 |
+
c-types type. For example: ``self.strides_as(ctypes.c_longlong)``.
|
299 |
+
"""
|
300 |
+
if self._zerod:
|
301 |
+
return None
|
302 |
+
return (obj*self._arr.ndim)(*self._arr.strides)
|
303 |
+
|
304 |
+
@property
|
305 |
+
def data(self):
|
306 |
+
"""
|
307 |
+
A pointer to the memory area of the array as a Python integer.
|
308 |
+
This memory area may contain data that is not aligned, or not in correct
|
309 |
+
byte-order. The memory area may not even be writeable. The array
|
310 |
+
flags and data-type of this array should be respected when passing this
|
311 |
+
attribute to arbitrary C-code to avoid trouble that can include Python
|
312 |
+
crashing. User Beware! The value of this attribute is exactly the same
|
313 |
+
as ``self._array_interface_['data'][0]``.
|
314 |
+
|
315 |
+
Note that unlike ``data_as``, a reference will not be kept to the array:
|
316 |
+
code like ``ctypes.c_void_p((a + b).ctypes.data)`` will result in a
|
317 |
+
pointer to a deallocated array, and should be spelt
|
318 |
+
``(a + b).ctypes.data_as(ctypes.c_void_p)``
|
319 |
+
"""
|
320 |
+
return self._data.value
|
321 |
+
|
322 |
+
@property
|
323 |
+
def shape(self):
|
324 |
+
"""
|
325 |
+
(c_intp*self.ndim): A ctypes array of length self.ndim where
|
326 |
+
the basetype is the C-integer corresponding to ``dtype('p')`` on this
|
327 |
+
platform (see `~numpy.ctypeslib.c_intp`). This base-type could be
|
328 |
+
`ctypes.c_int`, `ctypes.c_long`, or `ctypes.c_longlong` depending on
|
329 |
+
the platform. The ctypes array contains the shape of
|
330 |
+
the underlying array.
|
331 |
+
"""
|
332 |
+
return self.shape_as(_getintp_ctype())
|
333 |
+
|
334 |
+
@property
|
335 |
+
def strides(self):
|
336 |
+
"""
|
337 |
+
(c_intp*self.ndim): A ctypes array of length self.ndim where
|
338 |
+
the basetype is the same as for the shape attribute. This ctypes array
|
339 |
+
contains the strides information from the underlying array. This strides
|
340 |
+
information is important for showing how many bytes must be jumped to
|
341 |
+
get to the next element in the array.
|
342 |
+
"""
|
343 |
+
return self.strides_as(_getintp_ctype())
|
344 |
+
|
345 |
+
@property
|
346 |
+
def _as_parameter_(self):
|
347 |
+
"""
|
348 |
+
Overrides the ctypes semi-magic method
|
349 |
+
|
350 |
+
Enables `c_func(some_array.ctypes)`
|
351 |
+
"""
|
352 |
+
return self.data_as(ctypes.c_void_p)
|
353 |
+
|
354 |
+
# Numpy 1.21.0, 2021-05-18
|
355 |
+
|
356 |
+
def get_data(self):
|
357 |
+
"""Deprecated getter for the `_ctypes.data` property.
|
358 |
+
|
359 |
+
.. deprecated:: 1.21
|
360 |
+
"""
|
361 |
+
warnings.warn('"get_data" is deprecated. Use "data" instead',
|
362 |
+
DeprecationWarning, stacklevel=2)
|
363 |
+
return self.data
|
364 |
+
|
365 |
+
def get_shape(self):
|
366 |
+
"""Deprecated getter for the `_ctypes.shape` property.
|
367 |
+
|
368 |
+
.. deprecated:: 1.21
|
369 |
+
"""
|
370 |
+
warnings.warn('"get_shape" is deprecated. Use "shape" instead',
|
371 |
+
DeprecationWarning, stacklevel=2)
|
372 |
+
return self.shape
|
373 |
+
|
374 |
+
def get_strides(self):
|
375 |
+
"""Deprecated getter for the `_ctypes.strides` property.
|
376 |
+
|
377 |
+
.. deprecated:: 1.21
|
378 |
+
"""
|
379 |
+
warnings.warn('"get_strides" is deprecated. Use "strides" instead',
|
380 |
+
DeprecationWarning, stacklevel=2)
|
381 |
+
return self.strides
|
382 |
+
|
383 |
+
def get_as_parameter(self):
|
384 |
+
"""Deprecated getter for the `_ctypes._as_parameter_` property.
|
385 |
+
|
386 |
+
.. deprecated:: 1.21
|
387 |
+
"""
|
388 |
+
warnings.warn(
|
389 |
+
'"get_as_parameter" is deprecated. Use "_as_parameter_" instead',
|
390 |
+
DeprecationWarning, stacklevel=2,
|
391 |
+
)
|
392 |
+
return self._as_parameter_
|
393 |
+
|
394 |
+
|
395 |
+
def _newnames(datatype, order):
|
396 |
+
"""
|
397 |
+
Given a datatype and an order object, return a new names tuple, with the
|
398 |
+
order indicated
|
399 |
+
"""
|
400 |
+
oldnames = datatype.names
|
401 |
+
nameslist = list(oldnames)
|
402 |
+
if isinstance(order, str):
|
403 |
+
order = [order]
|
404 |
+
seen = set()
|
405 |
+
if isinstance(order, (list, tuple)):
|
406 |
+
for name in order:
|
407 |
+
try:
|
408 |
+
nameslist.remove(name)
|
409 |
+
except ValueError:
|
410 |
+
if name in seen:
|
411 |
+
raise ValueError(f"duplicate field name: {name}") from None
|
412 |
+
else:
|
413 |
+
raise ValueError(f"unknown field name: {name}") from None
|
414 |
+
seen.add(name)
|
415 |
+
return tuple(list(order) + nameslist)
|
416 |
+
raise ValueError(f"unsupported order value: {order}")
|
417 |
+
|
418 |
+
def _copy_fields(ary):
|
419 |
+
"""Return copy of structured array with padding between fields removed.
|
420 |
+
|
421 |
+
Parameters
|
422 |
+
----------
|
423 |
+
ary : ndarray
|
424 |
+
Structured array from which to remove padding bytes
|
425 |
+
|
426 |
+
Returns
|
427 |
+
-------
|
428 |
+
ary_copy : ndarray
|
429 |
+
Copy of ary with padding bytes removed
|
430 |
+
"""
|
431 |
+
dt = ary.dtype
|
432 |
+
copy_dtype = {'names': dt.names,
|
433 |
+
'formats': [dt.fields[name][0] for name in dt.names]}
|
434 |
+
return array(ary, dtype=copy_dtype, copy=True)
|
435 |
+
|
436 |
+
def _promote_fields(dt1, dt2):
|
437 |
+
""" Perform type promotion for two structured dtypes.
|
438 |
+
|
439 |
+
Parameters
|
440 |
+
----------
|
441 |
+
dt1 : structured dtype
|
442 |
+
First dtype.
|
443 |
+
dt2 : structured dtype
|
444 |
+
Second dtype.
|
445 |
+
|
446 |
+
Returns
|
447 |
+
-------
|
448 |
+
out : dtype
|
449 |
+
The promoted dtype
|
450 |
+
|
451 |
+
Notes
|
452 |
+
-----
|
453 |
+
If one of the inputs is aligned, the result will be. The titles of
|
454 |
+
both descriptors must match (point to the same field).
|
455 |
+
"""
|
456 |
+
# Both must be structured and have the same names in the same order
|
457 |
+
if (dt1.names is None or dt2.names is None) or dt1.names != dt2.names:
|
458 |
+
raise DTypePromotionError(
|
459 |
+
f"field names `{dt1.names}` and `{dt2.names}` mismatch.")
|
460 |
+
|
461 |
+
# if both are identical, we can (maybe!) just return the same dtype.
|
462 |
+
identical = dt1 is dt2
|
463 |
+
new_fields = []
|
464 |
+
for name in dt1.names:
|
465 |
+
field1 = dt1.fields[name]
|
466 |
+
field2 = dt2.fields[name]
|
467 |
+
new_descr = promote_types(field1[0], field2[0])
|
468 |
+
identical = identical and new_descr is field1[0]
|
469 |
+
|
470 |
+
# Check that the titles match (if given):
|
471 |
+
if field1[2:] != field2[2:]:
|
472 |
+
raise DTypePromotionError(
|
473 |
+
f"field titles of field '{name}' mismatch")
|
474 |
+
if len(field1) == 2:
|
475 |
+
new_fields.append((name, new_descr))
|
476 |
+
else:
|
477 |
+
new_fields.append(((field1[2], name), new_descr))
|
478 |
+
|
479 |
+
res = dtype(new_fields, align=dt1.isalignedstruct or dt2.isalignedstruct)
|
480 |
+
|
481 |
+
# Might as well preserve identity (and metadata) if the dtype is identical
|
482 |
+
# and the itemsize, offsets are also unmodified. This could probably be
|
483 |
+
# sped up, but also probably just be removed entirely.
|
484 |
+
if identical and res.itemsize == dt1.itemsize:
|
485 |
+
for name in dt1.names:
|
486 |
+
if dt1.fields[name][1] != res.fields[name][1]:
|
487 |
+
return res # the dtype changed.
|
488 |
+
return dt1
|
489 |
+
|
490 |
+
return res
|
491 |
+
|
492 |
+
|
493 |
+
def _getfield_is_safe(oldtype, newtype, offset):
|
494 |
+
""" Checks safety of getfield for object arrays.
|
495 |
+
|
496 |
+
As in _view_is_safe, we need to check that memory containing objects is not
|
497 |
+
reinterpreted as a non-object datatype and vice versa.
|
498 |
+
|
499 |
+
Parameters
|
500 |
+
----------
|
501 |
+
oldtype : data-type
|
502 |
+
Data type of the original ndarray.
|
503 |
+
newtype : data-type
|
504 |
+
Data type of the field being accessed by ndarray.getfield
|
505 |
+
offset : int
|
506 |
+
Offset of the field being accessed by ndarray.getfield
|
507 |
+
|
508 |
+
Raises
|
509 |
+
------
|
510 |
+
TypeError
|
511 |
+
If the field access is invalid
|
512 |
+
|
513 |
+
"""
|
514 |
+
if newtype.hasobject or oldtype.hasobject:
|
515 |
+
if offset == 0 and newtype == oldtype:
|
516 |
+
return
|
517 |
+
if oldtype.names is not None:
|
518 |
+
for name in oldtype.names:
|
519 |
+
if (oldtype.fields[name][1] == offset and
|
520 |
+
oldtype.fields[name][0] == newtype):
|
521 |
+
return
|
522 |
+
raise TypeError("Cannot get/set field of an object array")
|
523 |
+
return
|
524 |
+
|
525 |
+
def _view_is_safe(oldtype, newtype):
|
526 |
+
""" Checks safety of a view involving object arrays, for example when
|
527 |
+
doing::
|
528 |
+
|
529 |
+
np.zeros(10, dtype=oldtype).view(newtype)
|
530 |
+
|
531 |
+
Parameters
|
532 |
+
----------
|
533 |
+
oldtype : data-type
|
534 |
+
Data type of original ndarray
|
535 |
+
newtype : data-type
|
536 |
+
Data type of the view
|
537 |
+
|
538 |
+
Raises
|
539 |
+
------
|
540 |
+
TypeError
|
541 |
+
If the new type is incompatible with the old type.
|
542 |
+
|
543 |
+
"""
|
544 |
+
|
545 |
+
# if the types are equivalent, there is no problem.
|
546 |
+
# for example: dtype((np.record, 'i4,i4')) == dtype((np.void, 'i4,i4'))
|
547 |
+
if oldtype == newtype:
|
548 |
+
return
|
549 |
+
|
550 |
+
if newtype.hasobject or oldtype.hasobject:
|
551 |
+
raise TypeError("Cannot change data-type for object array.")
|
552 |
+
return
|
553 |
+
|
554 |
+
# Given a string containing a PEP 3118 format specifier,
|
555 |
+
# construct a NumPy dtype
|
556 |
+
|
557 |
+
_pep3118_native_map = {
|
558 |
+
'?': '?',
|
559 |
+
'c': 'S1',
|
560 |
+
'b': 'b',
|
561 |
+
'B': 'B',
|
562 |
+
'h': 'h',
|
563 |
+
'H': 'H',
|
564 |
+
'i': 'i',
|
565 |
+
'I': 'I',
|
566 |
+
'l': 'l',
|
567 |
+
'L': 'L',
|
568 |
+
'q': 'q',
|
569 |
+
'Q': 'Q',
|
570 |
+
'e': 'e',
|
571 |
+
'f': 'f',
|
572 |
+
'd': 'd',
|
573 |
+
'g': 'g',
|
574 |
+
'Zf': 'F',
|
575 |
+
'Zd': 'D',
|
576 |
+
'Zg': 'G',
|
577 |
+
's': 'S',
|
578 |
+
'w': 'U',
|
579 |
+
'O': 'O',
|
580 |
+
'x': 'V', # padding
|
581 |
+
}
|
582 |
+
_pep3118_native_typechars = ''.join(_pep3118_native_map.keys())
|
583 |
+
|
584 |
+
_pep3118_standard_map = {
|
585 |
+
'?': '?',
|
586 |
+
'c': 'S1',
|
587 |
+
'b': 'b',
|
588 |
+
'B': 'B',
|
589 |
+
'h': 'i2',
|
590 |
+
'H': 'u2',
|
591 |
+
'i': 'i4',
|
592 |
+
'I': 'u4',
|
593 |
+
'l': 'i4',
|
594 |
+
'L': 'u4',
|
595 |
+
'q': 'i8',
|
596 |
+
'Q': 'u8',
|
597 |
+
'e': 'f2',
|
598 |
+
'f': 'f',
|
599 |
+
'd': 'd',
|
600 |
+
'Zf': 'F',
|
601 |
+
'Zd': 'D',
|
602 |
+
's': 'S',
|
603 |
+
'w': 'U',
|
604 |
+
'O': 'O',
|
605 |
+
'x': 'V', # padding
|
606 |
+
}
|
607 |
+
_pep3118_standard_typechars = ''.join(_pep3118_standard_map.keys())
|
608 |
+
|
609 |
+
_pep3118_unsupported_map = {
|
610 |
+
'u': 'UCS-2 strings',
|
611 |
+
'&': 'pointers',
|
612 |
+
't': 'bitfields',
|
613 |
+
'X': 'function pointers',
|
614 |
+
}
|
615 |
+
|
616 |
+
class _Stream:
|
617 |
+
def __init__(self, s):
|
618 |
+
self.s = s
|
619 |
+
self.byteorder = '@'
|
620 |
+
|
621 |
+
def advance(self, n):
|
622 |
+
res = self.s[:n]
|
623 |
+
self.s = self.s[n:]
|
624 |
+
return res
|
625 |
+
|
626 |
+
def consume(self, c):
|
627 |
+
if self.s[:len(c)] == c:
|
628 |
+
self.advance(len(c))
|
629 |
+
return True
|
630 |
+
return False
|
631 |
+
|
632 |
+
def consume_until(self, c):
|
633 |
+
if callable(c):
|
634 |
+
i = 0
|
635 |
+
while i < len(self.s) and not c(self.s[i]):
|
636 |
+
i = i + 1
|
637 |
+
return self.advance(i)
|
638 |
+
else:
|
639 |
+
i = self.s.index(c)
|
640 |
+
res = self.advance(i)
|
641 |
+
self.advance(len(c))
|
642 |
+
return res
|
643 |
+
|
644 |
+
@property
|
645 |
+
def next(self):
|
646 |
+
return self.s[0]
|
647 |
+
|
648 |
+
def __bool__(self):
|
649 |
+
return bool(self.s)
|
650 |
+
|
651 |
+
|
652 |
+
def _dtype_from_pep3118(spec):
|
653 |
+
stream = _Stream(spec)
|
654 |
+
dtype, align = __dtype_from_pep3118(stream, is_subdtype=False)
|
655 |
+
return dtype
|
656 |
+
|
657 |
+
def __dtype_from_pep3118(stream, is_subdtype):
|
658 |
+
field_spec = dict(
|
659 |
+
names=[],
|
660 |
+
formats=[],
|
661 |
+
offsets=[],
|
662 |
+
itemsize=0
|
663 |
+
)
|
664 |
+
offset = 0
|
665 |
+
common_alignment = 1
|
666 |
+
is_padding = False
|
667 |
+
|
668 |
+
# Parse spec
|
669 |
+
while stream:
|
670 |
+
value = None
|
671 |
+
|
672 |
+
# End of structure, bail out to upper level
|
673 |
+
if stream.consume('}'):
|
674 |
+
break
|
675 |
+
|
676 |
+
# Sub-arrays (1)
|
677 |
+
shape = None
|
678 |
+
if stream.consume('('):
|
679 |
+
shape = stream.consume_until(')')
|
680 |
+
shape = tuple(map(int, shape.split(',')))
|
681 |
+
|
682 |
+
# Byte order
|
683 |
+
if stream.next in ('@', '=', '<', '>', '^', '!'):
|
684 |
+
byteorder = stream.advance(1)
|
685 |
+
if byteorder == '!':
|
686 |
+
byteorder = '>'
|
687 |
+
stream.byteorder = byteorder
|
688 |
+
|
689 |
+
# Byte order characters also control native vs. standard type sizes
|
690 |
+
if stream.byteorder in ('@', '^'):
|
691 |
+
type_map = _pep3118_native_map
|
692 |
+
type_map_chars = _pep3118_native_typechars
|
693 |
+
else:
|
694 |
+
type_map = _pep3118_standard_map
|
695 |
+
type_map_chars = _pep3118_standard_typechars
|
696 |
+
|
697 |
+
# Item sizes
|
698 |
+
itemsize_str = stream.consume_until(lambda c: not c.isdigit())
|
699 |
+
if itemsize_str:
|
700 |
+
itemsize = int(itemsize_str)
|
701 |
+
else:
|
702 |
+
itemsize = 1
|
703 |
+
|
704 |
+
# Data types
|
705 |
+
is_padding = False
|
706 |
+
|
707 |
+
if stream.consume('T{'):
|
708 |
+
value, align = __dtype_from_pep3118(
|
709 |
+
stream, is_subdtype=True)
|
710 |
+
elif stream.next in type_map_chars:
|
711 |
+
if stream.next == 'Z':
|
712 |
+
typechar = stream.advance(2)
|
713 |
+
else:
|
714 |
+
typechar = stream.advance(1)
|
715 |
+
|
716 |
+
is_padding = (typechar == 'x')
|
717 |
+
dtypechar = type_map[typechar]
|
718 |
+
if dtypechar in 'USV':
|
719 |
+
dtypechar += '%d' % itemsize
|
720 |
+
itemsize = 1
|
721 |
+
numpy_byteorder = {'@': '=', '^': '='}.get(
|
722 |
+
stream.byteorder, stream.byteorder)
|
723 |
+
value = dtype(numpy_byteorder + dtypechar)
|
724 |
+
align = value.alignment
|
725 |
+
elif stream.next in _pep3118_unsupported_map:
|
726 |
+
desc = _pep3118_unsupported_map[stream.next]
|
727 |
+
raise NotImplementedError(
|
728 |
+
"Unrepresentable PEP 3118 data type {!r} ({})"
|
729 |
+
.format(stream.next, desc))
|
730 |
+
else:
|
731 |
+
raise ValueError("Unknown PEP 3118 data type specifier %r" % stream.s)
|
732 |
+
|
733 |
+
#
|
734 |
+
# Native alignment may require padding
|
735 |
+
#
|
736 |
+
# Here we assume that the presence of a '@' character implicitly implies
|
737 |
+
# that the start of the array is *already* aligned.
|
738 |
+
#
|
739 |
+
extra_offset = 0
|
740 |
+
if stream.byteorder == '@':
|
741 |
+
start_padding = (-offset) % align
|
742 |
+
intra_padding = (-value.itemsize) % align
|
743 |
+
|
744 |
+
offset += start_padding
|
745 |
+
|
746 |
+
if intra_padding != 0:
|
747 |
+
if itemsize > 1 or (shape is not None and _prod(shape) > 1):
|
748 |
+
# Inject internal padding to the end of the sub-item
|
749 |
+
value = _add_trailing_padding(value, intra_padding)
|
750 |
+
else:
|
751 |
+
# We can postpone the injection of internal padding,
|
752 |
+
# as the item appears at most once
|
753 |
+
extra_offset += intra_padding
|
754 |
+
|
755 |
+
# Update common alignment
|
756 |
+
common_alignment = _lcm(align, common_alignment)
|
757 |
+
|
758 |
+
# Convert itemsize to sub-array
|
759 |
+
if itemsize != 1:
|
760 |
+
value = dtype((value, (itemsize,)))
|
761 |
+
|
762 |
+
# Sub-arrays (2)
|
763 |
+
if shape is not None:
|
764 |
+
value = dtype((value, shape))
|
765 |
+
|
766 |
+
# Field name
|
767 |
+
if stream.consume(':'):
|
768 |
+
name = stream.consume_until(':')
|
769 |
+
else:
|
770 |
+
name = None
|
771 |
+
|
772 |
+
if not (is_padding and name is None):
|
773 |
+
if name is not None and name in field_spec['names']:
|
774 |
+
raise RuntimeError(f"Duplicate field name '{name}' in PEP3118 format")
|
775 |
+
field_spec['names'].append(name)
|
776 |
+
field_spec['formats'].append(value)
|
777 |
+
field_spec['offsets'].append(offset)
|
778 |
+
|
779 |
+
offset += value.itemsize
|
780 |
+
offset += extra_offset
|
781 |
+
|
782 |
+
field_spec['itemsize'] = offset
|
783 |
+
|
784 |
+
# extra final padding for aligned types
|
785 |
+
if stream.byteorder == '@':
|
786 |
+
field_spec['itemsize'] += (-offset) % common_alignment
|
787 |
+
|
788 |
+
# Check if this was a simple 1-item type, and unwrap it
|
789 |
+
if (field_spec['names'] == [None]
|
790 |
+
and field_spec['offsets'][0] == 0
|
791 |
+
and field_spec['itemsize'] == field_spec['formats'][0].itemsize
|
792 |
+
and not is_subdtype):
|
793 |
+
ret = field_spec['formats'][0]
|
794 |
+
else:
|
795 |
+
_fix_names(field_spec)
|
796 |
+
ret = dtype(field_spec)
|
797 |
+
|
798 |
+
# Finished
|
799 |
+
return ret, common_alignment
|
800 |
+
|
801 |
+
def _fix_names(field_spec):
|
802 |
+
""" Replace names which are None with the next unused f%d name """
|
803 |
+
names = field_spec['names']
|
804 |
+
for i, name in enumerate(names):
|
805 |
+
if name is not None:
|
806 |
+
continue
|
807 |
+
|
808 |
+
j = 0
|
809 |
+
while True:
|
810 |
+
name = f'f{j}'
|
811 |
+
if name not in names:
|
812 |
+
break
|
813 |
+
j = j + 1
|
814 |
+
names[i] = name
|
815 |
+
|
816 |
+
def _add_trailing_padding(value, padding):
|
817 |
+
"""Inject the specified number of padding bytes at the end of a dtype"""
|
818 |
+
if value.fields is None:
|
819 |
+
field_spec = dict(
|
820 |
+
names=['f0'],
|
821 |
+
formats=[value],
|
822 |
+
offsets=[0],
|
823 |
+
itemsize=value.itemsize
|
824 |
+
)
|
825 |
+
else:
|
826 |
+
fields = value.fields
|
827 |
+
names = value.names
|
828 |
+
field_spec = dict(
|
829 |
+
names=names,
|
830 |
+
formats=[fields[name][0] for name in names],
|
831 |
+
offsets=[fields[name][1] for name in names],
|
832 |
+
itemsize=value.itemsize
|
833 |
+
)
|
834 |
+
|
835 |
+
field_spec['itemsize'] += padding
|
836 |
+
return dtype(field_spec)
|
837 |
+
|
838 |
+
def _prod(a):
|
839 |
+
p = 1
|
840 |
+
for x in a:
|
841 |
+
p *= x
|
842 |
+
return p
|
843 |
+
|
844 |
+
def _gcd(a, b):
|
845 |
+
"""Calculate the greatest common divisor of a and b"""
|
846 |
+
while b:
|
847 |
+
a, b = b, a % b
|
848 |
+
return a
|
849 |
+
|
850 |
+
def _lcm(a, b):
|
851 |
+
return a // _gcd(a, b) * b
|
852 |
+
|
853 |
+
def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
|
854 |
+
""" Format the error message for when __array_ufunc__ gives up. """
|
855 |
+
args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] +
|
856 |
+
['{}={!r}'.format(k, v)
|
857 |
+
for k, v in kwargs.items()])
|
858 |
+
args = inputs + kwargs.get('out', ())
|
859 |
+
types_string = ', '.join(repr(type(arg).__name__) for arg in args)
|
860 |
+
return ('operand type(s) all returned NotImplemented from '
|
861 |
+
'__array_ufunc__({!r}, {!r}, {}): {}'
|
862 |
+
.format(ufunc, method, args_string, types_string))
|
863 |
+
|
864 |
+
|
865 |
+
def array_function_errmsg_formatter(public_api, types):
|
866 |
+
""" Format the error message for when __array_ufunc__ gives up. """
|
867 |
+
func_name = '{}.{}'.format(public_api.__module__, public_api.__name__)
|
868 |
+
return ("no implementation found for '{}' on types that implement "
|
869 |
+
'__array_function__: {}'.format(func_name, list(types)))
|
870 |
+
|
871 |
+
|
872 |
+
def _ufunc_doc_signature_formatter(ufunc):
|
873 |
+
"""
|
874 |
+
Builds a signature string which resembles PEP 457
|
875 |
+
|
876 |
+
This is used to construct the first line of the docstring
|
877 |
+
"""
|
878 |
+
|
879 |
+
# input arguments are simple
|
880 |
+
if ufunc.nin == 1:
|
881 |
+
in_args = 'x'
|
882 |
+
else:
|
883 |
+
in_args = ', '.join(f'x{i+1}' for i in range(ufunc.nin))
|
884 |
+
|
885 |
+
# output arguments are both keyword or positional
|
886 |
+
if ufunc.nout == 0:
|
887 |
+
out_args = ', /, out=()'
|
888 |
+
elif ufunc.nout == 1:
|
889 |
+
out_args = ', /, out=None'
|
890 |
+
else:
|
891 |
+
out_args = '[, {positional}], / [, out={default}]'.format(
|
892 |
+
positional=', '.join(
|
893 |
+
'out{}'.format(i+1) for i in range(ufunc.nout)),
|
894 |
+
default=repr((None,)*ufunc.nout)
|
895 |
+
)
|
896 |
+
|
897 |
+
# keyword only args depend on whether this is a gufunc
|
898 |
+
kwargs = (
|
899 |
+
", casting='same_kind'"
|
900 |
+
", order='K'"
|
901 |
+
", dtype=None"
|
902 |
+
", subok=True"
|
903 |
+
)
|
904 |
+
|
905 |
+
# NOTE: gufuncs may or may not support the `axis` parameter
|
906 |
+
if ufunc.signature is None:
|
907 |
+
kwargs = f", where=True{kwargs}[, signature, extobj]"
|
908 |
+
else:
|
909 |
+
kwargs += "[, signature, extobj, axes, axis]"
|
910 |
+
|
911 |
+
# join all the parts together
|
912 |
+
return '{name}({in_args}{out_args}, *{kwargs})'.format(
|
913 |
+
name=ufunc.__name__,
|
914 |
+
in_args=in_args,
|
915 |
+
out_args=out_args,
|
916 |
+
kwargs=kwargs
|
917 |
+
)
|
918 |
+
|
919 |
+
|
920 |
+
def npy_ctypes_check(cls):
|
921 |
+
# determine if a class comes from ctypes, in order to work around
|
922 |
+
# a bug in the buffer protocol for those objects, bpo-10746
|
923 |
+
try:
|
924 |
+
# ctypes class are new-style, so have an __mro__. This probably fails
|
925 |
+
# for ctypes classes with multiple inheritance.
|
926 |
+
if IS_PYPY:
|
927 |
+
# (..., _ctypes.basics._CData, Bufferable, object)
|
928 |
+
ctype_base = cls.__mro__[-3]
|
929 |
+
else:
|
930 |
+
# # (..., _ctypes._CData, object)
|
931 |
+
ctype_base = cls.__mro__[-2]
|
932 |
+
# right now, they're part of the _ctypes module
|
933 |
+
return '_ctypes' in ctype_base.__module__
|
934 |
+
except Exception:
|
935 |
+
return False
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_internal.pyi
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, TypeVar, overload, Generic
|
2 |
+
import ctypes as ct
|
3 |
+
|
4 |
+
from numpy import ndarray
|
5 |
+
from numpy.ctypeslib import c_intp
|
6 |
+
|
7 |
+
_CastT = TypeVar("_CastT", bound=ct._CanCastTo) # Copied from `ctypes.cast`
|
8 |
+
_CT = TypeVar("_CT", bound=ct._CData)
|
9 |
+
_PT = TypeVar("_PT", bound=None | int)
|
10 |
+
|
11 |
+
# TODO: Let the likes of `shape_as` and `strides_as` return `None`
|
12 |
+
# for 0D arrays once we've got shape-support
|
13 |
+
|
14 |
+
class _ctypes(Generic[_PT]):
|
15 |
+
@overload
|
16 |
+
def __new__(cls, array: ndarray[Any, Any], ptr: None = ...) -> _ctypes[None]: ...
|
17 |
+
@overload
|
18 |
+
def __new__(cls, array: ndarray[Any, Any], ptr: _PT) -> _ctypes[_PT]: ...
|
19 |
+
@property
|
20 |
+
def data(self) -> _PT: ...
|
21 |
+
@property
|
22 |
+
def shape(self) -> ct.Array[c_intp]: ...
|
23 |
+
@property
|
24 |
+
def strides(self) -> ct.Array[c_intp]: ...
|
25 |
+
@property
|
26 |
+
def _as_parameter_(self) -> ct.c_void_p: ...
|
27 |
+
|
28 |
+
def data_as(self, obj: type[_CastT]) -> _CastT: ...
|
29 |
+
def shape_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
|
30 |
+
def strides_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_methods.py
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 warnings
|
7 |
+
from contextlib import nullcontext
|
8 |
+
|
9 |
+
from numpy.core import multiarray as mu
|
10 |
+
from numpy.core import umath as um
|
11 |
+
from numpy.core.multiarray import asanyarray
|
12 |
+
from numpy.core import numerictypes as nt
|
13 |
+
from numpy.core import _exceptions
|
14 |
+
from numpy.core._ufunc_config import _no_nep50_warning
|
15 |
+
from numpy._globals import _NoValue
|
16 |
+
from numpy.compat import pickle, os_fspath
|
17 |
+
|
18 |
+
# save those O(100) nanoseconds!
|
19 |
+
umr_maximum = um.maximum.reduce
|
20 |
+
umr_minimum = um.minimum.reduce
|
21 |
+
umr_sum = um.add.reduce
|
22 |
+
umr_prod = um.multiply.reduce
|
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 |
+
# Parsing keyword arguments is currently fairly slow, so avoid it for now
|
57 |
+
if where is True:
|
58 |
+
return umr_any(a, axis, dtype, out, keepdims)
|
59 |
+
return umr_any(a, axis, dtype, out, keepdims, where=where)
|
60 |
+
|
61 |
+
def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
|
62 |
+
# Parsing keyword arguments is currently fairly slow, so avoid it for now
|
63 |
+
if where is True:
|
64 |
+
return umr_all(a, axis, dtype, out, keepdims)
|
65 |
+
return umr_all(a, axis, dtype, out, keepdims, where=where)
|
66 |
+
|
67 |
+
def _count_reduce_items(arr, axis, keepdims=False, where=True):
|
68 |
+
# fast-path for the default case
|
69 |
+
if where is True:
|
70 |
+
# no boolean mask given, calculate items according to axis
|
71 |
+
if axis is None:
|
72 |
+
axis = tuple(range(arr.ndim))
|
73 |
+
elif not isinstance(axis, tuple):
|
74 |
+
axis = (axis,)
|
75 |
+
items = 1
|
76 |
+
for ax in axis:
|
77 |
+
items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
|
78 |
+
items = nt.intp(items)
|
79 |
+
else:
|
80 |
+
# TODO: Optimize case when `where` is broadcast along a non-reduction
|
81 |
+
# axis and full sum is more excessive than needed.
|
82 |
+
|
83 |
+
# guarded to protect circular imports
|
84 |
+
from numpy.lib.stride_tricks import broadcast_to
|
85 |
+
# count True values in (potentially broadcasted) boolean mask
|
86 |
+
items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
|
87 |
+
keepdims)
|
88 |
+
return items
|
89 |
+
|
90 |
+
def _clip(a, min=None, max=None, out=None, **kwargs):
|
91 |
+
if min is None and max is None:
|
92 |
+
raise ValueError("One of max or min must be given")
|
93 |
+
|
94 |
+
if min is None:
|
95 |
+
return um.minimum(a, max, out=out, **kwargs)
|
96 |
+
elif max is None:
|
97 |
+
return um.maximum(a, min, out=out, **kwargs)
|
98 |
+
else:
|
99 |
+
return um.clip(a, min, max, out=out, **kwargs)
|
100 |
+
|
101 |
+
def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
|
102 |
+
arr = asanyarray(a)
|
103 |
+
|
104 |
+
is_float16_result = False
|
105 |
+
|
106 |
+
rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
|
107 |
+
if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
|
108 |
+
warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
|
109 |
+
|
110 |
+
# Cast bool, unsigned int, and int to float64 by default
|
111 |
+
if dtype is None:
|
112 |
+
if issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
|
113 |
+
dtype = mu.dtype('f8')
|
114 |
+
elif issubclass(arr.dtype.type, nt.float16):
|
115 |
+
dtype = mu.dtype('f4')
|
116 |
+
is_float16_result = True
|
117 |
+
|
118 |
+
ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
|
119 |
+
if isinstance(ret, mu.ndarray):
|
120 |
+
with _no_nep50_warning():
|
121 |
+
ret = um.true_divide(
|
122 |
+
ret, rcount, out=ret, casting='unsafe', subok=False)
|
123 |
+
if is_float16_result and out is None:
|
124 |
+
ret = arr.dtype.type(ret)
|
125 |
+
elif hasattr(ret, 'dtype'):
|
126 |
+
if is_float16_result:
|
127 |
+
ret = arr.dtype.type(ret / rcount)
|
128 |
+
else:
|
129 |
+
ret = ret.dtype.type(ret / rcount)
|
130 |
+
else:
|
131 |
+
ret = ret / rcount
|
132 |
+
|
133 |
+
return ret
|
134 |
+
|
135 |
+
def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
|
136 |
+
where=True):
|
137 |
+
arr = asanyarray(a)
|
138 |
+
|
139 |
+
rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
|
140 |
+
# Make this warning show up on top.
|
141 |
+
if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
|
142 |
+
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
|
143 |
+
stacklevel=2)
|
144 |
+
|
145 |
+
# Cast bool, unsigned int, and int to float64 by default
|
146 |
+
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
|
147 |
+
dtype = mu.dtype('f8')
|
148 |
+
|
149 |
+
# Compute the mean.
|
150 |
+
# Note that if dtype is not of inexact type then arraymean will
|
151 |
+
# not be either.
|
152 |
+
arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
|
153 |
+
# The shape of rcount has to match arrmean to not change the shape of out
|
154 |
+
# in broadcasting. Otherwise, it cannot be stored back to arrmean.
|
155 |
+
if rcount.ndim == 0:
|
156 |
+
# fast-path for default case when where is True
|
157 |
+
div = rcount
|
158 |
+
else:
|
159 |
+
# matching rcount to arrmean when where is specified as array
|
160 |
+
div = rcount.reshape(arrmean.shape)
|
161 |
+
if isinstance(arrmean, mu.ndarray):
|
162 |
+
with _no_nep50_warning():
|
163 |
+
arrmean = um.true_divide(arrmean, div, out=arrmean,
|
164 |
+
casting='unsafe', subok=False)
|
165 |
+
elif hasattr(arrmean, "dtype"):
|
166 |
+
arrmean = arrmean.dtype.type(arrmean / rcount)
|
167 |
+
else:
|
168 |
+
arrmean = arrmean / rcount
|
169 |
+
|
170 |
+
# Compute sum of squared deviations from mean
|
171 |
+
# Note that x may not be inexact and that we need it to be an array,
|
172 |
+
# not a scalar.
|
173 |
+
x = asanyarray(arr - arrmean)
|
174 |
+
|
175 |
+
if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
|
176 |
+
x = um.multiply(x, x, out=x)
|
177 |
+
# Fast-paths for built-in complex types
|
178 |
+
elif x.dtype in _complex_to_float:
|
179 |
+
xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
|
180 |
+
um.multiply(xv, xv, out=xv)
|
181 |
+
x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
|
182 |
+
# Most general case; includes handling object arrays containing imaginary
|
183 |
+
# numbers and complex types with non-native byteorder
|
184 |
+
else:
|
185 |
+
x = um.multiply(x, um.conjugate(x), out=x).real
|
186 |
+
|
187 |
+
ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
|
188 |
+
|
189 |
+
# Compute degrees of freedom and make sure it is not negative.
|
190 |
+
rcount = um.maximum(rcount - ddof, 0)
|
191 |
+
|
192 |
+
# divide by degrees of freedom
|
193 |
+
if isinstance(ret, mu.ndarray):
|
194 |
+
with _no_nep50_warning():
|
195 |
+
ret = um.true_divide(
|
196 |
+
ret, rcount, out=ret, casting='unsafe', subok=False)
|
197 |
+
elif hasattr(ret, 'dtype'):
|
198 |
+
ret = ret.dtype.type(ret / rcount)
|
199 |
+
else:
|
200 |
+
ret = ret / rcount
|
201 |
+
|
202 |
+
return ret
|
203 |
+
|
204 |
+
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
|
205 |
+
where=True):
|
206 |
+
ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
|
207 |
+
keepdims=keepdims, where=where)
|
208 |
+
|
209 |
+
if isinstance(ret, mu.ndarray):
|
210 |
+
ret = um.sqrt(ret, out=ret)
|
211 |
+
elif hasattr(ret, 'dtype'):
|
212 |
+
ret = ret.dtype.type(um.sqrt(ret))
|
213 |
+
else:
|
214 |
+
ret = um.sqrt(ret)
|
215 |
+
|
216 |
+
return ret
|
217 |
+
|
218 |
+
def _ptp(a, axis=None, out=None, keepdims=False):
|
219 |
+
return um.subtract(
|
220 |
+
umr_maximum(a, axis, None, out, keepdims),
|
221 |
+
umr_minimum(a, axis, None, None, keepdims),
|
222 |
+
out
|
223 |
+
)
|
224 |
+
|
225 |
+
def _dump(self, file, protocol=2):
|
226 |
+
if hasattr(file, 'write'):
|
227 |
+
ctx = nullcontext(file)
|
228 |
+
else:
|
229 |
+
ctx = open(os_fspath(file), "wb")
|
230 |
+
with ctx as f:
|
231 |
+
pickle.dump(self, f, protocol=protocol)
|
232 |
+
|
233 |
+
def _dumps(self, protocol=2):
|
234 |
+
return pickle.dumps(self, protocol=protocol)
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (176 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_type_aliases.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from numpy.compat import unicode
|
21 |
+
from numpy.core._string_helpers import english_lower
|
22 |
+
from numpy.core.multiarray import typeinfo, dtype
|
23 |
+
from numpy.core._dtype import _kind_name
|
24 |
+
|
25 |
+
|
26 |
+
sctypeDict = {} # Contains all leaf-node scalar types with aliases
|
27 |
+
allTypes = {} # Collect the types we will add to the module
|
28 |
+
|
29 |
+
|
30 |
+
# separate the actual type info from the abstract base classes
|
31 |
+
_abstract_types = {}
|
32 |
+
_concrete_typeinfo = {}
|
33 |
+
for k, v in typeinfo.items():
|
34 |
+
# make all the keys lowercase too
|
35 |
+
k = english_lower(k)
|
36 |
+
if isinstance(v, type):
|
37 |
+
_abstract_types[k] = v
|
38 |
+
else:
|
39 |
+
_concrete_typeinfo[k] = v
|
40 |
+
|
41 |
+
_concrete_types = {v.type for k, v in _concrete_typeinfo.items()}
|
42 |
+
|
43 |
+
|
44 |
+
def _bits_of(obj):
|
45 |
+
try:
|
46 |
+
info = next(v for v in _concrete_typeinfo.values() if v.type is obj)
|
47 |
+
except StopIteration:
|
48 |
+
if obj in _abstract_types.values():
|
49 |
+
msg = "Cannot count the bits of an abstract type"
|
50 |
+
raise ValueError(msg) from None
|
51 |
+
|
52 |
+
# some third-party type - make a best-guess
|
53 |
+
return dtype(obj).itemsize * 8
|
54 |
+
else:
|
55 |
+
return info.bits
|
56 |
+
|
57 |
+
|
58 |
+
def bitname(obj):
|
59 |
+
"""Return a bit-width name for a given type object"""
|
60 |
+
bits = _bits_of(obj)
|
61 |
+
dt = dtype(obj)
|
62 |
+
char = dt.kind
|
63 |
+
base = _kind_name(dt)
|
64 |
+
|
65 |
+
if base == 'object':
|
66 |
+
bits = 0
|
67 |
+
|
68 |
+
if bits != 0:
|
69 |
+
char = "%s%d" % (char, bits // 8)
|
70 |
+
|
71 |
+
return base, bits, char
|
72 |
+
|
73 |
+
|
74 |
+
def _add_types():
|
75 |
+
for name, info in _concrete_typeinfo.items():
|
76 |
+
# define C-name and insert typenum and typechar references also
|
77 |
+
allTypes[name] = info.type
|
78 |
+
sctypeDict[name] = info.type
|
79 |
+
sctypeDict[info.char] = info.type
|
80 |
+
sctypeDict[info.num] = info.type
|
81 |
+
|
82 |
+
for name, cls in _abstract_types.items():
|
83 |
+
allTypes[name] = cls
|
84 |
+
_add_types()
|
85 |
+
|
86 |
+
# This is the priority order used to assign the bit-sized NPY_INTxx names, which
|
87 |
+
# must match the order in npy_common.h in order for NPY_INTxx and np.intxx to be
|
88 |
+
# consistent.
|
89 |
+
# If two C types have the same size, then the earliest one in this list is used
|
90 |
+
# as the sized name.
|
91 |
+
_int_ctypes = ['long', 'longlong', 'int', 'short', 'byte']
|
92 |
+
_uint_ctypes = list('u' + t for t in _int_ctypes)
|
93 |
+
|
94 |
+
def _add_aliases():
|
95 |
+
for name, info in _concrete_typeinfo.items():
|
96 |
+
# these are handled by _add_integer_aliases
|
97 |
+
if name in _int_ctypes or name in _uint_ctypes:
|
98 |
+
continue
|
99 |
+
|
100 |
+
# insert bit-width version for this class (if relevant)
|
101 |
+
base, bit, char = bitname(info.type)
|
102 |
+
|
103 |
+
myname = "%s%d" % (base, bit)
|
104 |
+
|
105 |
+
# ensure that (c)longdouble does not overwrite the aliases assigned to
|
106 |
+
# (c)double
|
107 |
+
if name in ('longdouble', 'clongdouble') and myname in allTypes:
|
108 |
+
continue
|
109 |
+
|
110 |
+
# Add to the main namespace if desired:
|
111 |
+
if bit != 0 and base != "bool":
|
112 |
+
allTypes[myname] = info.type
|
113 |
+
|
114 |
+
# add forward, reverse, and string mapping to numarray
|
115 |
+
sctypeDict[char] = info.type
|
116 |
+
|
117 |
+
# add mapping for both the bit name
|
118 |
+
sctypeDict[myname] = info.type
|
119 |
+
|
120 |
+
|
121 |
+
_add_aliases()
|
122 |
+
|
123 |
+
def _add_integer_aliases():
|
124 |
+
seen_bits = set()
|
125 |
+
for i_ctype, u_ctype in zip(_int_ctypes, _uint_ctypes):
|
126 |
+
i_info = _concrete_typeinfo[i_ctype]
|
127 |
+
u_info = _concrete_typeinfo[u_ctype]
|
128 |
+
bits = i_info.bits # same for both
|
129 |
+
|
130 |
+
for info, charname, intname in [
|
131 |
+
(i_info,'i%d' % (bits//8,), 'int%d' % bits),
|
132 |
+
(u_info,'u%d' % (bits//8,), 'uint%d' % bits)]:
|
133 |
+
if bits not in seen_bits:
|
134 |
+
# sometimes two different types have the same number of bits
|
135 |
+
# if so, the one iterated over first takes precedence
|
136 |
+
allTypes[intname] = info.type
|
137 |
+
sctypeDict[intname] = info.type
|
138 |
+
sctypeDict[charname] = info.type
|
139 |
+
|
140 |
+
seen_bits.add(bits)
|
141 |
+
|
142 |
+
_add_integer_aliases()
|
143 |
+
|
144 |
+
# We use these later
|
145 |
+
void = allTypes['void']
|
146 |
+
|
147 |
+
#
|
148 |
+
# Rework the Python names (so that float and complex and int are consistent
|
149 |
+
# with Python usage)
|
150 |
+
#
|
151 |
+
def _set_up_aliases():
|
152 |
+
type_pairs = [('complex_', 'cdouble'),
|
153 |
+
('single', 'float'),
|
154 |
+
('csingle', 'cfloat'),
|
155 |
+
('singlecomplex', 'cfloat'),
|
156 |
+
('float_', 'double'),
|
157 |
+
('intc', 'int'),
|
158 |
+
('uintc', 'uint'),
|
159 |
+
('int_', 'long'),
|
160 |
+
('uint', 'ulong'),
|
161 |
+
('cfloat', 'cdouble'),
|
162 |
+
('longfloat', 'longdouble'),
|
163 |
+
('clongfloat', 'clongdouble'),
|
164 |
+
('longcomplex', 'clongdouble'),
|
165 |
+
('bool_', 'bool'),
|
166 |
+
('bytes_', 'string'),
|
167 |
+
('string_', 'string'),
|
168 |
+
('str_', 'unicode'),
|
169 |
+
('unicode_', 'unicode'),
|
170 |
+
('object_', 'object')]
|
171 |
+
for alias, t in type_pairs:
|
172 |
+
allTypes[alias] = allTypes[t]
|
173 |
+
sctypeDict[alias] = sctypeDict[t]
|
174 |
+
# Remove aliases overriding python types and modules
|
175 |
+
to_remove = ['object', 'int', 'float',
|
176 |
+
'complex', 'bool', 'string', 'datetime', 'timedelta',
|
177 |
+
'bytes', 'str']
|
178 |
+
|
179 |
+
for t in to_remove:
|
180 |
+
try:
|
181 |
+
del allTypes[t]
|
182 |
+
del sctypeDict[t]
|
183 |
+
except KeyError:
|
184 |
+
pass
|
185 |
+
|
186 |
+
# Additional aliases in sctypeDict that should not be exposed as attributes
|
187 |
+
attrs_to_remove = ['ulong']
|
188 |
+
|
189 |
+
for t in attrs_to_remove:
|
190 |
+
try:
|
191 |
+
del allTypes[t]
|
192 |
+
except KeyError:
|
193 |
+
pass
|
194 |
+
_set_up_aliases()
|
195 |
+
|
196 |
+
|
197 |
+
sctypes = {'int': [],
|
198 |
+
'uint':[],
|
199 |
+
'float':[],
|
200 |
+
'complex':[],
|
201 |
+
'others':[bool, object, bytes, unicode, void]}
|
202 |
+
|
203 |
+
def _add_array_type(typename, bits):
|
204 |
+
try:
|
205 |
+
t = allTypes['%s%d' % (typename, bits)]
|
206 |
+
except KeyError:
|
207 |
+
pass
|
208 |
+
else:
|
209 |
+
sctypes[typename].append(t)
|
210 |
+
|
211 |
+
def _set_array_types():
|
212 |
+
ibytes = [1, 2, 4, 8, 16, 32, 64]
|
213 |
+
fbytes = [2, 4, 8, 10, 12, 16, 32, 64]
|
214 |
+
for bytes in ibytes:
|
215 |
+
bits = 8*bytes
|
216 |
+
_add_array_type('int', bits)
|
217 |
+
_add_array_type('uint', bits)
|
218 |
+
for bytes in fbytes:
|
219 |
+
bits = 8*bytes
|
220 |
+
_add_array_type('float', bits)
|
221 |
+
_add_array_type('complex', 2*bits)
|
222 |
+
_gi = dtype('p')
|
223 |
+
if _gi.type not in sctypes['int']:
|
224 |
+
indx = 0
|
225 |
+
sz = _gi.itemsize
|
226 |
+
_lst = sctypes['int']
|
227 |
+
while (indx < len(_lst) and sz >= _lst[indx](0).itemsize):
|
228 |
+
indx += 1
|
229 |
+
sctypes['int'].insert(indx, _gi.type)
|
230 |
+
sctypes['uint'].insert(indx, dtype('P').type)
|
231 |
+
_set_array_types()
|
232 |
+
|
233 |
+
|
234 |
+
# Add additional strings to the sctypeDict
|
235 |
+
_toadd = ['int', 'float', 'complex', 'bool', 'object',
|
236 |
+
'str', 'bytes', ('a', 'bytes_'),
|
237 |
+
('int0', 'intp'), ('uint0', 'uintp')]
|
238 |
+
|
239 |
+
for name in _toadd:
|
240 |
+
if isinstance(name, tuple):
|
241 |
+
sctypeDict[name[0]] = allTypes[name[1]]
|
242 |
+
else:
|
243 |
+
sctypeDict[name] = allTypes['%s_' % name]
|
244 |
+
|
245 |
+
del _toadd, name
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_type_aliases.pyi
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, TypedDict
|
2 |
+
|
3 |
+
from numpy import generic, signedinteger, unsignedinteger, floating, complexfloating
|
4 |
+
|
5 |
+
class _SCTypes(TypedDict):
|
6 |
+
int: list[type[signedinteger[Any]]]
|
7 |
+
uint: list[type[unsignedinteger[Any]]]
|
8 |
+
float: list[type[floating[Any]]]
|
9 |
+
complex: list[type[complexfloating[Any, Any]]]
|
10 |
+
others: list[type]
|
11 |
+
|
12 |
+
sctypeDict: dict[int | str, type[generic]]
|
13 |
+
sctypes: _SCTypes
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_ufunc_config.py
ADDED
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Functions for changing global ufunc configuration
|
3 |
+
|
4 |
+
This provides helpers which wrap `umath.geterrobj` and `umath.seterrobj`
|
5 |
+
"""
|
6 |
+
import collections.abc
|
7 |
+
import contextlib
|
8 |
+
import contextvars
|
9 |
+
|
10 |
+
from .._utils import set_module
|
11 |
+
from .umath import (
|
12 |
+
UFUNC_BUFSIZE_DEFAULT,
|
13 |
+
ERR_IGNORE, ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, ERR_DEFAULT,
|
14 |
+
SHIFT_DIVIDEBYZERO, SHIFT_OVERFLOW, SHIFT_UNDERFLOW, SHIFT_INVALID,
|
15 |
+
)
|
16 |
+
from . import umath
|
17 |
+
|
18 |
+
__all__ = [
|
19 |
+
"seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
|
20 |
+
"errstate", '_no_nep50_warning'
|
21 |
+
]
|
22 |
+
|
23 |
+
_errdict = {"ignore": ERR_IGNORE,
|
24 |
+
"warn": ERR_WARN,
|
25 |
+
"raise": ERR_RAISE,
|
26 |
+
"call": ERR_CALL,
|
27 |
+
"print": ERR_PRINT,
|
28 |
+
"log": ERR_LOG}
|
29 |
+
|
30 |
+
_errdict_rev = {value: key for key, value in _errdict.items()}
|
31 |
+
|
32 |
+
|
33 |
+
@set_module('numpy')
|
34 |
+
def seterr(all=None, divide=None, over=None, under=None, invalid=None):
|
35 |
+
"""
|
36 |
+
Set how floating-point errors are handled.
|
37 |
+
|
38 |
+
Note that operations on integer scalar types (such as `int16`) are
|
39 |
+
handled like floating point, and are affected by these settings.
|
40 |
+
|
41 |
+
Parameters
|
42 |
+
----------
|
43 |
+
all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
44 |
+
Set treatment for all types of floating-point errors at once:
|
45 |
+
|
46 |
+
- ignore: Take no action when the exception occurs.
|
47 |
+
- warn: Print a `RuntimeWarning` (via the Python `warnings` module).
|
48 |
+
- raise: Raise a `FloatingPointError`.
|
49 |
+
- call: Call a function specified using the `seterrcall` function.
|
50 |
+
- print: Print a warning directly to ``stdout``.
|
51 |
+
- log: Record error in a Log object specified by `seterrcall`.
|
52 |
+
|
53 |
+
The default is not to change the current behavior.
|
54 |
+
divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
55 |
+
Treatment for division by zero.
|
56 |
+
over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
57 |
+
Treatment for floating-point overflow.
|
58 |
+
under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
59 |
+
Treatment for floating-point underflow.
|
60 |
+
invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
|
61 |
+
Treatment for invalid floating-point operation.
|
62 |
+
|
63 |
+
Returns
|
64 |
+
-------
|
65 |
+
old_settings : dict
|
66 |
+
Dictionary containing the old settings.
|
67 |
+
|
68 |
+
See also
|
69 |
+
--------
|
70 |
+
seterrcall : Set a callback function for the 'call' mode.
|
71 |
+
geterr, geterrcall, errstate
|
72 |
+
|
73 |
+
Notes
|
74 |
+
-----
|
75 |
+
The floating-point exceptions are defined in the IEEE 754 standard [1]_:
|
76 |
+
|
77 |
+
- Division by zero: infinite result obtained from finite numbers.
|
78 |
+
- Overflow: result too large to be expressed.
|
79 |
+
- Underflow: result so close to zero that some precision
|
80 |
+
was lost.
|
81 |
+
- Invalid operation: result is not an expressible number, typically
|
82 |
+
indicates that a NaN was produced.
|
83 |
+
|
84 |
+
.. [1] https://en.wikipedia.org/wiki/IEEE_754
|
85 |
+
|
86 |
+
Examples
|
87 |
+
--------
|
88 |
+
>>> old_settings = np.seterr(all='ignore') #seterr to known value
|
89 |
+
>>> np.seterr(over='raise')
|
90 |
+
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
|
91 |
+
>>> np.seterr(**old_settings) # reset to default
|
92 |
+
{'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'}
|
93 |
+
|
94 |
+
>>> np.int16(32000) * np.int16(3)
|
95 |
+
30464
|
96 |
+
>>> old_settings = np.seterr(all='warn', over='raise')
|
97 |
+
>>> np.int16(32000) * np.int16(3)
|
98 |
+
Traceback (most recent call last):
|
99 |
+
File "<stdin>", line 1, in <module>
|
100 |
+
FloatingPointError: overflow encountered in scalar multiply
|
101 |
+
|
102 |
+
>>> old_settings = np.seterr(all='print')
|
103 |
+
>>> np.geterr()
|
104 |
+
{'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
|
105 |
+
>>> np.int16(32000) * np.int16(3)
|
106 |
+
30464
|
107 |
+
|
108 |
+
"""
|
109 |
+
|
110 |
+
pyvals = umath.geterrobj()
|
111 |
+
old = geterr()
|
112 |
+
|
113 |
+
if divide is None:
|
114 |
+
divide = all or old['divide']
|
115 |
+
if over is None:
|
116 |
+
over = all or old['over']
|
117 |
+
if under is None:
|
118 |
+
under = all or old['under']
|
119 |
+
if invalid is None:
|
120 |
+
invalid = all or old['invalid']
|
121 |
+
|
122 |
+
maskvalue = ((_errdict[divide] << SHIFT_DIVIDEBYZERO) +
|
123 |
+
(_errdict[over] << SHIFT_OVERFLOW) +
|
124 |
+
(_errdict[under] << SHIFT_UNDERFLOW) +
|
125 |
+
(_errdict[invalid] << SHIFT_INVALID))
|
126 |
+
|
127 |
+
pyvals[1] = maskvalue
|
128 |
+
umath.seterrobj(pyvals)
|
129 |
+
return old
|
130 |
+
|
131 |
+
|
132 |
+
@set_module('numpy')
|
133 |
+
def geterr():
|
134 |
+
"""
|
135 |
+
Get the current way of handling floating-point errors.
|
136 |
+
|
137 |
+
Returns
|
138 |
+
-------
|
139 |
+
res : dict
|
140 |
+
A dictionary with keys "divide", "over", "under", and "invalid",
|
141 |
+
whose values are from the strings "ignore", "print", "log", "warn",
|
142 |
+
"raise", and "call". The keys represent possible floating-point
|
143 |
+
exceptions, and the values define how these exceptions are handled.
|
144 |
+
|
145 |
+
See Also
|
146 |
+
--------
|
147 |
+
geterrcall, seterr, seterrcall
|
148 |
+
|
149 |
+
Notes
|
150 |
+
-----
|
151 |
+
For complete documentation of the types of floating-point exceptions and
|
152 |
+
treatment options, see `seterr`.
|
153 |
+
|
154 |
+
Examples
|
155 |
+
--------
|
156 |
+
>>> np.geterr()
|
157 |
+
{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
|
158 |
+
>>> np.arange(3.) / np.arange(3.)
|
159 |
+
array([nan, 1., 1.])
|
160 |
+
|
161 |
+
>>> oldsettings = np.seterr(all='warn', over='raise')
|
162 |
+
>>> np.geterr()
|
163 |
+
{'divide': 'warn', 'over': 'raise', 'under': 'warn', 'invalid': 'warn'}
|
164 |
+
>>> np.arange(3.) / np.arange(3.)
|
165 |
+
array([nan, 1., 1.])
|
166 |
+
|
167 |
+
"""
|
168 |
+
maskvalue = umath.geterrobj()[1]
|
169 |
+
mask = 7
|
170 |
+
res = {}
|
171 |
+
val = (maskvalue >> SHIFT_DIVIDEBYZERO) & mask
|
172 |
+
res['divide'] = _errdict_rev[val]
|
173 |
+
val = (maskvalue >> SHIFT_OVERFLOW) & mask
|
174 |
+
res['over'] = _errdict_rev[val]
|
175 |
+
val = (maskvalue >> SHIFT_UNDERFLOW) & mask
|
176 |
+
res['under'] = _errdict_rev[val]
|
177 |
+
val = (maskvalue >> SHIFT_INVALID) & mask
|
178 |
+
res['invalid'] = _errdict_rev[val]
|
179 |
+
return res
|
180 |
+
|
181 |
+
|
182 |
+
@set_module('numpy')
|
183 |
+
def setbufsize(size):
|
184 |
+
"""
|
185 |
+
Set the size of the buffer used in ufuncs.
|
186 |
+
|
187 |
+
Parameters
|
188 |
+
----------
|
189 |
+
size : int
|
190 |
+
Size of buffer.
|
191 |
+
|
192 |
+
"""
|
193 |
+
if size > 10e6:
|
194 |
+
raise ValueError("Buffer size, %s, is too big." % size)
|
195 |
+
if size < 5:
|
196 |
+
raise ValueError("Buffer size, %s, is too small." % size)
|
197 |
+
if size % 16 != 0:
|
198 |
+
raise ValueError("Buffer size, %s, is not a multiple of 16." % size)
|
199 |
+
|
200 |
+
pyvals = umath.geterrobj()
|
201 |
+
old = getbufsize()
|
202 |
+
pyvals[0] = size
|
203 |
+
umath.seterrobj(pyvals)
|
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 |
+
"""
|
218 |
+
return umath.geterrobj()[0]
|
219 |
+
|
220 |
+
|
221 |
+
@set_module('numpy')
|
222 |
+
def seterrcall(func):
|
223 |
+
"""
|
224 |
+
Set the floating-point error callback function or log object.
|
225 |
+
|
226 |
+
There are two ways to capture floating-point error messages. The first
|
227 |
+
is to set the error-handler to 'call', using `seterr`. Then, set
|
228 |
+
the function to call using this function.
|
229 |
+
|
230 |
+
The second is to set the error-handler to 'log', using `seterr`.
|
231 |
+
Floating-point errors then trigger a call to the 'write' method of
|
232 |
+
the provided object.
|
233 |
+
|
234 |
+
Parameters
|
235 |
+
----------
|
236 |
+
func : callable f(err, flag) or object with write method
|
237 |
+
Function to call upon floating-point errors ('call'-mode) or
|
238 |
+
object whose 'write' method is used to log such message ('log'-mode).
|
239 |
+
|
240 |
+
The call function takes two arguments. The first is a string describing
|
241 |
+
the type of error (such as "divide by zero", "overflow", "underflow",
|
242 |
+
or "invalid value"), and the second is the status flag. The flag is a
|
243 |
+
byte, whose four least-significant bits indicate the type of error, one
|
244 |
+
of "divide", "over", "under", "invalid"::
|
245 |
+
|
246 |
+
[0 0 0 0 divide over under invalid]
|
247 |
+
|
248 |
+
In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
|
249 |
+
|
250 |
+
If an object is provided, its write method should take one argument,
|
251 |
+
a string.
|
252 |
+
|
253 |
+
Returns
|
254 |
+
-------
|
255 |
+
h : callable, log instance or None
|
256 |
+
The old error handler.
|
257 |
+
|
258 |
+
See Also
|
259 |
+
--------
|
260 |
+
seterr, geterr, geterrcall
|
261 |
+
|
262 |
+
Examples
|
263 |
+
--------
|
264 |
+
Callback upon error:
|
265 |
+
|
266 |
+
>>> def err_handler(type, flag):
|
267 |
+
... print("Floating point error (%s), with flag %s" % (type, flag))
|
268 |
+
...
|
269 |
+
|
270 |
+
>>> saved_handler = np.seterrcall(err_handler)
|
271 |
+
>>> save_err = np.seterr(all='call')
|
272 |
+
|
273 |
+
>>> np.array([1, 2, 3]) / 0.0
|
274 |
+
Floating point error (divide by zero), with flag 1
|
275 |
+
array([inf, inf, inf])
|
276 |
+
|
277 |
+
>>> np.seterrcall(saved_handler)
|
278 |
+
<function err_handler at 0x...>
|
279 |
+
>>> np.seterr(**save_err)
|
280 |
+
{'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
|
281 |
+
|
282 |
+
Log error message:
|
283 |
+
|
284 |
+
>>> class Log:
|
285 |
+
... def write(self, msg):
|
286 |
+
... print("LOG: %s" % msg)
|
287 |
+
...
|
288 |
+
|
289 |
+
>>> log = Log()
|
290 |
+
>>> saved_handler = np.seterrcall(log)
|
291 |
+
>>> save_err = np.seterr(all='log')
|
292 |
+
|
293 |
+
>>> np.array([1, 2, 3]) / 0.0
|
294 |
+
LOG: Warning: divide by zero encountered in divide
|
295 |
+
array([inf, inf, inf])
|
296 |
+
|
297 |
+
>>> np.seterrcall(saved_handler)
|
298 |
+
<numpy.core.numeric.Log object at 0x...>
|
299 |
+
>>> np.seterr(**save_err)
|
300 |
+
{'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
|
301 |
+
|
302 |
+
"""
|
303 |
+
if func is not None and not isinstance(func, collections.abc.Callable):
|
304 |
+
if (not hasattr(func, 'write') or
|
305 |
+
not isinstance(func.write, collections.abc.Callable)):
|
306 |
+
raise ValueError("Only callable can be used as callback")
|
307 |
+
pyvals = umath.geterrobj()
|
308 |
+
old = geterrcall()
|
309 |
+
pyvals[2] = func
|
310 |
+
umath.seterrobj(pyvals)
|
311 |
+
return old
|
312 |
+
|
313 |
+
|
314 |
+
@set_module('numpy')
|
315 |
+
def geterrcall():
|
316 |
+
"""
|
317 |
+
Return the current callback function used on floating-point errors.
|
318 |
+
|
319 |
+
When the error handling for a floating-point error (one of "divide",
|
320 |
+
"over", "under", or "invalid") is set to 'call' or 'log', the function
|
321 |
+
that is called or the log instance that is written to is returned by
|
322 |
+
`geterrcall`. This function or log instance has been set with
|
323 |
+
`seterrcall`.
|
324 |
+
|
325 |
+
Returns
|
326 |
+
-------
|
327 |
+
errobj : callable, log instance or None
|
328 |
+
The current error handler. If no handler was set through `seterrcall`,
|
329 |
+
``None`` is returned.
|
330 |
+
|
331 |
+
See Also
|
332 |
+
--------
|
333 |
+
seterrcall, seterr, geterr
|
334 |
+
|
335 |
+
Notes
|
336 |
+
-----
|
337 |
+
For complete documentation of the types of floating-point exceptions and
|
338 |
+
treatment options, see `seterr`.
|
339 |
+
|
340 |
+
Examples
|
341 |
+
--------
|
342 |
+
>>> np.geterrcall() # we did not yet set a handler, returns None
|
343 |
+
|
344 |
+
>>> oldsettings = np.seterr(all='call')
|
345 |
+
>>> def err_handler(type, flag):
|
346 |
+
... print("Floating point error (%s), with flag %s" % (type, flag))
|
347 |
+
>>> oldhandler = np.seterrcall(err_handler)
|
348 |
+
>>> np.array([1, 2, 3]) / 0.0
|
349 |
+
Floating point error (divide by zero), with flag 1
|
350 |
+
array([inf, inf, inf])
|
351 |
+
|
352 |
+
>>> cur_handler = np.geterrcall()
|
353 |
+
>>> cur_handler is err_handler
|
354 |
+
True
|
355 |
+
|
356 |
+
"""
|
357 |
+
return umath.geterrobj()[2]
|
358 |
+
|
359 |
+
|
360 |
+
class _unspecified:
|
361 |
+
pass
|
362 |
+
|
363 |
+
|
364 |
+
_Unspecified = _unspecified()
|
365 |
+
|
366 |
+
|
367 |
+
@set_module('numpy')
|
368 |
+
class errstate(contextlib.ContextDecorator):
|
369 |
+
"""
|
370 |
+
errstate(**kwargs)
|
371 |
+
|
372 |
+
Context manager for floating-point error handling.
|
373 |
+
|
374 |
+
Using an instance of `errstate` as a context manager allows statements in
|
375 |
+
that context to execute with a known error handling behavior. Upon entering
|
376 |
+
the context the error handling is set with `seterr` and `seterrcall`, and
|
377 |
+
upon exiting it is reset to what it was before.
|
378 |
+
|
379 |
+
.. versionchanged:: 1.17.0
|
380 |
+
`errstate` is also usable as a function decorator, saving
|
381 |
+
a level of indentation if an entire function is wrapped.
|
382 |
+
See :py:class:`contextlib.ContextDecorator` for more information.
|
383 |
+
|
384 |
+
Parameters
|
385 |
+
----------
|
386 |
+
kwargs : {divide, over, under, invalid}
|
387 |
+
Keyword arguments. The valid keywords are the possible floating-point
|
388 |
+
exceptions. Each keyword should have a string value that defines the
|
389 |
+
treatment for the particular error. Possible values are
|
390 |
+
{'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
|
391 |
+
|
392 |
+
See Also
|
393 |
+
--------
|
394 |
+
seterr, geterr, seterrcall, geterrcall
|
395 |
+
|
396 |
+
Notes
|
397 |
+
-----
|
398 |
+
For complete documentation of the types of floating-point exceptions and
|
399 |
+
treatment options, see `seterr`.
|
400 |
+
|
401 |
+
Examples
|
402 |
+
--------
|
403 |
+
>>> olderr = np.seterr(all='ignore') # Set error handling to known state.
|
404 |
+
|
405 |
+
>>> np.arange(3) / 0.
|
406 |
+
array([nan, inf, inf])
|
407 |
+
>>> with np.errstate(divide='warn'):
|
408 |
+
... np.arange(3) / 0.
|
409 |
+
array([nan, inf, inf])
|
410 |
+
|
411 |
+
>>> np.sqrt(-1)
|
412 |
+
nan
|
413 |
+
>>> with np.errstate(invalid='raise'):
|
414 |
+
... np.sqrt(-1)
|
415 |
+
Traceback (most recent call last):
|
416 |
+
File "<stdin>", line 2, in <module>
|
417 |
+
FloatingPointError: invalid value encountered in sqrt
|
418 |
+
|
419 |
+
Outside the context the error handling behavior has not changed:
|
420 |
+
|
421 |
+
>>> np.geterr()
|
422 |
+
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
|
423 |
+
|
424 |
+
"""
|
425 |
+
|
426 |
+
def __init__(self, *, call=_Unspecified, **kwargs):
|
427 |
+
self.call = call
|
428 |
+
self.kwargs = kwargs
|
429 |
+
|
430 |
+
def __enter__(self):
|
431 |
+
self.oldstate = seterr(**self.kwargs)
|
432 |
+
if self.call is not _Unspecified:
|
433 |
+
self.oldcall = seterrcall(self.call)
|
434 |
+
|
435 |
+
def __exit__(self, *exc_info):
|
436 |
+
seterr(**self.oldstate)
|
437 |
+
if self.call is not _Unspecified:
|
438 |
+
seterrcall(self.oldcall)
|
439 |
+
|
440 |
+
|
441 |
+
def _setdef():
|
442 |
+
defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT, None]
|
443 |
+
umath.seterrobj(defval)
|
444 |
+
|
445 |
+
|
446 |
+
# set the default values
|
447 |
+
_setdef()
|
448 |
+
|
449 |
+
|
450 |
+
NO_NEP50_WARNING = contextvars.ContextVar("_no_nep50_warning", default=False)
|
451 |
+
|
452 |
+
@set_module('numpy')
|
453 |
+
@contextlib.contextmanager
|
454 |
+
def _no_nep50_warning():
|
455 |
+
"""
|
456 |
+
Context manager to disable NEP 50 warnings. This context manager is
|
457 |
+
only relevant if the NEP 50 warnings are enabled globally (which is not
|
458 |
+
thread/context safe).
|
459 |
+
|
460 |
+
This warning context manager itself is fully safe, however.
|
461 |
+
"""
|
462 |
+
token = NO_NEP50_WARNING.set(True)
|
463 |
+
try:
|
464 |
+
yield
|
465 |
+
finally:
|
466 |
+
NO_NEP50_WARNING.reset(token)
|
env-llmeval/lib/python3.10/site-packages/numpy/core/_umath_tests.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (42.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/arrayprint.pyi
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from types import TracebackType
|
2 |
+
from collections.abc import Callable
|
3 |
+
from typing import Any, Literal, TypedDict, SupportsIndex
|
4 |
+
|
5 |
+
# Using a private class is by no means ideal, but it is simply a consequence
|
6 |
+
# of a `contextlib.context` returning an instance of aforementioned class
|
7 |
+
from contextlib import _GeneratorContextManager
|
8 |
+
|
9 |
+
from numpy import (
|
10 |
+
ndarray,
|
11 |
+
generic,
|
12 |
+
bool_,
|
13 |
+
integer,
|
14 |
+
timedelta64,
|
15 |
+
datetime64,
|
16 |
+
floating,
|
17 |
+
complexfloating,
|
18 |
+
void,
|
19 |
+
str_,
|
20 |
+
bytes_,
|
21 |
+
longdouble,
|
22 |
+
clongdouble,
|
23 |
+
)
|
24 |
+
from numpy._typing import ArrayLike, _CharLike_co, _FloatLike_co
|
25 |
+
|
26 |
+
_FloatMode = Literal["fixed", "unique", "maxprec", "maxprec_equal"]
|
27 |
+
|
28 |
+
class _FormatDict(TypedDict, total=False):
|
29 |
+
bool: Callable[[bool_], str]
|
30 |
+
int: Callable[[integer[Any]], str]
|
31 |
+
timedelta: Callable[[timedelta64], str]
|
32 |
+
datetime: Callable[[datetime64], str]
|
33 |
+
float: Callable[[floating[Any]], str]
|
34 |
+
longfloat: Callable[[longdouble], str]
|
35 |
+
complexfloat: Callable[[complexfloating[Any, Any]], str]
|
36 |
+
longcomplexfloat: Callable[[clongdouble], str]
|
37 |
+
void: Callable[[void], str]
|
38 |
+
numpystr: Callable[[_CharLike_co], str]
|
39 |
+
object: Callable[[object], str]
|
40 |
+
all: Callable[[object], str]
|
41 |
+
int_kind: Callable[[integer[Any]], str]
|
42 |
+
float_kind: Callable[[floating[Any]], str]
|
43 |
+
complex_kind: Callable[[complexfloating[Any, Any]], str]
|
44 |
+
str_kind: Callable[[_CharLike_co], str]
|
45 |
+
|
46 |
+
class _FormatOptions(TypedDict):
|
47 |
+
precision: int
|
48 |
+
threshold: int
|
49 |
+
edgeitems: int
|
50 |
+
linewidth: int
|
51 |
+
suppress: bool
|
52 |
+
nanstr: str
|
53 |
+
infstr: str
|
54 |
+
formatter: None | _FormatDict
|
55 |
+
sign: Literal["-", "+", " "]
|
56 |
+
floatmode: _FloatMode
|
57 |
+
legacy: Literal[False, "1.13", "1.21"]
|
58 |
+
|
59 |
+
def set_printoptions(
|
60 |
+
precision: None | SupportsIndex = ...,
|
61 |
+
threshold: None | int = ...,
|
62 |
+
edgeitems: None | int = ...,
|
63 |
+
linewidth: None | int = ...,
|
64 |
+
suppress: None | bool = ...,
|
65 |
+
nanstr: None | str = ...,
|
66 |
+
infstr: None | str = ...,
|
67 |
+
formatter: None | _FormatDict = ...,
|
68 |
+
sign: Literal[None, "-", "+", " "] = ...,
|
69 |
+
floatmode: None | _FloatMode = ...,
|
70 |
+
*,
|
71 |
+
legacy: Literal[None, False, "1.13", "1.21"] = ...
|
72 |
+
) -> None: ...
|
73 |
+
def get_printoptions() -> _FormatOptions: ...
|
74 |
+
def array2string(
|
75 |
+
a: ndarray[Any, Any],
|
76 |
+
max_line_width: None | int = ...,
|
77 |
+
precision: None | SupportsIndex = ...,
|
78 |
+
suppress_small: None | bool = ...,
|
79 |
+
separator: str = ...,
|
80 |
+
prefix: str = ...,
|
81 |
+
# NOTE: With the `style` argument being deprecated,
|
82 |
+
# all arguments between `formatter` and `suffix` are de facto
|
83 |
+
# keyworld-only arguments
|
84 |
+
*,
|
85 |
+
formatter: None | _FormatDict = ...,
|
86 |
+
threshold: None | int = ...,
|
87 |
+
edgeitems: None | int = ...,
|
88 |
+
sign: Literal[None, "-", "+", " "] = ...,
|
89 |
+
floatmode: None | _FloatMode = ...,
|
90 |
+
suffix: str = ...,
|
91 |
+
legacy: Literal[None, False, "1.13", "1.21"] = ...,
|
92 |
+
) -> str: ...
|
93 |
+
def format_float_scientific(
|
94 |
+
x: _FloatLike_co,
|
95 |
+
precision: None | int = ...,
|
96 |
+
unique: bool = ...,
|
97 |
+
trim: Literal["k", ".", "0", "-"] = ...,
|
98 |
+
sign: bool = ...,
|
99 |
+
pad_left: None | int = ...,
|
100 |
+
exp_digits: None | int = ...,
|
101 |
+
min_digits: None | int = ...,
|
102 |
+
) -> str: ...
|
103 |
+
def format_float_positional(
|
104 |
+
x: _FloatLike_co,
|
105 |
+
precision: None | int = ...,
|
106 |
+
unique: bool = ...,
|
107 |
+
fractional: bool = ...,
|
108 |
+
trim: Literal["k", ".", "0", "-"] = ...,
|
109 |
+
sign: bool = ...,
|
110 |
+
pad_left: None | int = ...,
|
111 |
+
pad_right: None | int = ...,
|
112 |
+
min_digits: None | int = ...,
|
113 |
+
) -> str: ...
|
114 |
+
def array_repr(
|
115 |
+
arr: ndarray[Any, Any],
|
116 |
+
max_line_width: None | int = ...,
|
117 |
+
precision: None | SupportsIndex = ...,
|
118 |
+
suppress_small: None | bool = ...,
|
119 |
+
) -> str: ...
|
120 |
+
def array_str(
|
121 |
+
a: ndarray[Any, Any],
|
122 |
+
max_line_width: None | int = ...,
|
123 |
+
precision: None | SupportsIndex = ...,
|
124 |
+
suppress_small: None | bool = ...,
|
125 |
+
) -> str: ...
|
126 |
+
def set_string_function(
|
127 |
+
f: None | Callable[[ndarray[Any, Any]], str], repr: bool = ...
|
128 |
+
) -> None: ...
|
129 |
+
def printoptions(
|
130 |
+
precision: None | SupportsIndex = ...,
|
131 |
+
threshold: None | int = ...,
|
132 |
+
edgeitems: None | int = ...,
|
133 |
+
linewidth: None | int = ...,
|
134 |
+
suppress: None | bool = ...,
|
135 |
+
nanstr: None | str = ...,
|
136 |
+
infstr: None | str = ...,
|
137 |
+
formatter: None | _FormatDict = ...,
|
138 |
+
sign: Literal[None, "-", "+", " "] = ...,
|
139 |
+
floatmode: None | _FloatMode = ...,
|
140 |
+
*,
|
141 |
+
legacy: Literal[None, False, "1.13", "1.21"] = ...
|
142 |
+
) -> _GeneratorContextManager[_FormatOptions]: ...
|
env-llmeval/lib/python3.10/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))
|
env-llmeval/lib/python3.10/site-packages/numpy/core/defchararray.py
ADDED
@@ -0,0 +1,2914 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from .._utils import set_module
|
21 |
+
from .numerictypes import (
|
22 |
+
bytes_, str_, integer, int_, object_, bool_, character)
|
23 |
+
from .numeric import ndarray, compare_chararrays
|
24 |
+
from .numeric import array as narray
|
25 |
+
from numpy.core.multiarray import _vec_string
|
26 |
+
from numpy.core import overrides
|
27 |
+
from numpy.compat import asbytes
|
28 |
+
import numpy
|
29 |
+
|
30 |
+
__all__ = [
|
31 |
+
'equal', 'not_equal', 'greater_equal', 'less_equal',
|
32 |
+
'greater', 'less', 'str_len', 'add', 'multiply', 'mod', 'capitalize',
|
33 |
+
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
|
34 |
+
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
|
35 |
+
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
|
36 |
+
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
|
37 |
+
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
|
38 |
+
'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal',
|
39 |
+
'array', 'asarray'
|
40 |
+
]
|
41 |
+
|
42 |
+
|
43 |
+
_globalvar = 0
|
44 |
+
|
45 |
+
array_function_dispatch = functools.partial(
|
46 |
+
overrides.array_function_dispatch, module='numpy.char')
|
47 |
+
|
48 |
+
|
49 |
+
def _is_unicode(arr):
|
50 |
+
"""Returns True if arr is a string or a string array with a dtype that
|
51 |
+
represents a unicode string, otherwise returns False.
|
52 |
+
|
53 |
+
"""
|
54 |
+
if (isinstance(arr, str) or
|
55 |
+
issubclass(numpy.asarray(arr).dtype.type, str)):
|
56 |
+
return True
|
57 |
+
return False
|
58 |
+
|
59 |
+
|
60 |
+
def _to_bytes_or_str_array(result, output_dtype_like=None):
|
61 |
+
"""
|
62 |
+
Helper function to cast a result back into an array
|
63 |
+
with the appropriate dtype if an object array must be used
|
64 |
+
as an intermediary.
|
65 |
+
"""
|
66 |
+
ret = numpy.asarray(result.tolist())
|
67 |
+
dtype = getattr(output_dtype_like, 'dtype', None)
|
68 |
+
if dtype is not None:
|
69 |
+
return ret.astype(type(dtype)(_get_num_chars(ret)), copy=False)
|
70 |
+
return ret
|
71 |
+
|
72 |
+
|
73 |
+
def _clean_args(*args):
|
74 |
+
"""
|
75 |
+
Helper function for delegating arguments to Python string
|
76 |
+
functions.
|
77 |
+
|
78 |
+
Many of the Python string operations that have optional arguments
|
79 |
+
do not use 'None' to indicate a default value. In these cases,
|
80 |
+
we need to remove all None arguments, and those following them.
|
81 |
+
"""
|
82 |
+
newargs = []
|
83 |
+
for chk in args:
|
84 |
+
if chk is None:
|
85 |
+
break
|
86 |
+
newargs.append(chk)
|
87 |
+
return newargs
|
88 |
+
|
89 |
+
def _get_num_chars(a):
|
90 |
+
"""
|
91 |
+
Helper function that returns the number of characters per field in
|
92 |
+
a string or unicode array. This is to abstract out the fact that
|
93 |
+
for a unicode array this is itemsize / 4.
|
94 |
+
"""
|
95 |
+
if issubclass(a.dtype.type, str_):
|
96 |
+
return a.itemsize // 4
|
97 |
+
return a.itemsize
|
98 |
+
|
99 |
+
|
100 |
+
def _binary_op_dispatcher(x1, x2):
|
101 |
+
return (x1, x2)
|
102 |
+
|
103 |
+
|
104 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
105 |
+
def equal(x1, x2):
|
106 |
+
"""
|
107 |
+
Return (x1 == x2) element-wise.
|
108 |
+
|
109 |
+
Unlike `numpy.equal`, this comparison is performed by first
|
110 |
+
stripping whitespace characters from the end of the string. This
|
111 |
+
behavior is provided for backward-compatibility with numarray.
|
112 |
+
|
113 |
+
Parameters
|
114 |
+
----------
|
115 |
+
x1, x2 : array_like of str or unicode
|
116 |
+
Input arrays of the same shape.
|
117 |
+
|
118 |
+
Returns
|
119 |
+
-------
|
120 |
+
out : ndarray
|
121 |
+
Output array of bools.
|
122 |
+
|
123 |
+
See Also
|
124 |
+
--------
|
125 |
+
not_equal, greater_equal, less_equal, greater, less
|
126 |
+
"""
|
127 |
+
return compare_chararrays(x1, x2, '==', True)
|
128 |
+
|
129 |
+
|
130 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
131 |
+
def not_equal(x1, x2):
|
132 |
+
"""
|
133 |
+
Return (x1 != x2) element-wise.
|
134 |
+
|
135 |
+
Unlike `numpy.not_equal`, this comparison is performed by first
|
136 |
+
stripping whitespace characters from the end of the string. This
|
137 |
+
behavior is provided for backward-compatibility with 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, greater_equal, less_equal, greater, less
|
152 |
+
"""
|
153 |
+
return compare_chararrays(x1, x2, '!=', True)
|
154 |
+
|
155 |
+
|
156 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
157 |
+
def greater_equal(x1, x2):
|
158 |
+
"""
|
159 |
+
Return (x1 >= x2) element-wise.
|
160 |
+
|
161 |
+
Unlike `numpy.greater_equal`, this comparison is performed by
|
162 |
+
first stripping whitespace characters from the end of the string.
|
163 |
+
This behavior is provided for backward-compatibility with
|
164 |
+
numarray.
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
----------
|
168 |
+
x1, x2 : array_like of str or unicode
|
169 |
+
Input arrays of the same shape.
|
170 |
+
|
171 |
+
Returns
|
172 |
+
-------
|
173 |
+
out : ndarray
|
174 |
+
Output array of bools.
|
175 |
+
|
176 |
+
See Also
|
177 |
+
--------
|
178 |
+
equal, not_equal, less_equal, greater, less
|
179 |
+
"""
|
180 |
+
return compare_chararrays(x1, x2, '>=', True)
|
181 |
+
|
182 |
+
|
183 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
184 |
+
def less_equal(x1, x2):
|
185 |
+
"""
|
186 |
+
Return (x1 <= x2) element-wise.
|
187 |
+
|
188 |
+
Unlike `numpy.less_equal`, this comparison is performed by first
|
189 |
+
stripping whitespace characters from the end of the string. This
|
190 |
+
behavior is provided for backward-compatibility with numarray.
|
191 |
+
|
192 |
+
Parameters
|
193 |
+
----------
|
194 |
+
x1, x2 : array_like of str or unicode
|
195 |
+
Input arrays of the same shape.
|
196 |
+
|
197 |
+
Returns
|
198 |
+
-------
|
199 |
+
out : ndarray
|
200 |
+
Output array of bools.
|
201 |
+
|
202 |
+
See Also
|
203 |
+
--------
|
204 |
+
equal, not_equal, greater_equal, greater, less
|
205 |
+
"""
|
206 |
+
return compare_chararrays(x1, x2, '<=', True)
|
207 |
+
|
208 |
+
|
209 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
210 |
+
def greater(x1, x2):
|
211 |
+
"""
|
212 |
+
Return (x1 > x2) element-wise.
|
213 |
+
|
214 |
+
Unlike `numpy.greater`, this comparison is performed by first
|
215 |
+
stripping whitespace characters from the end of the string. This
|
216 |
+
behavior is provided for backward-compatibility with numarray.
|
217 |
+
|
218 |
+
Parameters
|
219 |
+
----------
|
220 |
+
x1, x2 : array_like of str or unicode
|
221 |
+
Input arrays of the same shape.
|
222 |
+
|
223 |
+
Returns
|
224 |
+
-------
|
225 |
+
out : ndarray
|
226 |
+
Output array of bools.
|
227 |
+
|
228 |
+
See Also
|
229 |
+
--------
|
230 |
+
equal, not_equal, greater_equal, less_equal, less
|
231 |
+
"""
|
232 |
+
return compare_chararrays(x1, x2, '>', True)
|
233 |
+
|
234 |
+
|
235 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
236 |
+
def less(x1, x2):
|
237 |
+
"""
|
238 |
+
Return (x1 < x2) element-wise.
|
239 |
+
|
240 |
+
Unlike `numpy.greater`, this comparison is performed by first
|
241 |
+
stripping whitespace characters from the end of the string. This
|
242 |
+
behavior is provided for backward-compatibility with numarray.
|
243 |
+
|
244 |
+
Parameters
|
245 |
+
----------
|
246 |
+
x1, x2 : array_like of str or unicode
|
247 |
+
Input arrays of the same shape.
|
248 |
+
|
249 |
+
Returns
|
250 |
+
-------
|
251 |
+
out : ndarray
|
252 |
+
Output array of bools.
|
253 |
+
|
254 |
+
See Also
|
255 |
+
--------
|
256 |
+
equal, not_equal, greater_equal, less_equal, greater
|
257 |
+
"""
|
258 |
+
return compare_chararrays(x1, x2, '<', True)
|
259 |
+
|
260 |
+
|
261 |
+
def _unary_op_dispatcher(a):
|
262 |
+
return (a,)
|
263 |
+
|
264 |
+
|
265 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
266 |
+
def str_len(a):
|
267 |
+
"""
|
268 |
+
Return len(a) element-wise.
|
269 |
+
|
270 |
+
Parameters
|
271 |
+
----------
|
272 |
+
a : array_like of str or unicode
|
273 |
+
|
274 |
+
Returns
|
275 |
+
-------
|
276 |
+
out : ndarray
|
277 |
+
Output array of integers
|
278 |
+
|
279 |
+
See Also
|
280 |
+
--------
|
281 |
+
len
|
282 |
+
|
283 |
+
Examples
|
284 |
+
--------
|
285 |
+
>>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])
|
286 |
+
>>> np.char.str_len(a)
|
287 |
+
array([23, 15])
|
288 |
+
>>> a = np.array([u'\u0420', u'\u043e'])
|
289 |
+
>>> np.char.str_len(a)
|
290 |
+
array([1, 1])
|
291 |
+
>>> a = np.array([['hello', 'world'], [u'\u0420', u'\u043e']])
|
292 |
+
>>> np.char.str_len(a)
|
293 |
+
array([[5, 5], [1, 1]])
|
294 |
+
"""
|
295 |
+
# Note: __len__, etc. currently return ints, which are not C-integers.
|
296 |
+
# Generally intp would be expected for lengths, although int is sufficient
|
297 |
+
# due to the dtype itemsize limitation.
|
298 |
+
return _vec_string(a, int_, '__len__')
|
299 |
+
|
300 |
+
|
301 |
+
@array_function_dispatch(_binary_op_dispatcher)
|
302 |
+
def add(x1, x2):
|
303 |
+
"""
|
304 |
+
Return element-wise string concatenation for two arrays of str or unicode.
|
305 |
+
|
306 |
+
Arrays `x1` and `x2` must have the same shape.
|
307 |
+
|
308 |
+
Parameters
|
309 |
+
----------
|
310 |
+
x1 : array_like of str or unicode
|
311 |
+
Input array.
|
312 |
+
x2 : array_like of str or unicode
|
313 |
+
Input array.
|
314 |
+
|
315 |
+
Returns
|
316 |
+
-------
|
317 |
+
add : ndarray
|
318 |
+
Output array of `bytes_` or `str_`, depending on input types
|
319 |
+
of the same shape as `x1` and `x2`.
|
320 |
+
|
321 |
+
"""
|
322 |
+
arr1 = numpy.asarray(x1)
|
323 |
+
arr2 = numpy.asarray(x2)
|
324 |
+
out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
|
325 |
+
|
326 |
+
if type(arr1.dtype) != type(arr2.dtype):
|
327 |
+
# Enforce this for now. The solution to it will be implement add
|
328 |
+
# as a ufunc. It never worked right on Python 3: bytes + unicode gave
|
329 |
+
# nonsense unicode + bytes errored, and unicode + object used the
|
330 |
+
# object dtype itemsize as num chars (worked on short strings).
|
331 |
+
# bytes + void worked but promoting void->bytes is dubious also.
|
332 |
+
raise TypeError(
|
333 |
+
"np.char.add() requires both arrays of the same dtype kind, but "
|
334 |
+
f"got dtypes: '{arr1.dtype}' and '{arr2.dtype}' (the few cases "
|
335 |
+
"where this used to work often lead to incorrect results).")
|
336 |
+
|
337 |
+
return _vec_string(arr1, type(arr1.dtype)(out_size), '__add__', (arr2,))
|
338 |
+
|
339 |
+
def _multiply_dispatcher(a, i):
|
340 |
+
return (a,)
|
341 |
+
|
342 |
+
|
343 |
+
@array_function_dispatch(_multiply_dispatcher)
|
344 |
+
def multiply(a, i):
|
345 |
+
"""
|
346 |
+
Return (a * i), that is string multiple concatenation,
|
347 |
+
element-wise.
|
348 |
+
|
349 |
+
Values in `i` of less than 0 are treated as 0 (which yields an
|
350 |
+
empty string).
|
351 |
+
|
352 |
+
Parameters
|
353 |
+
----------
|
354 |
+
a : array_like of str or unicode
|
355 |
+
|
356 |
+
i : array_like of ints
|
357 |
+
|
358 |
+
Returns
|
359 |
+
-------
|
360 |
+
out : ndarray
|
361 |
+
Output array of str or unicode, depending on input types
|
362 |
+
|
363 |
+
Examples
|
364 |
+
--------
|
365 |
+
>>> a = np.array(["a", "b", "c"])
|
366 |
+
>>> np.char.multiply(x, 3)
|
367 |
+
array(['aaa', 'bbb', 'ccc'], dtype='<U3')
|
368 |
+
>>> i = np.array([1, 2, 3])
|
369 |
+
>>> np.char.multiply(a, i)
|
370 |
+
array(['a', 'bb', 'ccc'], dtype='<U3')
|
371 |
+
>>> np.char.multiply(np.array(['a']), i)
|
372 |
+
array(['a', 'aa', 'aaa'], dtype='<U3')
|
373 |
+
>>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
|
374 |
+
>>> np.char.multiply(a, 3)
|
375 |
+
array([['aaa', 'bbb', 'ccc'],
|
376 |
+
['ddd', 'eee', 'fff']], dtype='<U3')
|
377 |
+
>>> np.char.multiply(a, i)
|
378 |
+
array([['a', 'bb', 'ccc'],
|
379 |
+
['d', 'ee', 'fff']], dtype='<U3')
|
380 |
+
"""
|
381 |
+
a_arr = numpy.asarray(a)
|
382 |
+
i_arr = numpy.asarray(i)
|
383 |
+
if not issubclass(i_arr.dtype.type, integer):
|
384 |
+
raise ValueError("Can only multiply by integers")
|
385 |
+
out_size = _get_num_chars(a_arr) * max(int(i_arr.max()), 0)
|
386 |
+
return _vec_string(
|
387 |
+
a_arr, type(a_arr.dtype)(out_size), '__mul__', (i_arr,))
|
388 |
+
|
389 |
+
|
390 |
+
def _mod_dispatcher(a, values):
|
391 |
+
return (a, values)
|
392 |
+
|
393 |
+
|
394 |
+
@array_function_dispatch(_mod_dispatcher)
|
395 |
+
def mod(a, values):
|
396 |
+
"""
|
397 |
+
Return (a % i), that is pre-Python 2.6 string formatting
|
398 |
+
(interpolation), element-wise for a pair of array_likes of str
|
399 |
+
or unicode.
|
400 |
+
|
401 |
+
Parameters
|
402 |
+
----------
|
403 |
+
a : array_like of str or unicode
|
404 |
+
|
405 |
+
values : array_like of values
|
406 |
+
These values will be element-wise interpolated into the string.
|
407 |
+
|
408 |
+
Returns
|
409 |
+
-------
|
410 |
+
out : ndarray
|
411 |
+
Output array of str or unicode, depending on input types
|
412 |
+
|
413 |
+
See Also
|
414 |
+
--------
|
415 |
+
str.__mod__
|
416 |
+
|
417 |
+
"""
|
418 |
+
return _to_bytes_or_str_array(
|
419 |
+
_vec_string(a, object_, '__mod__', (values,)), a)
|
420 |
+
|
421 |
+
|
422 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
423 |
+
def capitalize(a):
|
424 |
+
"""
|
425 |
+
Return a copy of `a` with only the first character of each element
|
426 |
+
capitalized.
|
427 |
+
|
428 |
+
Calls `str.capitalize` element-wise.
|
429 |
+
|
430 |
+
For 8-bit strings, this method is locale-dependent.
|
431 |
+
|
432 |
+
Parameters
|
433 |
+
----------
|
434 |
+
a : array_like of str or unicode
|
435 |
+
Input array of strings to capitalize.
|
436 |
+
|
437 |
+
Returns
|
438 |
+
-------
|
439 |
+
out : ndarray
|
440 |
+
Output array of str or unicode, depending on input
|
441 |
+
types
|
442 |
+
|
443 |
+
See Also
|
444 |
+
--------
|
445 |
+
str.capitalize
|
446 |
+
|
447 |
+
Examples
|
448 |
+
--------
|
449 |
+
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
|
450 |
+
array(['a1b2', '1b2a', 'b2a1', '2a1b'],
|
451 |
+
dtype='|S4')
|
452 |
+
>>> np.char.capitalize(c)
|
453 |
+
array(['A1b2', '1b2a', 'B2a1', '2a1b'],
|
454 |
+
dtype='|S4')
|
455 |
+
|
456 |
+
"""
|
457 |
+
a_arr = numpy.asarray(a)
|
458 |
+
return _vec_string(a_arr, a_arr.dtype, 'capitalize')
|
459 |
+
|
460 |
+
|
461 |
+
def _center_dispatcher(a, width, fillchar=None):
|
462 |
+
return (a,)
|
463 |
+
|
464 |
+
|
465 |
+
@array_function_dispatch(_center_dispatcher)
|
466 |
+
def center(a, width, fillchar=' '):
|
467 |
+
"""
|
468 |
+
Return a copy of `a` with its elements centered in a string of
|
469 |
+
length `width`.
|
470 |
+
|
471 |
+
Calls `str.center` element-wise.
|
472 |
+
|
473 |
+
Parameters
|
474 |
+
----------
|
475 |
+
a : array_like of str or unicode
|
476 |
+
|
477 |
+
width : int
|
478 |
+
The length of the resulting strings
|
479 |
+
fillchar : str or unicode, optional
|
480 |
+
The padding character to use (default is space).
|
481 |
+
|
482 |
+
Returns
|
483 |
+
-------
|
484 |
+
out : ndarray
|
485 |
+
Output array of str or unicode, depending on input
|
486 |
+
types
|
487 |
+
|
488 |
+
See Also
|
489 |
+
--------
|
490 |
+
str.center
|
491 |
+
|
492 |
+
Notes
|
493 |
+
-----
|
494 |
+
This function is intended to work with arrays of strings. The
|
495 |
+
fill character is not applied to numeric types.
|
496 |
+
|
497 |
+
Examples
|
498 |
+
--------
|
499 |
+
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
|
500 |
+
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
|
501 |
+
>>> np.char.center(c, width=9)
|
502 |
+
array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
|
503 |
+
>>> np.char.center(c, width=9, fillchar='*')
|
504 |
+
array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
|
505 |
+
>>> np.char.center(c, width=1)
|
506 |
+
array(['a', '1', 'b', '2'], dtype='<U1')
|
507 |
+
|
508 |
+
"""
|
509 |
+
a_arr = numpy.asarray(a)
|
510 |
+
width_arr = numpy.asarray(width)
|
511 |
+
size = int(numpy.max(width_arr.flat))
|
512 |
+
if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
|
513 |
+
fillchar = asbytes(fillchar)
|
514 |
+
return _vec_string(
|
515 |
+
a_arr, type(a_arr.dtype)(size), 'center', (width_arr, fillchar))
|
516 |
+
|
517 |
+
|
518 |
+
def _count_dispatcher(a, sub, start=None, end=None):
|
519 |
+
return (a,)
|
520 |
+
|
521 |
+
|
522 |
+
@array_function_dispatch(_count_dispatcher)
|
523 |
+
def count(a, sub, start=0, end=None):
|
524 |
+
"""
|
525 |
+
Returns an array with the number of non-overlapping occurrences of
|
526 |
+
substring `sub` in the range [`start`, `end`].
|
527 |
+
|
528 |
+
Calls `str.count` element-wise.
|
529 |
+
|
530 |
+
Parameters
|
531 |
+
----------
|
532 |
+
a : array_like of str or unicode
|
533 |
+
|
534 |
+
sub : str or unicode
|
535 |
+
The substring to search for.
|
536 |
+
|
537 |
+
start, end : int, optional
|
538 |
+
Optional arguments `start` and `end` are interpreted as slice
|
539 |
+
notation to specify the range in which to count.
|
540 |
+
|
541 |
+
Returns
|
542 |
+
-------
|
543 |
+
out : ndarray
|
544 |
+
Output array of ints.
|
545 |
+
|
546 |
+
See Also
|
547 |
+
--------
|
548 |
+
str.count
|
549 |
+
|
550 |
+
Examples
|
551 |
+
--------
|
552 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
553 |
+
>>> c
|
554 |
+
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
|
555 |
+
>>> np.char.count(c, 'A')
|
556 |
+
array([3, 1, 1])
|
557 |
+
>>> np.char.count(c, 'aA')
|
558 |
+
array([3, 1, 0])
|
559 |
+
>>> np.char.count(c, 'A', start=1, end=4)
|
560 |
+
array([2, 1, 1])
|
561 |
+
>>> np.char.count(c, 'A', start=1, end=3)
|
562 |
+
array([1, 0, 0])
|
563 |
+
|
564 |
+
"""
|
565 |
+
return _vec_string(a, int_, 'count', [sub, start] + _clean_args(end))
|
566 |
+
|
567 |
+
|
568 |
+
def _code_dispatcher(a, encoding=None, errors=None):
|
569 |
+
return (a,)
|
570 |
+
|
571 |
+
|
572 |
+
@array_function_dispatch(_code_dispatcher)
|
573 |
+
def decode(a, encoding=None, errors=None):
|
574 |
+
r"""
|
575 |
+
Calls ``bytes.decode`` element-wise.
|
576 |
+
|
577 |
+
The set of available codecs comes from the Python standard library,
|
578 |
+
and may be extended at runtime. For more information, see the
|
579 |
+
:mod:`codecs` module.
|
580 |
+
|
581 |
+
Parameters
|
582 |
+
----------
|
583 |
+
a : array_like of str or unicode
|
584 |
+
|
585 |
+
encoding : str, optional
|
586 |
+
The name of an encoding
|
587 |
+
|
588 |
+
errors : str, optional
|
589 |
+
Specifies how to handle encoding errors
|
590 |
+
|
591 |
+
Returns
|
592 |
+
-------
|
593 |
+
out : ndarray
|
594 |
+
|
595 |
+
See Also
|
596 |
+
--------
|
597 |
+
:py:meth:`bytes.decode`
|
598 |
+
|
599 |
+
Notes
|
600 |
+
-----
|
601 |
+
The type of the result will depend on the encoding specified.
|
602 |
+
|
603 |
+
Examples
|
604 |
+
--------
|
605 |
+
>>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
|
606 |
+
... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
|
607 |
+
>>> c
|
608 |
+
array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
|
609 |
+
... b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
|
610 |
+
>>> np.char.decode(c, encoding='cp037')
|
611 |
+
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
|
612 |
+
|
613 |
+
"""
|
614 |
+
return _to_bytes_or_str_array(
|
615 |
+
_vec_string(a, object_, 'decode', _clean_args(encoding, errors)))
|
616 |
+
|
617 |
+
|
618 |
+
@array_function_dispatch(_code_dispatcher)
|
619 |
+
def encode(a, encoding=None, errors=None):
|
620 |
+
"""
|
621 |
+
Calls `str.encode` element-wise.
|
622 |
+
|
623 |
+
The set of available codecs comes from the Python standard library,
|
624 |
+
and may be extended at runtime. For more information, see the codecs
|
625 |
+
module.
|
626 |
+
|
627 |
+
Parameters
|
628 |
+
----------
|
629 |
+
a : array_like of str or unicode
|
630 |
+
|
631 |
+
encoding : str, optional
|
632 |
+
The name of an encoding
|
633 |
+
|
634 |
+
errors : str, optional
|
635 |
+
Specifies how to handle encoding errors
|
636 |
+
|
637 |
+
Returns
|
638 |
+
-------
|
639 |
+
out : ndarray
|
640 |
+
|
641 |
+
See Also
|
642 |
+
--------
|
643 |
+
str.encode
|
644 |
+
|
645 |
+
Notes
|
646 |
+
-----
|
647 |
+
The type of the result will depend on the encoding specified.
|
648 |
+
|
649 |
+
"""
|
650 |
+
return _to_bytes_or_str_array(
|
651 |
+
_vec_string(a, object_, 'encode', _clean_args(encoding, errors)))
|
652 |
+
|
653 |
+
|
654 |
+
def _endswith_dispatcher(a, suffix, start=None, end=None):
|
655 |
+
return (a,)
|
656 |
+
|
657 |
+
|
658 |
+
@array_function_dispatch(_endswith_dispatcher)
|
659 |
+
def endswith(a, suffix, start=0, end=None):
|
660 |
+
"""
|
661 |
+
Returns a boolean array which is `True` where the string element
|
662 |
+
in `a` ends with `suffix`, otherwise `False`.
|
663 |
+
|
664 |
+
Calls `str.endswith` element-wise.
|
665 |
+
|
666 |
+
Parameters
|
667 |
+
----------
|
668 |
+
a : array_like of str or unicode
|
669 |
+
|
670 |
+
suffix : str
|
671 |
+
|
672 |
+
start, end : int, optional
|
673 |
+
With optional `start`, test beginning at that position. With
|
674 |
+
optional `end`, stop comparing at that position.
|
675 |
+
|
676 |
+
Returns
|
677 |
+
-------
|
678 |
+
out : ndarray
|
679 |
+
Outputs an array of bools.
|
680 |
+
|
681 |
+
See Also
|
682 |
+
--------
|
683 |
+
str.endswith
|
684 |
+
|
685 |
+
Examples
|
686 |
+
--------
|
687 |
+
>>> s = np.array(['foo', 'bar'])
|
688 |
+
>>> s[0] = 'foo'
|
689 |
+
>>> s[1] = 'bar'
|
690 |
+
>>> s
|
691 |
+
array(['foo', 'bar'], dtype='<U3')
|
692 |
+
>>> np.char.endswith(s, 'ar')
|
693 |
+
array([False, True])
|
694 |
+
>>> np.char.endswith(s, 'a', start=1, end=2)
|
695 |
+
array([False, True])
|
696 |
+
|
697 |
+
"""
|
698 |
+
return _vec_string(
|
699 |
+
a, bool_, 'endswith', [suffix, start] + _clean_args(end))
|
700 |
+
|
701 |
+
|
702 |
+
def _expandtabs_dispatcher(a, tabsize=None):
|
703 |
+
return (a,)
|
704 |
+
|
705 |
+
|
706 |
+
@array_function_dispatch(_expandtabs_dispatcher)
|
707 |
+
def expandtabs(a, tabsize=8):
|
708 |
+
"""
|
709 |
+
Return a copy of each string element where all tab characters are
|
710 |
+
replaced by one or more spaces.
|
711 |
+
|
712 |
+
Calls `str.expandtabs` element-wise.
|
713 |
+
|
714 |
+
Return a copy of each string element where all tab characters are
|
715 |
+
replaced by one or more spaces, depending on the current column
|
716 |
+
and the given `tabsize`. The column number is reset to zero after
|
717 |
+
each newline occurring in the string. This doesn't understand other
|
718 |
+
non-printing characters or escape sequences.
|
719 |
+
|
720 |
+
Parameters
|
721 |
+
----------
|
722 |
+
a : array_like of str or unicode
|
723 |
+
Input array
|
724 |
+
tabsize : int, optional
|
725 |
+
Replace tabs with `tabsize` number of spaces. If not given defaults
|
726 |
+
to 8 spaces.
|
727 |
+
|
728 |
+
Returns
|
729 |
+
-------
|
730 |
+
out : ndarray
|
731 |
+
Output array of str or unicode, depending on input type
|
732 |
+
|
733 |
+
See Also
|
734 |
+
--------
|
735 |
+
str.expandtabs
|
736 |
+
|
737 |
+
"""
|
738 |
+
return _to_bytes_or_str_array(
|
739 |
+
_vec_string(a, object_, 'expandtabs', (tabsize,)), a)
|
740 |
+
|
741 |
+
|
742 |
+
@array_function_dispatch(_count_dispatcher)
|
743 |
+
def find(a, sub, start=0, end=None):
|
744 |
+
"""
|
745 |
+
For each element, return the lowest index in the string where
|
746 |
+
substring `sub` is found.
|
747 |
+
|
748 |
+
Calls `str.find` element-wise.
|
749 |
+
|
750 |
+
For each element, return the lowest index in the string where
|
751 |
+
substring `sub` is found, such that `sub` is contained in the
|
752 |
+
range [`start`, `end`].
|
753 |
+
|
754 |
+
Parameters
|
755 |
+
----------
|
756 |
+
a : array_like of str or unicode
|
757 |
+
|
758 |
+
sub : str or unicode
|
759 |
+
|
760 |
+
start, end : int, optional
|
761 |
+
Optional arguments `start` and `end` are interpreted as in
|
762 |
+
slice notation.
|
763 |
+
|
764 |
+
Returns
|
765 |
+
-------
|
766 |
+
out : ndarray or int
|
767 |
+
Output array of ints. Returns -1 if `sub` is not found.
|
768 |
+
|
769 |
+
See Also
|
770 |
+
--------
|
771 |
+
str.find
|
772 |
+
|
773 |
+
Examples
|
774 |
+
--------
|
775 |
+
>>> a = np.array(["NumPy is a Python library"])
|
776 |
+
>>> np.char.find(a, "Python", start=0, end=None)
|
777 |
+
array([11])
|
778 |
+
|
779 |
+
"""
|
780 |
+
return _vec_string(
|
781 |
+
a, int_, 'find', [sub, start] + _clean_args(end))
|
782 |
+
|
783 |
+
|
784 |
+
@array_function_dispatch(_count_dispatcher)
|
785 |
+
def index(a, sub, start=0, end=None):
|
786 |
+
"""
|
787 |
+
Like `find`, but raises `ValueError` when the substring is not found.
|
788 |
+
|
789 |
+
Calls `str.index` element-wise.
|
790 |
+
|
791 |
+
Parameters
|
792 |
+
----------
|
793 |
+
a : array_like of str or unicode
|
794 |
+
|
795 |
+
sub : str or unicode
|
796 |
+
|
797 |
+
start, end : int, optional
|
798 |
+
|
799 |
+
Returns
|
800 |
+
-------
|
801 |
+
out : ndarray
|
802 |
+
Output array of ints. Returns -1 if `sub` is not found.
|
803 |
+
|
804 |
+
See Also
|
805 |
+
--------
|
806 |
+
find, str.find
|
807 |
+
|
808 |
+
Examples
|
809 |
+
--------
|
810 |
+
>>> a = np.array(["Computer Science"])
|
811 |
+
>>> np.char.index(a, "Science", start=0, end=None)
|
812 |
+
array([9])
|
813 |
+
|
814 |
+
"""
|
815 |
+
return _vec_string(
|
816 |
+
a, int_, 'index', [sub, start] + _clean_args(end))
|
817 |
+
|
818 |
+
|
819 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
820 |
+
def isalnum(a):
|
821 |
+
"""
|
822 |
+
Returns true for each element if all characters in the string are
|
823 |
+
alphanumeric and there is at least one character, false otherwise.
|
824 |
+
|
825 |
+
Calls `str.isalnum` element-wise.
|
826 |
+
|
827 |
+
For 8-bit strings, this method is locale-dependent.
|
828 |
+
|
829 |
+
Parameters
|
830 |
+
----------
|
831 |
+
a : array_like of str or unicode
|
832 |
+
|
833 |
+
Returns
|
834 |
+
-------
|
835 |
+
out : ndarray
|
836 |
+
Output array of str or unicode, depending on input type
|
837 |
+
|
838 |
+
See Also
|
839 |
+
--------
|
840 |
+
str.isalnum
|
841 |
+
"""
|
842 |
+
return _vec_string(a, bool_, 'isalnum')
|
843 |
+
|
844 |
+
|
845 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
846 |
+
def isalpha(a):
|
847 |
+
"""
|
848 |
+
Returns true for each element if all characters in the string are
|
849 |
+
alphabetic and there is at least one character, false otherwise.
|
850 |
+
|
851 |
+
Calls `str.isalpha` element-wise.
|
852 |
+
|
853 |
+
For 8-bit strings, this method is locale-dependent.
|
854 |
+
|
855 |
+
Parameters
|
856 |
+
----------
|
857 |
+
a : array_like of str or unicode
|
858 |
+
|
859 |
+
Returns
|
860 |
+
-------
|
861 |
+
out : ndarray
|
862 |
+
Output array of bools
|
863 |
+
|
864 |
+
See Also
|
865 |
+
--------
|
866 |
+
str.isalpha
|
867 |
+
"""
|
868 |
+
return _vec_string(a, bool_, 'isalpha')
|
869 |
+
|
870 |
+
|
871 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
872 |
+
def isdigit(a):
|
873 |
+
"""
|
874 |
+
Returns true for each element if all characters in the string are
|
875 |
+
digits and there is at least one character, false otherwise.
|
876 |
+
|
877 |
+
Calls `str.isdigit` element-wise.
|
878 |
+
|
879 |
+
For 8-bit strings, this method is locale-dependent.
|
880 |
+
|
881 |
+
Parameters
|
882 |
+
----------
|
883 |
+
a : array_like of str or unicode
|
884 |
+
|
885 |
+
Returns
|
886 |
+
-------
|
887 |
+
out : ndarray
|
888 |
+
Output array of bools
|
889 |
+
|
890 |
+
See Also
|
891 |
+
--------
|
892 |
+
str.isdigit
|
893 |
+
|
894 |
+
Examples
|
895 |
+
--------
|
896 |
+
>>> a = np.array(['a', 'b', '0'])
|
897 |
+
>>> np.char.isdigit(a)
|
898 |
+
array([False, False, True])
|
899 |
+
>>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
|
900 |
+
>>> np.char.isdigit(a)
|
901 |
+
array([[False, False, True], [False, True, True]])
|
902 |
+
"""
|
903 |
+
return _vec_string(a, bool_, 'isdigit')
|
904 |
+
|
905 |
+
|
906 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
907 |
+
def islower(a):
|
908 |
+
"""
|
909 |
+
Returns true for each element if all cased characters in the
|
910 |
+
string are lowercase and there is at least one cased character,
|
911 |
+
false otherwise.
|
912 |
+
|
913 |
+
Calls `str.islower` element-wise.
|
914 |
+
|
915 |
+
For 8-bit strings, this method is locale-dependent.
|
916 |
+
|
917 |
+
Parameters
|
918 |
+
----------
|
919 |
+
a : array_like of str or unicode
|
920 |
+
|
921 |
+
Returns
|
922 |
+
-------
|
923 |
+
out : ndarray
|
924 |
+
Output array of bools
|
925 |
+
|
926 |
+
See Also
|
927 |
+
--------
|
928 |
+
str.islower
|
929 |
+
"""
|
930 |
+
return _vec_string(a, bool_, 'islower')
|
931 |
+
|
932 |
+
|
933 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
934 |
+
def isspace(a):
|
935 |
+
"""
|
936 |
+
Returns true for each element if there are only whitespace
|
937 |
+
characters in the string and there is at least one character,
|
938 |
+
false otherwise.
|
939 |
+
|
940 |
+
Calls `str.isspace` element-wise.
|
941 |
+
|
942 |
+
For 8-bit strings, this method is locale-dependent.
|
943 |
+
|
944 |
+
Parameters
|
945 |
+
----------
|
946 |
+
a : array_like of str or unicode
|
947 |
+
|
948 |
+
Returns
|
949 |
+
-------
|
950 |
+
out : ndarray
|
951 |
+
Output array of bools
|
952 |
+
|
953 |
+
See Also
|
954 |
+
--------
|
955 |
+
str.isspace
|
956 |
+
"""
|
957 |
+
return _vec_string(a, bool_, 'isspace')
|
958 |
+
|
959 |
+
|
960 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
961 |
+
def istitle(a):
|
962 |
+
"""
|
963 |
+
Returns true for each element if the element is a titlecased
|
964 |
+
string and there is at least one character, false otherwise.
|
965 |
+
|
966 |
+
Call `str.istitle` element-wise.
|
967 |
+
|
968 |
+
For 8-bit strings, this method is locale-dependent.
|
969 |
+
|
970 |
+
Parameters
|
971 |
+
----------
|
972 |
+
a : array_like of str or unicode
|
973 |
+
|
974 |
+
Returns
|
975 |
+
-------
|
976 |
+
out : ndarray
|
977 |
+
Output array of bools
|
978 |
+
|
979 |
+
See Also
|
980 |
+
--------
|
981 |
+
str.istitle
|
982 |
+
"""
|
983 |
+
return _vec_string(a, bool_, 'istitle')
|
984 |
+
|
985 |
+
|
986 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
987 |
+
def isupper(a):
|
988 |
+
"""
|
989 |
+
Return true for each element if all cased characters in the
|
990 |
+
string are uppercase and there is at least one character, false
|
991 |
+
otherwise.
|
992 |
+
|
993 |
+
Call `str.isupper` element-wise.
|
994 |
+
|
995 |
+
For 8-bit strings, this method is locale-dependent.
|
996 |
+
|
997 |
+
Parameters
|
998 |
+
----------
|
999 |
+
a : array_like of str or unicode
|
1000 |
+
|
1001 |
+
Returns
|
1002 |
+
-------
|
1003 |
+
out : ndarray
|
1004 |
+
Output array of bools
|
1005 |
+
|
1006 |
+
See Also
|
1007 |
+
--------
|
1008 |
+
str.isupper
|
1009 |
+
|
1010 |
+
Examples
|
1011 |
+
--------
|
1012 |
+
>>> str = "GHC"
|
1013 |
+
>>> np.char.isupper(str)
|
1014 |
+
array(True)
|
1015 |
+
>>> a = np.array(["hello", "HELLO", "Hello"])
|
1016 |
+
>>> np.char.isupper(a)
|
1017 |
+
array([False, True, False])
|
1018 |
+
|
1019 |
+
"""
|
1020 |
+
return _vec_string(a, bool_, 'isupper')
|
1021 |
+
|
1022 |
+
|
1023 |
+
def _join_dispatcher(sep, seq):
|
1024 |
+
return (sep, seq)
|
1025 |
+
|
1026 |
+
|
1027 |
+
@array_function_dispatch(_join_dispatcher)
|
1028 |
+
def join(sep, seq):
|
1029 |
+
"""
|
1030 |
+
Return a string which is the concatenation of the strings in the
|
1031 |
+
sequence `seq`.
|
1032 |
+
|
1033 |
+
Calls `str.join` element-wise.
|
1034 |
+
|
1035 |
+
Parameters
|
1036 |
+
----------
|
1037 |
+
sep : array_like of str or unicode
|
1038 |
+
seq : array_like of str or unicode
|
1039 |
+
|
1040 |
+
Returns
|
1041 |
+
-------
|
1042 |
+
out : ndarray
|
1043 |
+
Output array of str or unicode, depending on input types
|
1044 |
+
|
1045 |
+
See Also
|
1046 |
+
--------
|
1047 |
+
str.join
|
1048 |
+
|
1049 |
+
Examples
|
1050 |
+
--------
|
1051 |
+
>>> np.char.join('-', 'osd')
|
1052 |
+
array('o-s-d', dtype='<U5')
|
1053 |
+
|
1054 |
+
>>> np.char.join(['-', '.'], ['ghc', 'osd'])
|
1055 |
+
array(['g-h-c', 'o.s.d'], dtype='<U5')
|
1056 |
+
|
1057 |
+
"""
|
1058 |
+
return _to_bytes_or_str_array(
|
1059 |
+
_vec_string(sep, object_, 'join', (seq,)), seq)
|
1060 |
+
|
1061 |
+
|
1062 |
+
|
1063 |
+
def _just_dispatcher(a, width, fillchar=None):
|
1064 |
+
return (a,)
|
1065 |
+
|
1066 |
+
|
1067 |
+
@array_function_dispatch(_just_dispatcher)
|
1068 |
+
def ljust(a, width, fillchar=' '):
|
1069 |
+
"""
|
1070 |
+
Return an array with the elements of `a` left-justified in a
|
1071 |
+
string of length `width`.
|
1072 |
+
|
1073 |
+
Calls `str.ljust` element-wise.
|
1074 |
+
|
1075 |
+
Parameters
|
1076 |
+
----------
|
1077 |
+
a : array_like of str or unicode
|
1078 |
+
|
1079 |
+
width : int
|
1080 |
+
The length of the resulting strings
|
1081 |
+
fillchar : str or unicode, optional
|
1082 |
+
The character to use for padding
|
1083 |
+
|
1084 |
+
Returns
|
1085 |
+
-------
|
1086 |
+
out : ndarray
|
1087 |
+
Output array of str or unicode, depending on input type
|
1088 |
+
|
1089 |
+
See Also
|
1090 |
+
--------
|
1091 |
+
str.ljust
|
1092 |
+
|
1093 |
+
"""
|
1094 |
+
a_arr = numpy.asarray(a)
|
1095 |
+
width_arr = numpy.asarray(width)
|
1096 |
+
size = int(numpy.max(width_arr.flat))
|
1097 |
+
if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
|
1098 |
+
fillchar = asbytes(fillchar)
|
1099 |
+
return _vec_string(
|
1100 |
+
a_arr, type(a_arr.dtype)(size), 'ljust', (width_arr, fillchar))
|
1101 |
+
|
1102 |
+
|
1103 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1104 |
+
def lower(a):
|
1105 |
+
"""
|
1106 |
+
Return an array with the elements converted to lowercase.
|
1107 |
+
|
1108 |
+
Call `str.lower` element-wise.
|
1109 |
+
|
1110 |
+
For 8-bit strings, this method is locale-dependent.
|
1111 |
+
|
1112 |
+
Parameters
|
1113 |
+
----------
|
1114 |
+
a : array_like, {str, unicode}
|
1115 |
+
Input array.
|
1116 |
+
|
1117 |
+
Returns
|
1118 |
+
-------
|
1119 |
+
out : ndarray, {str, unicode}
|
1120 |
+
Output array of str or unicode, depending on input type
|
1121 |
+
|
1122 |
+
See Also
|
1123 |
+
--------
|
1124 |
+
str.lower
|
1125 |
+
|
1126 |
+
Examples
|
1127 |
+
--------
|
1128 |
+
>>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
|
1129 |
+
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
|
1130 |
+
>>> np.char.lower(c)
|
1131 |
+
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
|
1132 |
+
|
1133 |
+
"""
|
1134 |
+
a_arr = numpy.asarray(a)
|
1135 |
+
return _vec_string(a_arr, a_arr.dtype, 'lower')
|
1136 |
+
|
1137 |
+
|
1138 |
+
def _strip_dispatcher(a, chars=None):
|
1139 |
+
return (a,)
|
1140 |
+
|
1141 |
+
|
1142 |
+
@array_function_dispatch(_strip_dispatcher)
|
1143 |
+
def lstrip(a, chars=None):
|
1144 |
+
"""
|
1145 |
+
For each element in `a`, return a copy with the leading characters
|
1146 |
+
removed.
|
1147 |
+
|
1148 |
+
Calls `str.lstrip` element-wise.
|
1149 |
+
|
1150 |
+
Parameters
|
1151 |
+
----------
|
1152 |
+
a : array-like, {str, unicode}
|
1153 |
+
Input array.
|
1154 |
+
|
1155 |
+
chars : {str, unicode}, optional
|
1156 |
+
The `chars` argument is a string specifying the set of
|
1157 |
+
characters to be removed. If omitted or None, the `chars`
|
1158 |
+
argument defaults to removing whitespace. The `chars` argument
|
1159 |
+
is not a prefix; rather, all combinations of its values are
|
1160 |
+
stripped.
|
1161 |
+
|
1162 |
+
Returns
|
1163 |
+
-------
|
1164 |
+
out : ndarray, {str, unicode}
|
1165 |
+
Output array of str or unicode, depending on input type
|
1166 |
+
|
1167 |
+
See Also
|
1168 |
+
--------
|
1169 |
+
str.lstrip
|
1170 |
+
|
1171 |
+
Examples
|
1172 |
+
--------
|
1173 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
1174 |
+
>>> c
|
1175 |
+
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
|
1176 |
+
|
1177 |
+
The 'a' variable is unstripped from c[1] because whitespace leading.
|
1178 |
+
|
1179 |
+
>>> np.char.lstrip(c, 'a')
|
1180 |
+
array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
|
1181 |
+
|
1182 |
+
|
1183 |
+
>>> np.char.lstrip(c, 'A') # leaves c unchanged
|
1184 |
+
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
|
1185 |
+
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
|
1186 |
+
... # XXX: is this a regression? This used to return True
|
1187 |
+
... # np.char.lstrip(c,'') does not modify c at all.
|
1188 |
+
False
|
1189 |
+
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
|
1190 |
+
True
|
1191 |
+
|
1192 |
+
"""
|
1193 |
+
a_arr = numpy.asarray(a)
|
1194 |
+
return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,))
|
1195 |
+
|
1196 |
+
|
1197 |
+
def _partition_dispatcher(a, sep):
|
1198 |
+
return (a,)
|
1199 |
+
|
1200 |
+
|
1201 |
+
@array_function_dispatch(_partition_dispatcher)
|
1202 |
+
def partition(a, sep):
|
1203 |
+
"""
|
1204 |
+
Partition each element in `a` around `sep`.
|
1205 |
+
|
1206 |
+
Calls `str.partition` element-wise.
|
1207 |
+
|
1208 |
+
For each element in `a`, split the element as the first
|
1209 |
+
occurrence of `sep`, and return 3 strings containing the part
|
1210 |
+
before the separator, the separator itself, and the part after
|
1211 |
+
the separator. If the separator is not found, return 3 strings
|
1212 |
+
containing the string itself, followed by two empty strings.
|
1213 |
+
|
1214 |
+
Parameters
|
1215 |
+
----------
|
1216 |
+
a : array_like, {str, unicode}
|
1217 |
+
Input array
|
1218 |
+
sep : {str, unicode}
|
1219 |
+
Separator to split each string element in `a`.
|
1220 |
+
|
1221 |
+
Returns
|
1222 |
+
-------
|
1223 |
+
out : ndarray, {str, unicode}
|
1224 |
+
Output array of str or unicode, depending on input type.
|
1225 |
+
The output array will have an extra dimension with 3
|
1226 |
+
elements per input element.
|
1227 |
+
|
1228 |
+
See Also
|
1229 |
+
--------
|
1230 |
+
str.partition
|
1231 |
+
|
1232 |
+
"""
|
1233 |
+
return _to_bytes_or_str_array(
|
1234 |
+
_vec_string(a, object_, 'partition', (sep,)), a)
|
1235 |
+
|
1236 |
+
|
1237 |
+
def _replace_dispatcher(a, old, new, count=None):
|
1238 |
+
return (a,)
|
1239 |
+
|
1240 |
+
|
1241 |
+
@array_function_dispatch(_replace_dispatcher)
|
1242 |
+
def replace(a, old, new, count=None):
|
1243 |
+
"""
|
1244 |
+
For each element in `a`, return a copy of the string with all
|
1245 |
+
occurrences of substring `old` replaced by `new`.
|
1246 |
+
|
1247 |
+
Calls `str.replace` element-wise.
|
1248 |
+
|
1249 |
+
Parameters
|
1250 |
+
----------
|
1251 |
+
a : array-like of str or unicode
|
1252 |
+
|
1253 |
+
old, new : str or unicode
|
1254 |
+
|
1255 |
+
count : int, optional
|
1256 |
+
If the optional argument `count` is given, only the first
|
1257 |
+
`count` occurrences are replaced.
|
1258 |
+
|
1259 |
+
Returns
|
1260 |
+
-------
|
1261 |
+
out : ndarray
|
1262 |
+
Output array of str or unicode, depending on input type
|
1263 |
+
|
1264 |
+
See Also
|
1265 |
+
--------
|
1266 |
+
str.replace
|
1267 |
+
|
1268 |
+
Examples
|
1269 |
+
--------
|
1270 |
+
>>> a = np.array(["That is a mango", "Monkeys eat mangos"])
|
1271 |
+
>>> np.char.replace(a, 'mango', 'banana')
|
1272 |
+
array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19')
|
1273 |
+
|
1274 |
+
>>> a = np.array(["The dish is fresh", "This is it"])
|
1275 |
+
>>> np.char.replace(a, 'is', 'was')
|
1276 |
+
array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
|
1277 |
+
"""
|
1278 |
+
return _to_bytes_or_str_array(
|
1279 |
+
_vec_string(a, object_, 'replace', [old, new] + _clean_args(count)), a)
|
1280 |
+
|
1281 |
+
|
1282 |
+
@array_function_dispatch(_count_dispatcher)
|
1283 |
+
def rfind(a, sub, start=0, end=None):
|
1284 |
+
"""
|
1285 |
+
For each element in `a`, return the highest index in the string
|
1286 |
+
where substring `sub` is found, such that `sub` is contained
|
1287 |
+
within [`start`, `end`].
|
1288 |
+
|
1289 |
+
Calls `str.rfind` element-wise.
|
1290 |
+
|
1291 |
+
Parameters
|
1292 |
+
----------
|
1293 |
+
a : array-like of str or unicode
|
1294 |
+
|
1295 |
+
sub : str or unicode
|
1296 |
+
|
1297 |
+
start, end : int, optional
|
1298 |
+
Optional arguments `start` and `end` are interpreted as in
|
1299 |
+
slice notation.
|
1300 |
+
|
1301 |
+
Returns
|
1302 |
+
-------
|
1303 |
+
out : ndarray
|
1304 |
+
Output array of ints. Return -1 on failure.
|
1305 |
+
|
1306 |
+
See Also
|
1307 |
+
--------
|
1308 |
+
str.rfind
|
1309 |
+
|
1310 |
+
"""
|
1311 |
+
return _vec_string(
|
1312 |
+
a, int_, 'rfind', [sub, start] + _clean_args(end))
|
1313 |
+
|
1314 |
+
|
1315 |
+
@array_function_dispatch(_count_dispatcher)
|
1316 |
+
def rindex(a, sub, start=0, end=None):
|
1317 |
+
"""
|
1318 |
+
Like `rfind`, but raises `ValueError` when the substring `sub` is
|
1319 |
+
not found.
|
1320 |
+
|
1321 |
+
Calls `str.rindex` element-wise.
|
1322 |
+
|
1323 |
+
Parameters
|
1324 |
+
----------
|
1325 |
+
a : array-like of str or unicode
|
1326 |
+
|
1327 |
+
sub : str or unicode
|
1328 |
+
|
1329 |
+
start, end : int, optional
|
1330 |
+
|
1331 |
+
Returns
|
1332 |
+
-------
|
1333 |
+
out : ndarray
|
1334 |
+
Output array of ints.
|
1335 |
+
|
1336 |
+
See Also
|
1337 |
+
--------
|
1338 |
+
rfind, str.rindex
|
1339 |
+
|
1340 |
+
"""
|
1341 |
+
return _vec_string(
|
1342 |
+
a, int_, 'rindex', [sub, start] + _clean_args(end))
|
1343 |
+
|
1344 |
+
|
1345 |
+
@array_function_dispatch(_just_dispatcher)
|
1346 |
+
def rjust(a, width, fillchar=' '):
|
1347 |
+
"""
|
1348 |
+
Return an array with the elements of `a` right-justified in a
|
1349 |
+
string of length `width`.
|
1350 |
+
|
1351 |
+
Calls `str.rjust` element-wise.
|
1352 |
+
|
1353 |
+
Parameters
|
1354 |
+
----------
|
1355 |
+
a : array_like of str or unicode
|
1356 |
+
|
1357 |
+
width : int
|
1358 |
+
The length of the resulting strings
|
1359 |
+
fillchar : str or unicode, optional
|
1360 |
+
The character to use for padding
|
1361 |
+
|
1362 |
+
Returns
|
1363 |
+
-------
|
1364 |
+
out : ndarray
|
1365 |
+
Output array of str or unicode, depending on input type
|
1366 |
+
|
1367 |
+
See Also
|
1368 |
+
--------
|
1369 |
+
str.rjust
|
1370 |
+
|
1371 |
+
"""
|
1372 |
+
a_arr = numpy.asarray(a)
|
1373 |
+
width_arr = numpy.asarray(width)
|
1374 |
+
size = int(numpy.max(width_arr.flat))
|
1375 |
+
if numpy.issubdtype(a_arr.dtype, numpy.bytes_):
|
1376 |
+
fillchar = asbytes(fillchar)
|
1377 |
+
return _vec_string(
|
1378 |
+
a_arr, type(a_arr.dtype)(size), 'rjust', (width_arr, fillchar))
|
1379 |
+
|
1380 |
+
|
1381 |
+
@array_function_dispatch(_partition_dispatcher)
|
1382 |
+
def rpartition(a, sep):
|
1383 |
+
"""
|
1384 |
+
Partition (split) each element around the right-most separator.
|
1385 |
+
|
1386 |
+
Calls `str.rpartition` element-wise.
|
1387 |
+
|
1388 |
+
For each element in `a`, split the element as the last
|
1389 |
+
occurrence of `sep`, and return 3 strings containing the part
|
1390 |
+
before the separator, the separator itself, and the part after
|
1391 |
+
the separator. If the separator is not found, return 3 strings
|
1392 |
+
containing the string itself, followed by two empty strings.
|
1393 |
+
|
1394 |
+
Parameters
|
1395 |
+
----------
|
1396 |
+
a : array_like of str or unicode
|
1397 |
+
Input array
|
1398 |
+
sep : str or unicode
|
1399 |
+
Right-most separator to split each element in array.
|
1400 |
+
|
1401 |
+
Returns
|
1402 |
+
-------
|
1403 |
+
out : ndarray
|
1404 |
+
Output array of string or unicode, depending on input
|
1405 |
+
type. The output array will have an extra dimension with
|
1406 |
+
3 elements per input element.
|
1407 |
+
|
1408 |
+
See Also
|
1409 |
+
--------
|
1410 |
+
str.rpartition
|
1411 |
+
|
1412 |
+
"""
|
1413 |
+
return _to_bytes_or_str_array(
|
1414 |
+
_vec_string(a, object_, 'rpartition', (sep,)), a)
|
1415 |
+
|
1416 |
+
|
1417 |
+
def _split_dispatcher(a, sep=None, maxsplit=None):
|
1418 |
+
return (a,)
|
1419 |
+
|
1420 |
+
|
1421 |
+
@array_function_dispatch(_split_dispatcher)
|
1422 |
+
def rsplit(a, sep=None, maxsplit=None):
|
1423 |
+
"""
|
1424 |
+
For each element in `a`, return a list of the words in the
|
1425 |
+
string, using `sep` as the delimiter string.
|
1426 |
+
|
1427 |
+
Calls `str.rsplit` element-wise.
|
1428 |
+
|
1429 |
+
Except for splitting from the right, `rsplit`
|
1430 |
+
behaves like `split`.
|
1431 |
+
|
1432 |
+
Parameters
|
1433 |
+
----------
|
1434 |
+
a : array_like of str or unicode
|
1435 |
+
|
1436 |
+
sep : str or unicode, optional
|
1437 |
+
If `sep` is not specified or None, any whitespace string
|
1438 |
+
is a separator.
|
1439 |
+
maxsplit : int, optional
|
1440 |
+
If `maxsplit` is given, at most `maxsplit` splits are done,
|
1441 |
+
the rightmost ones.
|
1442 |
+
|
1443 |
+
Returns
|
1444 |
+
-------
|
1445 |
+
out : ndarray
|
1446 |
+
Array of list objects
|
1447 |
+
|
1448 |
+
See Also
|
1449 |
+
--------
|
1450 |
+
str.rsplit, split
|
1451 |
+
|
1452 |
+
"""
|
1453 |
+
# This will return an array of lists of different sizes, so we
|
1454 |
+
# leave it as an object array
|
1455 |
+
return _vec_string(
|
1456 |
+
a, object_, 'rsplit', [sep] + _clean_args(maxsplit))
|
1457 |
+
|
1458 |
+
|
1459 |
+
def _strip_dispatcher(a, chars=None):
|
1460 |
+
return (a,)
|
1461 |
+
|
1462 |
+
|
1463 |
+
@array_function_dispatch(_strip_dispatcher)
|
1464 |
+
def rstrip(a, chars=None):
|
1465 |
+
"""
|
1466 |
+
For each element in `a`, return a copy with the trailing
|
1467 |
+
characters removed.
|
1468 |
+
|
1469 |
+
Calls `str.rstrip` element-wise.
|
1470 |
+
|
1471 |
+
Parameters
|
1472 |
+
----------
|
1473 |
+
a : array-like of str or unicode
|
1474 |
+
|
1475 |
+
chars : str or unicode, optional
|
1476 |
+
The `chars` argument is a string specifying the set of
|
1477 |
+
characters to be removed. If omitted or None, the `chars`
|
1478 |
+
argument defaults to removing whitespace. The `chars` argument
|
1479 |
+
is not a suffix; rather, all combinations of its values are
|
1480 |
+
stripped.
|
1481 |
+
|
1482 |
+
Returns
|
1483 |
+
-------
|
1484 |
+
out : ndarray
|
1485 |
+
Output array of str or unicode, depending on input type
|
1486 |
+
|
1487 |
+
See Also
|
1488 |
+
--------
|
1489 |
+
str.rstrip
|
1490 |
+
|
1491 |
+
Examples
|
1492 |
+
--------
|
1493 |
+
>>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
|
1494 |
+
array(['aAaAaA', 'abBABba'],
|
1495 |
+
dtype='|S7')
|
1496 |
+
>>> np.char.rstrip(c, b'a')
|
1497 |
+
array(['aAaAaA', 'abBABb'],
|
1498 |
+
dtype='|S7')
|
1499 |
+
>>> np.char.rstrip(c, b'A')
|
1500 |
+
array(['aAaAa', 'abBABba'],
|
1501 |
+
dtype='|S7')
|
1502 |
+
|
1503 |
+
"""
|
1504 |
+
a_arr = numpy.asarray(a)
|
1505 |
+
return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,))
|
1506 |
+
|
1507 |
+
|
1508 |
+
@array_function_dispatch(_split_dispatcher)
|
1509 |
+
def split(a, sep=None, maxsplit=None):
|
1510 |
+
"""
|
1511 |
+
For each element in `a`, return a list of the words in the
|
1512 |
+
string, using `sep` as the delimiter string.
|
1513 |
+
|
1514 |
+
Calls `str.split` element-wise.
|
1515 |
+
|
1516 |
+
Parameters
|
1517 |
+
----------
|
1518 |
+
a : array_like of str or unicode
|
1519 |
+
|
1520 |
+
sep : str or unicode, optional
|
1521 |
+
If `sep` is not specified or None, any whitespace string is a
|
1522 |
+
separator.
|
1523 |
+
|
1524 |
+
maxsplit : int, optional
|
1525 |
+
If `maxsplit` is given, at most `maxsplit` splits are done.
|
1526 |
+
|
1527 |
+
Returns
|
1528 |
+
-------
|
1529 |
+
out : ndarray
|
1530 |
+
Array of list objects
|
1531 |
+
|
1532 |
+
See Also
|
1533 |
+
--------
|
1534 |
+
str.split, rsplit
|
1535 |
+
|
1536 |
+
"""
|
1537 |
+
# This will return an array of lists of different sizes, so we
|
1538 |
+
# leave it as an object array
|
1539 |
+
return _vec_string(
|
1540 |
+
a, object_, 'split', [sep] + _clean_args(maxsplit))
|
1541 |
+
|
1542 |
+
|
1543 |
+
def _splitlines_dispatcher(a, keepends=None):
|
1544 |
+
return (a,)
|
1545 |
+
|
1546 |
+
|
1547 |
+
@array_function_dispatch(_splitlines_dispatcher)
|
1548 |
+
def splitlines(a, keepends=None):
|
1549 |
+
"""
|
1550 |
+
For each element in `a`, return a list of the lines in the
|
1551 |
+
element, breaking at line boundaries.
|
1552 |
+
|
1553 |
+
Calls `str.splitlines` element-wise.
|
1554 |
+
|
1555 |
+
Parameters
|
1556 |
+
----------
|
1557 |
+
a : array_like of str or unicode
|
1558 |
+
|
1559 |
+
keepends : bool, optional
|
1560 |
+
Line breaks are not included in the resulting list unless
|
1561 |
+
keepends is given and true.
|
1562 |
+
|
1563 |
+
Returns
|
1564 |
+
-------
|
1565 |
+
out : ndarray
|
1566 |
+
Array of list objects
|
1567 |
+
|
1568 |
+
See Also
|
1569 |
+
--------
|
1570 |
+
str.splitlines
|
1571 |
+
|
1572 |
+
"""
|
1573 |
+
return _vec_string(
|
1574 |
+
a, object_, 'splitlines', _clean_args(keepends))
|
1575 |
+
|
1576 |
+
|
1577 |
+
def _startswith_dispatcher(a, prefix, start=None, end=None):
|
1578 |
+
return (a,)
|
1579 |
+
|
1580 |
+
|
1581 |
+
@array_function_dispatch(_startswith_dispatcher)
|
1582 |
+
def startswith(a, prefix, start=0, end=None):
|
1583 |
+
"""
|
1584 |
+
Returns a boolean array which is `True` where the string element
|
1585 |
+
in `a` starts with `prefix`, otherwise `False`.
|
1586 |
+
|
1587 |
+
Calls `str.startswith` element-wise.
|
1588 |
+
|
1589 |
+
Parameters
|
1590 |
+
----------
|
1591 |
+
a : array_like of str or unicode
|
1592 |
+
|
1593 |
+
prefix : str
|
1594 |
+
|
1595 |
+
start, end : int, optional
|
1596 |
+
With optional `start`, test beginning at that position. With
|
1597 |
+
optional `end`, stop comparing at that position.
|
1598 |
+
|
1599 |
+
Returns
|
1600 |
+
-------
|
1601 |
+
out : ndarray
|
1602 |
+
Array of booleans
|
1603 |
+
|
1604 |
+
See Also
|
1605 |
+
--------
|
1606 |
+
str.startswith
|
1607 |
+
|
1608 |
+
"""
|
1609 |
+
return _vec_string(
|
1610 |
+
a, bool_, 'startswith', [prefix, start] + _clean_args(end))
|
1611 |
+
|
1612 |
+
|
1613 |
+
@array_function_dispatch(_strip_dispatcher)
|
1614 |
+
def strip(a, chars=None):
|
1615 |
+
"""
|
1616 |
+
For each element in `a`, return a copy with the leading and
|
1617 |
+
trailing characters removed.
|
1618 |
+
|
1619 |
+
Calls `str.strip` element-wise.
|
1620 |
+
|
1621 |
+
Parameters
|
1622 |
+
----------
|
1623 |
+
a : array-like of str or unicode
|
1624 |
+
|
1625 |
+
chars : str or unicode, optional
|
1626 |
+
The `chars` argument is a string specifying the set of
|
1627 |
+
characters to be removed. If omitted or None, the `chars`
|
1628 |
+
argument defaults to removing whitespace. The `chars` argument
|
1629 |
+
is not a prefix or suffix; rather, all combinations of its
|
1630 |
+
values are stripped.
|
1631 |
+
|
1632 |
+
Returns
|
1633 |
+
-------
|
1634 |
+
out : ndarray
|
1635 |
+
Output array of str or unicode, depending on input type
|
1636 |
+
|
1637 |
+
See Also
|
1638 |
+
--------
|
1639 |
+
str.strip
|
1640 |
+
|
1641 |
+
Examples
|
1642 |
+
--------
|
1643 |
+
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
|
1644 |
+
>>> c
|
1645 |
+
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
|
1646 |
+
>>> np.char.strip(c)
|
1647 |
+
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
|
1648 |
+
>>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
|
1649 |
+
array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
|
1650 |
+
>>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
|
1651 |
+
array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
|
1652 |
+
|
1653 |
+
"""
|
1654 |
+
a_arr = numpy.asarray(a)
|
1655 |
+
return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars))
|
1656 |
+
|
1657 |
+
|
1658 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1659 |
+
def swapcase(a):
|
1660 |
+
"""
|
1661 |
+
Return element-wise a copy of the string with
|
1662 |
+
uppercase characters converted to lowercase and vice versa.
|
1663 |
+
|
1664 |
+
Calls `str.swapcase` element-wise.
|
1665 |
+
|
1666 |
+
For 8-bit strings, this method is locale-dependent.
|
1667 |
+
|
1668 |
+
Parameters
|
1669 |
+
----------
|
1670 |
+
a : array_like, {str, unicode}
|
1671 |
+
Input array.
|
1672 |
+
|
1673 |
+
Returns
|
1674 |
+
-------
|
1675 |
+
out : ndarray, {str, unicode}
|
1676 |
+
Output array of str or unicode, depending on input type
|
1677 |
+
|
1678 |
+
See Also
|
1679 |
+
--------
|
1680 |
+
str.swapcase
|
1681 |
+
|
1682 |
+
Examples
|
1683 |
+
--------
|
1684 |
+
>>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
|
1685 |
+
array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
|
1686 |
+
dtype='|S5')
|
1687 |
+
>>> np.char.swapcase(c)
|
1688 |
+
array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
|
1689 |
+
dtype='|S5')
|
1690 |
+
|
1691 |
+
"""
|
1692 |
+
a_arr = numpy.asarray(a)
|
1693 |
+
return _vec_string(a_arr, a_arr.dtype, 'swapcase')
|
1694 |
+
|
1695 |
+
|
1696 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1697 |
+
def title(a):
|
1698 |
+
"""
|
1699 |
+
Return element-wise title cased version of string or unicode.
|
1700 |
+
|
1701 |
+
Title case words start with uppercase characters, all remaining cased
|
1702 |
+
characters are lowercase.
|
1703 |
+
|
1704 |
+
Calls `str.title` element-wise.
|
1705 |
+
|
1706 |
+
For 8-bit strings, this method is locale-dependent.
|
1707 |
+
|
1708 |
+
Parameters
|
1709 |
+
----------
|
1710 |
+
a : array_like, {str, unicode}
|
1711 |
+
Input array.
|
1712 |
+
|
1713 |
+
Returns
|
1714 |
+
-------
|
1715 |
+
out : ndarray
|
1716 |
+
Output array of str or unicode, depending on input type
|
1717 |
+
|
1718 |
+
See Also
|
1719 |
+
--------
|
1720 |
+
str.title
|
1721 |
+
|
1722 |
+
Examples
|
1723 |
+
--------
|
1724 |
+
>>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
|
1725 |
+
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
|
1726 |
+
dtype='|S5')
|
1727 |
+
>>> np.char.title(c)
|
1728 |
+
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
|
1729 |
+
dtype='|S5')
|
1730 |
+
|
1731 |
+
"""
|
1732 |
+
a_arr = numpy.asarray(a)
|
1733 |
+
return _vec_string(a_arr, a_arr.dtype, 'title')
|
1734 |
+
|
1735 |
+
|
1736 |
+
def _translate_dispatcher(a, table, deletechars=None):
|
1737 |
+
return (a,)
|
1738 |
+
|
1739 |
+
|
1740 |
+
@array_function_dispatch(_translate_dispatcher)
|
1741 |
+
def translate(a, table, deletechars=None):
|
1742 |
+
"""
|
1743 |
+
For each element in `a`, return a copy of the string where all
|
1744 |
+
characters occurring in the optional argument `deletechars` are
|
1745 |
+
removed, and the remaining characters have been mapped through the
|
1746 |
+
given translation table.
|
1747 |
+
|
1748 |
+
Calls `str.translate` element-wise.
|
1749 |
+
|
1750 |
+
Parameters
|
1751 |
+
----------
|
1752 |
+
a : array-like of str or unicode
|
1753 |
+
|
1754 |
+
table : str of length 256
|
1755 |
+
|
1756 |
+
deletechars : str
|
1757 |
+
|
1758 |
+
Returns
|
1759 |
+
-------
|
1760 |
+
out : ndarray
|
1761 |
+
Output array of str or unicode, depending on input type
|
1762 |
+
|
1763 |
+
See Also
|
1764 |
+
--------
|
1765 |
+
str.translate
|
1766 |
+
|
1767 |
+
"""
|
1768 |
+
a_arr = numpy.asarray(a)
|
1769 |
+
if issubclass(a_arr.dtype.type, str_):
|
1770 |
+
return _vec_string(
|
1771 |
+
a_arr, a_arr.dtype, 'translate', (table,))
|
1772 |
+
else:
|
1773 |
+
return _vec_string(
|
1774 |
+
a_arr, a_arr.dtype, 'translate', [table] + _clean_args(deletechars))
|
1775 |
+
|
1776 |
+
|
1777 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1778 |
+
def upper(a):
|
1779 |
+
"""
|
1780 |
+
Return an array with the elements converted to uppercase.
|
1781 |
+
|
1782 |
+
Calls `str.upper` element-wise.
|
1783 |
+
|
1784 |
+
For 8-bit strings, this method is locale-dependent.
|
1785 |
+
|
1786 |
+
Parameters
|
1787 |
+
----------
|
1788 |
+
a : array_like, {str, unicode}
|
1789 |
+
Input array.
|
1790 |
+
|
1791 |
+
Returns
|
1792 |
+
-------
|
1793 |
+
out : ndarray, {str, unicode}
|
1794 |
+
Output array of str or unicode, depending on input type
|
1795 |
+
|
1796 |
+
See Also
|
1797 |
+
--------
|
1798 |
+
str.upper
|
1799 |
+
|
1800 |
+
Examples
|
1801 |
+
--------
|
1802 |
+
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
|
1803 |
+
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
|
1804 |
+
>>> np.char.upper(c)
|
1805 |
+
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
|
1806 |
+
|
1807 |
+
"""
|
1808 |
+
a_arr = numpy.asarray(a)
|
1809 |
+
return _vec_string(a_arr, a_arr.dtype, 'upper')
|
1810 |
+
|
1811 |
+
|
1812 |
+
def _zfill_dispatcher(a, width):
|
1813 |
+
return (a,)
|
1814 |
+
|
1815 |
+
|
1816 |
+
@array_function_dispatch(_zfill_dispatcher)
|
1817 |
+
def zfill(a, width):
|
1818 |
+
"""
|
1819 |
+
Return the numeric string left-filled with zeros
|
1820 |
+
|
1821 |
+
Calls `str.zfill` element-wise.
|
1822 |
+
|
1823 |
+
Parameters
|
1824 |
+
----------
|
1825 |
+
a : array_like, {str, unicode}
|
1826 |
+
Input array.
|
1827 |
+
width : int
|
1828 |
+
Width of string to left-fill elements in `a`.
|
1829 |
+
|
1830 |
+
Returns
|
1831 |
+
-------
|
1832 |
+
out : ndarray, {str, unicode}
|
1833 |
+
Output array of str or unicode, depending on input type
|
1834 |
+
|
1835 |
+
See Also
|
1836 |
+
--------
|
1837 |
+
str.zfill
|
1838 |
+
|
1839 |
+
"""
|
1840 |
+
a_arr = numpy.asarray(a)
|
1841 |
+
width_arr = numpy.asarray(width)
|
1842 |
+
size = int(numpy.max(width_arr.flat))
|
1843 |
+
return _vec_string(
|
1844 |
+
a_arr, type(a_arr.dtype)(size), 'zfill', (width_arr,))
|
1845 |
+
|
1846 |
+
|
1847 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1848 |
+
def isnumeric(a):
|
1849 |
+
"""
|
1850 |
+
For each element, return True if there are only numeric
|
1851 |
+
characters in the element.
|
1852 |
+
|
1853 |
+
Calls `str.isnumeric` element-wise.
|
1854 |
+
|
1855 |
+
Numeric characters include digit characters, and all characters
|
1856 |
+
that have the Unicode numeric value property, e.g. ``U+2155,
|
1857 |
+
VULGAR FRACTION ONE FIFTH``.
|
1858 |
+
|
1859 |
+
Parameters
|
1860 |
+
----------
|
1861 |
+
a : array_like, unicode
|
1862 |
+
Input array.
|
1863 |
+
|
1864 |
+
Returns
|
1865 |
+
-------
|
1866 |
+
out : ndarray, bool
|
1867 |
+
Array of booleans of same shape as `a`.
|
1868 |
+
|
1869 |
+
See Also
|
1870 |
+
--------
|
1871 |
+
str.isnumeric
|
1872 |
+
|
1873 |
+
Examples
|
1874 |
+
--------
|
1875 |
+
>>> np.char.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])
|
1876 |
+
array([ True, False, False, False, False])
|
1877 |
+
|
1878 |
+
"""
|
1879 |
+
if not _is_unicode(a):
|
1880 |
+
raise TypeError("isnumeric is only available for Unicode strings and arrays")
|
1881 |
+
return _vec_string(a, bool_, 'isnumeric')
|
1882 |
+
|
1883 |
+
|
1884 |
+
@array_function_dispatch(_unary_op_dispatcher)
|
1885 |
+
def isdecimal(a):
|
1886 |
+
"""
|
1887 |
+
For each element, return True if there are only decimal
|
1888 |
+
characters in the element.
|
1889 |
+
|
1890 |
+
Calls `str.isdecimal` element-wise.
|
1891 |
+
|
1892 |
+
Decimal characters include digit characters, and all characters
|
1893 |
+
that can be used to form decimal-radix numbers,
|
1894 |
+
e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
|
1895 |
+
|
1896 |
+
Parameters
|
1897 |
+
----------
|
1898 |
+
a : array_like, unicode
|
1899 |
+
Input array.
|
1900 |
+
|
1901 |
+
Returns
|
1902 |
+
-------
|
1903 |
+
out : ndarray, bool
|
1904 |
+
Array of booleans identical in shape to `a`.
|
1905 |
+
|
1906 |
+
See Also
|
1907 |
+
--------
|
1908 |
+
str.isdecimal
|
1909 |
+
|
1910 |
+
Examples
|
1911 |
+
--------
|
1912 |
+
>>> np.char.isdecimal(['12345', '4.99', '123ABC', ''])
|
1913 |
+
array([ True, False, False, False])
|
1914 |
+
|
1915 |
+
"""
|
1916 |
+
if not _is_unicode(a):
|
1917 |
+
raise TypeError(
|
1918 |
+
"isdecimal is only available for Unicode strings and arrays")
|
1919 |
+
return _vec_string(a, bool_, 'isdecimal')
|
1920 |
+
|
1921 |
+
|
1922 |
+
@set_module('numpy')
|
1923 |
+
class chararray(ndarray):
|
1924 |
+
"""
|
1925 |
+
chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
|
1926 |
+
strides=None, order=None)
|
1927 |
+
|
1928 |
+
Provides a convenient view on arrays of string and unicode values.
|
1929 |
+
|
1930 |
+
.. note::
|
1931 |
+
The `chararray` class exists for backwards compatibility with
|
1932 |
+
Numarray, it is not recommended for new development. Starting from numpy
|
1933 |
+
1.4, if one needs arrays of strings, it is recommended to use arrays of
|
1934 |
+
`dtype` `object_`, `bytes_` or `str_`, and use the free functions
|
1935 |
+
in the `numpy.char` module for fast vectorized string operations.
|
1936 |
+
|
1937 |
+
Versus a regular NumPy array of type `str` or `unicode`, this
|
1938 |
+
class adds the following functionality:
|
1939 |
+
|
1940 |
+
1) values automatically have whitespace removed from the end
|
1941 |
+
when indexed
|
1942 |
+
|
1943 |
+
2) comparison operators automatically remove whitespace from the
|
1944 |
+
end when comparing values
|
1945 |
+
|
1946 |
+
3) vectorized string operations are provided as methods
|
1947 |
+
(e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
|
1948 |
+
|
1949 |
+
chararrays should be created using `numpy.char.array` or
|
1950 |
+
`numpy.char.asarray`, rather than this constructor directly.
|
1951 |
+
|
1952 |
+
This constructor creates the array, using `buffer` (with `offset`
|
1953 |
+
and `strides`) if it is not ``None``. If `buffer` is ``None``, then
|
1954 |
+
constructs a new array with `strides` in "C order", unless both
|
1955 |
+
``len(shape) >= 2`` and ``order='F'``, in which case `strides`
|
1956 |
+
is in "Fortran order".
|
1957 |
+
|
1958 |
+
Methods
|
1959 |
+
-------
|
1960 |
+
astype
|
1961 |
+
argsort
|
1962 |
+
copy
|
1963 |
+
count
|
1964 |
+
decode
|
1965 |
+
dump
|
1966 |
+
dumps
|
1967 |
+
encode
|
1968 |
+
endswith
|
1969 |
+
expandtabs
|
1970 |
+
fill
|
1971 |
+
find
|
1972 |
+
flatten
|
1973 |
+
getfield
|
1974 |
+
index
|
1975 |
+
isalnum
|
1976 |
+
isalpha
|
1977 |
+
isdecimal
|
1978 |
+
isdigit
|
1979 |
+
islower
|
1980 |
+
isnumeric
|
1981 |
+
isspace
|
1982 |
+
istitle
|
1983 |
+
isupper
|
1984 |
+
item
|
1985 |
+
join
|
1986 |
+
ljust
|
1987 |
+
lower
|
1988 |
+
lstrip
|
1989 |
+
nonzero
|
1990 |
+
put
|
1991 |
+
ravel
|
1992 |
+
repeat
|
1993 |
+
replace
|
1994 |
+
reshape
|
1995 |
+
resize
|
1996 |
+
rfind
|
1997 |
+
rindex
|
1998 |
+
rjust
|
1999 |
+
rsplit
|
2000 |
+
rstrip
|
2001 |
+
searchsorted
|
2002 |
+
setfield
|
2003 |
+
setflags
|
2004 |
+
sort
|
2005 |
+
split
|
2006 |
+
splitlines
|
2007 |
+
squeeze
|
2008 |
+
startswith
|
2009 |
+
strip
|
2010 |
+
swapaxes
|
2011 |
+
swapcase
|
2012 |
+
take
|
2013 |
+
title
|
2014 |
+
tofile
|
2015 |
+
tolist
|
2016 |
+
tostring
|
2017 |
+
translate
|
2018 |
+
transpose
|
2019 |
+
upper
|
2020 |
+
view
|
2021 |
+
zfill
|
2022 |
+
|
2023 |
+
Parameters
|
2024 |
+
----------
|
2025 |
+
shape : tuple
|
2026 |
+
Shape of the array.
|
2027 |
+
itemsize : int, optional
|
2028 |
+
Length of each array element, in number of characters. Default is 1.
|
2029 |
+
unicode : bool, optional
|
2030 |
+
Are the array elements of type unicode (True) or string (False).
|
2031 |
+
Default is False.
|
2032 |
+
buffer : object exposing the buffer interface or str, optional
|
2033 |
+
Memory address of the start of the array data. Default is None,
|
2034 |
+
in which case a new array is created.
|
2035 |
+
offset : int, optional
|
2036 |
+
Fixed stride displacement from the beginning of an axis?
|
2037 |
+
Default is 0. Needs to be >=0.
|
2038 |
+
strides : array_like of ints, optional
|
2039 |
+
Strides for the array (see `ndarray.strides` for full description).
|
2040 |
+
Default is None.
|
2041 |
+
order : {'C', 'F'}, optional
|
2042 |
+
The order in which the array data is stored in memory: 'C' ->
|
2043 |
+
"row major" order (the default), 'F' -> "column major"
|
2044 |
+
(Fortran) order.
|
2045 |
+
|
2046 |
+
Examples
|
2047 |
+
--------
|
2048 |
+
>>> charar = np.chararray((3, 3))
|
2049 |
+
>>> charar[:] = 'a'
|
2050 |
+
>>> charar
|
2051 |
+
chararray([[b'a', b'a', b'a'],
|
2052 |
+
[b'a', b'a', b'a'],
|
2053 |
+
[b'a', b'a', b'a']], dtype='|S1')
|
2054 |
+
|
2055 |
+
>>> charar = np.chararray(charar.shape, itemsize=5)
|
2056 |
+
>>> charar[:] = 'abc'
|
2057 |
+
>>> charar
|
2058 |
+
chararray([[b'abc', b'abc', b'abc'],
|
2059 |
+
[b'abc', b'abc', b'abc'],
|
2060 |
+
[b'abc', b'abc', b'abc']], dtype='|S5')
|
2061 |
+
|
2062 |
+
"""
|
2063 |
+
def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
|
2064 |
+
offset=0, strides=None, order='C'):
|
2065 |
+
global _globalvar
|
2066 |
+
|
2067 |
+
if unicode:
|
2068 |
+
dtype = str_
|
2069 |
+
else:
|
2070 |
+
dtype = bytes_
|
2071 |
+
|
2072 |
+
# force itemsize to be a Python int, since using NumPy integer
|
2073 |
+
# types results in itemsize.itemsize being used as the size of
|
2074 |
+
# strings in the new array.
|
2075 |
+
itemsize = int(itemsize)
|
2076 |
+
|
2077 |
+
if isinstance(buffer, str):
|
2078 |
+
# unicode objects do not have the buffer interface
|
2079 |
+
filler = buffer
|
2080 |
+
buffer = None
|
2081 |
+
else:
|
2082 |
+
filler = None
|
2083 |
+
|
2084 |
+
_globalvar = 1
|
2085 |
+
if buffer is None:
|
2086 |
+
self = ndarray.__new__(subtype, shape, (dtype, itemsize),
|
2087 |
+
order=order)
|
2088 |
+
else:
|
2089 |
+
self = ndarray.__new__(subtype, shape, (dtype, itemsize),
|
2090 |
+
buffer=buffer,
|
2091 |
+
offset=offset, strides=strides,
|
2092 |
+
order=order)
|
2093 |
+
if filler is not None:
|
2094 |
+
self[...] = filler
|
2095 |
+
_globalvar = 0
|
2096 |
+
return self
|
2097 |
+
|
2098 |
+
def __array_finalize__(self, obj):
|
2099 |
+
# The b is a special case because it is used for reconstructing.
|
2100 |
+
if not _globalvar and self.dtype.char not in 'SUbc':
|
2101 |
+
raise ValueError("Can only create a chararray from string data.")
|
2102 |
+
|
2103 |
+
def __getitem__(self, obj):
|
2104 |
+
val = ndarray.__getitem__(self, obj)
|
2105 |
+
|
2106 |
+
if isinstance(val, character):
|
2107 |
+
temp = val.rstrip()
|
2108 |
+
if len(temp) == 0:
|
2109 |
+
val = ''
|
2110 |
+
else:
|
2111 |
+
val = temp
|
2112 |
+
|
2113 |
+
return val
|
2114 |
+
|
2115 |
+
# IMPLEMENTATION NOTE: Most of the methods of this class are
|
2116 |
+
# direct delegations to the free functions in this module.
|
2117 |
+
# However, those that return an array of strings should instead
|
2118 |
+
# return a chararray, so some extra wrapping is required.
|
2119 |
+
|
2120 |
+
def __eq__(self, other):
|
2121 |
+
"""
|
2122 |
+
Return (self == other) element-wise.
|
2123 |
+
|
2124 |
+
See Also
|
2125 |
+
--------
|
2126 |
+
equal
|
2127 |
+
"""
|
2128 |
+
return equal(self, other)
|
2129 |
+
|
2130 |
+
def __ne__(self, other):
|
2131 |
+
"""
|
2132 |
+
Return (self != other) element-wise.
|
2133 |
+
|
2134 |
+
See Also
|
2135 |
+
--------
|
2136 |
+
not_equal
|
2137 |
+
"""
|
2138 |
+
return not_equal(self, other)
|
2139 |
+
|
2140 |
+
def __ge__(self, other):
|
2141 |
+
"""
|
2142 |
+
Return (self >= other) element-wise.
|
2143 |
+
|
2144 |
+
See Also
|
2145 |
+
--------
|
2146 |
+
greater_equal
|
2147 |
+
"""
|
2148 |
+
return greater_equal(self, other)
|
2149 |
+
|
2150 |
+
def __le__(self, other):
|
2151 |
+
"""
|
2152 |
+
Return (self <= other) element-wise.
|
2153 |
+
|
2154 |
+
See Also
|
2155 |
+
--------
|
2156 |
+
less_equal
|
2157 |
+
"""
|
2158 |
+
return less_equal(self, other)
|
2159 |
+
|
2160 |
+
def __gt__(self, other):
|
2161 |
+
"""
|
2162 |
+
Return (self > other) element-wise.
|
2163 |
+
|
2164 |
+
See Also
|
2165 |
+
--------
|
2166 |
+
greater
|
2167 |
+
"""
|
2168 |
+
return greater(self, other)
|
2169 |
+
|
2170 |
+
def __lt__(self, other):
|
2171 |
+
"""
|
2172 |
+
Return (self < other) element-wise.
|
2173 |
+
|
2174 |
+
See Also
|
2175 |
+
--------
|
2176 |
+
less
|
2177 |
+
"""
|
2178 |
+
return less(self, other)
|
2179 |
+
|
2180 |
+
def __add__(self, other):
|
2181 |
+
"""
|
2182 |
+
Return (self + other), that is string concatenation,
|
2183 |
+
element-wise for a pair of array_likes of str or unicode.
|
2184 |
+
|
2185 |
+
See Also
|
2186 |
+
--------
|
2187 |
+
add
|
2188 |
+
"""
|
2189 |
+
return asarray(add(self, other))
|
2190 |
+
|
2191 |
+
def __radd__(self, other):
|
2192 |
+
"""
|
2193 |
+
Return (other + self), that is string concatenation,
|
2194 |
+
element-wise for a pair of array_likes of `bytes_` or `str_`.
|
2195 |
+
|
2196 |
+
See Also
|
2197 |
+
--------
|
2198 |
+
add
|
2199 |
+
"""
|
2200 |
+
return asarray(add(numpy.asarray(other), self))
|
2201 |
+
|
2202 |
+
def __mul__(self, i):
|
2203 |
+
"""
|
2204 |
+
Return (self * i), that is string multiple concatenation,
|
2205 |
+
element-wise.
|
2206 |
+
|
2207 |
+
See Also
|
2208 |
+
--------
|
2209 |
+
multiply
|
2210 |
+
"""
|
2211 |
+
return asarray(multiply(self, i))
|
2212 |
+
|
2213 |
+
def __rmul__(self, i):
|
2214 |
+
"""
|
2215 |
+
Return (self * i), that is string multiple concatenation,
|
2216 |
+
element-wise.
|
2217 |
+
|
2218 |
+
See Also
|
2219 |
+
--------
|
2220 |
+
multiply
|
2221 |
+
"""
|
2222 |
+
return asarray(multiply(self, i))
|
2223 |
+
|
2224 |
+
def __mod__(self, i):
|
2225 |
+
"""
|
2226 |
+
Return (self % i), that is pre-Python 2.6 string formatting
|
2227 |
+
(interpolation), element-wise for a pair of array_likes of `bytes_`
|
2228 |
+
or `str_`.
|
2229 |
+
|
2230 |
+
See Also
|
2231 |
+
--------
|
2232 |
+
mod
|
2233 |
+
"""
|
2234 |
+
return asarray(mod(self, i))
|
2235 |
+
|
2236 |
+
def __rmod__(self, other):
|
2237 |
+
return NotImplemented
|
2238 |
+
|
2239 |
+
def argsort(self, axis=-1, kind=None, order=None):
|
2240 |
+
"""
|
2241 |
+
Return the indices that sort the array lexicographically.
|
2242 |
+
|
2243 |
+
For full documentation see `numpy.argsort`, for which this method is
|
2244 |
+
in fact merely a "thin wrapper."
|
2245 |
+
|
2246 |
+
Examples
|
2247 |
+
--------
|
2248 |
+
>>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
|
2249 |
+
>>> c = c.view(np.chararray); c
|
2250 |
+
chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
|
2251 |
+
dtype='|S5')
|
2252 |
+
>>> c[c.argsort()]
|
2253 |
+
chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
|
2254 |
+
dtype='|S5')
|
2255 |
+
|
2256 |
+
"""
|
2257 |
+
return self.__array__().argsort(axis, kind, order)
|
2258 |
+
argsort.__doc__ = ndarray.argsort.__doc__
|
2259 |
+
|
2260 |
+
def capitalize(self):
|
2261 |
+
"""
|
2262 |
+
Return a copy of `self` with only the first character of each element
|
2263 |
+
capitalized.
|
2264 |
+
|
2265 |
+
See Also
|
2266 |
+
--------
|
2267 |
+
char.capitalize
|
2268 |
+
|
2269 |
+
"""
|
2270 |
+
return asarray(capitalize(self))
|
2271 |
+
|
2272 |
+
def center(self, width, fillchar=' '):
|
2273 |
+
"""
|
2274 |
+
Return a copy of `self` with its elements centered in a
|
2275 |
+
string of length `width`.
|
2276 |
+
|
2277 |
+
See Also
|
2278 |
+
--------
|
2279 |
+
center
|
2280 |
+
"""
|
2281 |
+
return asarray(center(self, width, fillchar))
|
2282 |
+
|
2283 |
+
def count(self, sub, start=0, end=None):
|
2284 |
+
"""
|
2285 |
+
Returns an array with the number of non-overlapping occurrences of
|
2286 |
+
substring `sub` in the range [`start`, `end`].
|
2287 |
+
|
2288 |
+
See Also
|
2289 |
+
--------
|
2290 |
+
char.count
|
2291 |
+
|
2292 |
+
"""
|
2293 |
+
return count(self, sub, start, end)
|
2294 |
+
|
2295 |
+
def decode(self, encoding=None, errors=None):
|
2296 |
+
"""
|
2297 |
+
Calls ``bytes.decode`` element-wise.
|
2298 |
+
|
2299 |
+
See Also
|
2300 |
+
--------
|
2301 |
+
char.decode
|
2302 |
+
|
2303 |
+
"""
|
2304 |
+
return decode(self, encoding, errors)
|
2305 |
+
|
2306 |
+
def encode(self, encoding=None, errors=None):
|
2307 |
+
"""
|
2308 |
+
Calls `str.encode` element-wise.
|
2309 |
+
|
2310 |
+
See Also
|
2311 |
+
--------
|
2312 |
+
char.encode
|
2313 |
+
|
2314 |
+
"""
|
2315 |
+
return encode(self, encoding, errors)
|
2316 |
+
|
2317 |
+
def endswith(self, suffix, start=0, end=None):
|
2318 |
+
"""
|
2319 |
+
Returns a boolean array which is `True` where the string element
|
2320 |
+
in `self` ends with `suffix`, otherwise `False`.
|
2321 |
+
|
2322 |
+
See Also
|
2323 |
+
--------
|
2324 |
+
char.endswith
|
2325 |
+
|
2326 |
+
"""
|
2327 |
+
return endswith(self, suffix, start, end)
|
2328 |
+
|
2329 |
+
def expandtabs(self, tabsize=8):
|
2330 |
+
"""
|
2331 |
+
Return a copy of each string element where all tab characters are
|
2332 |
+
replaced by one or more spaces.
|
2333 |
+
|
2334 |
+
See Also
|
2335 |
+
--------
|
2336 |
+
char.expandtabs
|
2337 |
+
|
2338 |
+
"""
|
2339 |
+
return asarray(expandtabs(self, tabsize))
|
2340 |
+
|
2341 |
+
def find(self, sub, start=0, end=None):
|
2342 |
+
"""
|
2343 |
+
For each element, return the lowest index in the string where
|
2344 |
+
substring `sub` is found.
|
2345 |
+
|
2346 |
+
See Also
|
2347 |
+
--------
|
2348 |
+
char.find
|
2349 |
+
|
2350 |
+
"""
|
2351 |
+
return find(self, sub, start, end)
|
2352 |
+
|
2353 |
+
def index(self, sub, start=0, end=None):
|
2354 |
+
"""
|
2355 |
+
Like `find`, but raises `ValueError` when the substring is not found.
|
2356 |
+
|
2357 |
+
See Also
|
2358 |
+
--------
|
2359 |
+
char.index
|
2360 |
+
|
2361 |
+
"""
|
2362 |
+
return index(self, sub, start, end)
|
2363 |
+
|
2364 |
+
def isalnum(self):
|
2365 |
+
"""
|
2366 |
+
Returns true for each element if all characters in the string
|
2367 |
+
are alphanumeric and there is at least one character, false
|
2368 |
+
otherwise.
|
2369 |
+
|
2370 |
+
See Also
|
2371 |
+
--------
|
2372 |
+
char.isalnum
|
2373 |
+
|
2374 |
+
"""
|
2375 |
+
return isalnum(self)
|
2376 |
+
|
2377 |
+
def isalpha(self):
|
2378 |
+
"""
|
2379 |
+
Returns true for each element if all characters in the string
|
2380 |
+
are alphabetic and there is at least one character, false
|
2381 |
+
otherwise.
|
2382 |
+
|
2383 |
+
See Also
|
2384 |
+
--------
|
2385 |
+
char.isalpha
|
2386 |
+
|
2387 |
+
"""
|
2388 |
+
return isalpha(self)
|
2389 |
+
|
2390 |
+
def isdigit(self):
|
2391 |
+
"""
|
2392 |
+
Returns true for each element if all characters in the string are
|
2393 |
+
digits and there is at least one character, false otherwise.
|
2394 |
+
|
2395 |
+
See Also
|
2396 |
+
--------
|
2397 |
+
char.isdigit
|
2398 |
+
|
2399 |
+
"""
|
2400 |
+
return isdigit(self)
|
2401 |
+
|
2402 |
+
def islower(self):
|
2403 |
+
"""
|
2404 |
+
Returns true for each element if all cased characters in the
|
2405 |
+
string are lowercase and there is at least one cased character,
|
2406 |
+
false otherwise.
|
2407 |
+
|
2408 |
+
See Also
|
2409 |
+
--------
|
2410 |
+
char.islower
|
2411 |
+
|
2412 |
+
"""
|
2413 |
+
return islower(self)
|
2414 |
+
|
2415 |
+
def isspace(self):
|
2416 |
+
"""
|
2417 |
+
Returns true for each element if there are only whitespace
|
2418 |
+
characters in the string and there is at least one character,
|
2419 |
+
false otherwise.
|
2420 |
+
|
2421 |
+
See Also
|
2422 |
+
--------
|
2423 |
+
char.isspace
|
2424 |
+
|
2425 |
+
"""
|
2426 |
+
return isspace(self)
|
2427 |
+
|
2428 |
+
def istitle(self):
|
2429 |
+
"""
|
2430 |
+
Returns true for each element if the element is a titlecased
|
2431 |
+
string and there is at least one character, false otherwise.
|
2432 |
+
|
2433 |
+
See Also
|
2434 |
+
--------
|
2435 |
+
char.istitle
|
2436 |
+
|
2437 |
+
"""
|
2438 |
+
return istitle(self)
|
2439 |
+
|
2440 |
+
def isupper(self):
|
2441 |
+
"""
|
2442 |
+
Returns true for each element if all cased characters in the
|
2443 |
+
string are uppercase and there is at least one character, false
|
2444 |
+
otherwise.
|
2445 |
+
|
2446 |
+
See Also
|
2447 |
+
--------
|
2448 |
+
char.isupper
|
2449 |
+
|
2450 |
+
"""
|
2451 |
+
return isupper(self)
|
2452 |
+
|
2453 |
+
def join(self, seq):
|
2454 |
+
"""
|
2455 |
+
Return a string which is the concatenation of the strings in the
|
2456 |
+
sequence `seq`.
|
2457 |
+
|
2458 |
+
See Also
|
2459 |
+
--------
|
2460 |
+
char.join
|
2461 |
+
|
2462 |
+
"""
|
2463 |
+
return join(self, seq)
|
2464 |
+
|
2465 |
+
def ljust(self, width, fillchar=' '):
|
2466 |
+
"""
|
2467 |
+
Return an array with the elements of `self` left-justified in a
|
2468 |
+
string of length `width`.
|
2469 |
+
|
2470 |
+
See Also
|
2471 |
+
--------
|
2472 |
+
char.ljust
|
2473 |
+
|
2474 |
+
"""
|
2475 |
+
return asarray(ljust(self, width, fillchar))
|
2476 |
+
|
2477 |
+
def lower(self):
|
2478 |
+
"""
|
2479 |
+
Return an array with the elements of `self` converted to
|
2480 |
+
lowercase.
|
2481 |
+
|
2482 |
+
See Also
|
2483 |
+
--------
|
2484 |
+
char.lower
|
2485 |
+
|
2486 |
+
"""
|
2487 |
+
return asarray(lower(self))
|
2488 |
+
|
2489 |
+
def lstrip(self, chars=None):
|
2490 |
+
"""
|
2491 |
+
For each element in `self`, return a copy with the leading characters
|
2492 |
+
removed.
|
2493 |
+
|
2494 |
+
See Also
|
2495 |
+
--------
|
2496 |
+
char.lstrip
|
2497 |
+
|
2498 |
+
"""
|
2499 |
+
return asarray(lstrip(self, chars))
|
2500 |
+
|
2501 |
+
def partition(self, sep):
|
2502 |
+
"""
|
2503 |
+
Partition each element in `self` around `sep`.
|
2504 |
+
|
2505 |
+
See Also
|
2506 |
+
--------
|
2507 |
+
partition
|
2508 |
+
"""
|
2509 |
+
return asarray(partition(self, sep))
|
2510 |
+
|
2511 |
+
def replace(self, old, new, count=None):
|
2512 |
+
"""
|
2513 |
+
For each element in `self`, return a copy of the string with all
|
2514 |
+
occurrences of substring `old` replaced by `new`.
|
2515 |
+
|
2516 |
+
See Also
|
2517 |
+
--------
|
2518 |
+
char.replace
|
2519 |
+
|
2520 |
+
"""
|
2521 |
+
return asarray(replace(self, old, new, count))
|
2522 |
+
|
2523 |
+
def rfind(self, sub, start=0, end=None):
|
2524 |
+
"""
|
2525 |
+
For each element in `self`, return the highest index in the string
|
2526 |
+
where substring `sub` is found, such that `sub` is contained
|
2527 |
+
within [`start`, `end`].
|
2528 |
+
|
2529 |
+
See Also
|
2530 |
+
--------
|
2531 |
+
char.rfind
|
2532 |
+
|
2533 |
+
"""
|
2534 |
+
return rfind(self, sub, start, end)
|
2535 |
+
|
2536 |
+
def rindex(self, sub, start=0, end=None):
|
2537 |
+
"""
|
2538 |
+
Like `rfind`, but raises `ValueError` when the substring `sub` is
|
2539 |
+
not found.
|
2540 |
+
|
2541 |
+
See Also
|
2542 |
+
--------
|
2543 |
+
char.rindex
|
2544 |
+
|
2545 |
+
"""
|
2546 |
+
return rindex(self, sub, start, end)
|
2547 |
+
|
2548 |
+
def rjust(self, width, fillchar=' '):
|
2549 |
+
"""
|
2550 |
+
Return an array with the elements of `self`
|
2551 |
+
right-justified in a string of length `width`.
|
2552 |
+
|
2553 |
+
See Also
|
2554 |
+
--------
|
2555 |
+
char.rjust
|
2556 |
+
|
2557 |
+
"""
|
2558 |
+
return asarray(rjust(self, width, fillchar))
|
2559 |
+
|
2560 |
+
def rpartition(self, sep):
|
2561 |
+
"""
|
2562 |
+
Partition each element in `self` around `sep`.
|
2563 |
+
|
2564 |
+
See Also
|
2565 |
+
--------
|
2566 |
+
rpartition
|
2567 |
+
"""
|
2568 |
+
return asarray(rpartition(self, sep))
|
2569 |
+
|
2570 |
+
def rsplit(self, sep=None, maxsplit=None):
|
2571 |
+
"""
|
2572 |
+
For each element in `self`, return a list of the words in
|
2573 |
+
the string, using `sep` as the delimiter string.
|
2574 |
+
|
2575 |
+
See Also
|
2576 |
+
--------
|
2577 |
+
char.rsplit
|
2578 |
+
|
2579 |
+
"""
|
2580 |
+
return rsplit(self, sep, maxsplit)
|
2581 |
+
|
2582 |
+
def rstrip(self, chars=None):
|
2583 |
+
"""
|
2584 |
+
For each element in `self`, return a copy with the trailing
|
2585 |
+
characters removed.
|
2586 |
+
|
2587 |
+
See Also
|
2588 |
+
--------
|
2589 |
+
char.rstrip
|
2590 |
+
|
2591 |
+
"""
|
2592 |
+
return asarray(rstrip(self, chars))
|
2593 |
+
|
2594 |
+
def split(self, sep=None, maxsplit=None):
|
2595 |
+
"""
|
2596 |
+
For each element in `self`, return a list of the words in the
|
2597 |
+
string, using `sep` as the delimiter string.
|
2598 |
+
|
2599 |
+
See Also
|
2600 |
+
--------
|
2601 |
+
char.split
|
2602 |
+
|
2603 |
+
"""
|
2604 |
+
return split(self, sep, maxsplit)
|
2605 |
+
|
2606 |
+
def splitlines(self, keepends=None):
|
2607 |
+
"""
|
2608 |
+
For each element in `self`, return a list of the lines in the
|
2609 |
+
element, breaking at line boundaries.
|
2610 |
+
|
2611 |
+
See Also
|
2612 |
+
--------
|
2613 |
+
char.splitlines
|
2614 |
+
|
2615 |
+
"""
|
2616 |
+
return splitlines(self, keepends)
|
2617 |
+
|
2618 |
+
def startswith(self, prefix, start=0, end=None):
|
2619 |
+
"""
|
2620 |
+
Returns a boolean array which is `True` where the string element
|
2621 |
+
in `self` starts with `prefix`, otherwise `False`.
|
2622 |
+
|
2623 |
+
See Also
|
2624 |
+
--------
|
2625 |
+
char.startswith
|
2626 |
+
|
2627 |
+
"""
|
2628 |
+
return startswith(self, prefix, start, end)
|
2629 |
+
|
2630 |
+
def strip(self, chars=None):
|
2631 |
+
"""
|
2632 |
+
For each element in `self`, return a copy with the leading and
|
2633 |
+
trailing characters removed.
|
2634 |
+
|
2635 |
+
See Also
|
2636 |
+
--------
|
2637 |
+
char.strip
|
2638 |
+
|
2639 |
+
"""
|
2640 |
+
return asarray(strip(self, chars))
|
2641 |
+
|
2642 |
+
def swapcase(self):
|
2643 |
+
"""
|
2644 |
+
For each element in `self`, return a copy of the string with
|
2645 |
+
uppercase characters converted to lowercase and vice versa.
|
2646 |
+
|
2647 |
+
See Also
|
2648 |
+
--------
|
2649 |
+
char.swapcase
|
2650 |
+
|
2651 |
+
"""
|
2652 |
+
return asarray(swapcase(self))
|
2653 |
+
|
2654 |
+
def title(self):
|
2655 |
+
"""
|
2656 |
+
For each element in `self`, return a titlecased version of the
|
2657 |
+
string: words start with uppercase characters, all remaining cased
|
2658 |
+
characters are lowercase.
|
2659 |
+
|
2660 |
+
See Also
|
2661 |
+
--------
|
2662 |
+
char.title
|
2663 |
+
|
2664 |
+
"""
|
2665 |
+
return asarray(title(self))
|
2666 |
+
|
2667 |
+
def translate(self, table, deletechars=None):
|
2668 |
+
"""
|
2669 |
+
For each element in `self`, return a copy of the string where
|
2670 |
+
all characters occurring in the optional argument
|
2671 |
+
`deletechars` are removed, and the remaining characters have
|
2672 |
+
been mapped through the given translation table.
|
2673 |
+
|
2674 |
+
See Also
|
2675 |
+
--------
|
2676 |
+
char.translate
|
2677 |
+
|
2678 |
+
"""
|
2679 |
+
return asarray(translate(self, table, deletechars))
|
2680 |
+
|
2681 |
+
def upper(self):
|
2682 |
+
"""
|
2683 |
+
Return an array with the elements of `self` converted to
|
2684 |
+
uppercase.
|
2685 |
+
|
2686 |
+
See Also
|
2687 |
+
--------
|
2688 |
+
char.upper
|
2689 |
+
|
2690 |
+
"""
|
2691 |
+
return asarray(upper(self))
|
2692 |
+
|
2693 |
+
def zfill(self, width):
|
2694 |
+
"""
|
2695 |
+
Return the numeric string left-filled with zeros in a string of
|
2696 |
+
length `width`.
|
2697 |
+
|
2698 |
+
See Also
|
2699 |
+
--------
|
2700 |
+
char.zfill
|
2701 |
+
|
2702 |
+
"""
|
2703 |
+
return asarray(zfill(self, width))
|
2704 |
+
|
2705 |
+
def isnumeric(self):
|
2706 |
+
"""
|
2707 |
+
For each element in `self`, return True if there are only
|
2708 |
+
numeric characters in the element.
|
2709 |
+
|
2710 |
+
See Also
|
2711 |
+
--------
|
2712 |
+
char.isnumeric
|
2713 |
+
|
2714 |
+
"""
|
2715 |
+
return isnumeric(self)
|
2716 |
+
|
2717 |
+
def isdecimal(self):
|
2718 |
+
"""
|
2719 |
+
For each element in `self`, return True if there are only
|
2720 |
+
decimal characters in the element.
|
2721 |
+
|
2722 |
+
See Also
|
2723 |
+
--------
|
2724 |
+
char.isdecimal
|
2725 |
+
|
2726 |
+
"""
|
2727 |
+
return isdecimal(self)
|
2728 |
+
|
2729 |
+
|
2730 |
+
@set_module("numpy.char")
|
2731 |
+
def array(obj, itemsize=None, copy=True, unicode=None, order=None):
|
2732 |
+
"""
|
2733 |
+
Create a `chararray`.
|
2734 |
+
|
2735 |
+
.. note::
|
2736 |
+
This class is provided for numarray backward-compatibility.
|
2737 |
+
New code (not concerned with numarray compatibility) should use
|
2738 |
+
arrays of type `bytes_` or `str_` and use the free functions
|
2739 |
+
in :mod:`numpy.char <numpy.core.defchararray>` for fast
|
2740 |
+
vectorized string operations instead.
|
2741 |
+
|
2742 |
+
Versus a regular NumPy array of type `str` or `unicode`, this
|
2743 |
+
class adds the following functionality:
|
2744 |
+
|
2745 |
+
1) values automatically have whitespace removed from the end
|
2746 |
+
when indexed
|
2747 |
+
|
2748 |
+
2) comparison operators automatically remove whitespace from the
|
2749 |
+
end when comparing values
|
2750 |
+
|
2751 |
+
3) vectorized string operations are provided as methods
|
2752 |
+
(e.g. `str.endswith`) and infix operators (e.g. ``+, *, %``)
|
2753 |
+
|
2754 |
+
Parameters
|
2755 |
+
----------
|
2756 |
+
obj : array of str or unicode-like
|
2757 |
+
|
2758 |
+
itemsize : int, optional
|
2759 |
+
`itemsize` is the number of characters per scalar in the
|
2760 |
+
resulting array. If `itemsize` is None, and `obj` is an
|
2761 |
+
object array or a Python list, the `itemsize` will be
|
2762 |
+
automatically determined. If `itemsize` is provided and `obj`
|
2763 |
+
is of type str or unicode, then the `obj` string will be
|
2764 |
+
chunked into `itemsize` pieces.
|
2765 |
+
|
2766 |
+
copy : bool, optional
|
2767 |
+
If true (default), then the object is copied. Otherwise, a copy
|
2768 |
+
will only be made if __array__ returns a copy, if obj is a
|
2769 |
+
nested sequence, or if a copy is needed to satisfy any of the other
|
2770 |
+
requirements (`itemsize`, unicode, `order`, etc.).
|
2771 |
+
|
2772 |
+
unicode : bool, optional
|
2773 |
+
When true, the resulting `chararray` can contain Unicode
|
2774 |
+
characters, when false only 8-bit characters. If unicode is
|
2775 |
+
None and `obj` is one of the following:
|
2776 |
+
|
2777 |
+
- a `chararray`,
|
2778 |
+
- an ndarray of type `str` or `unicode`
|
2779 |
+
- a Python str or unicode object,
|
2780 |
+
|
2781 |
+
then the unicode setting of the output array will be
|
2782 |
+
automatically determined.
|
2783 |
+
|
2784 |
+
order : {'C', 'F', 'A'}, optional
|
2785 |
+
Specify the order of the array. If order is 'C' (default), then the
|
2786 |
+
array will be in C-contiguous order (last-index varies the
|
2787 |
+
fastest). If order is 'F', then the returned array
|
2788 |
+
will be in Fortran-contiguous order (first-index varies the
|
2789 |
+
fastest). If order is 'A', then the returned array may
|
2790 |
+
be in any order (either C-, Fortran-contiguous, or even
|
2791 |
+
discontiguous).
|
2792 |
+
"""
|
2793 |
+
if isinstance(obj, (bytes, str)):
|
2794 |
+
if unicode is None:
|
2795 |
+
if isinstance(obj, str):
|
2796 |
+
unicode = True
|
2797 |
+
else:
|
2798 |
+
unicode = False
|
2799 |
+
|
2800 |
+
if itemsize is None:
|
2801 |
+
itemsize = len(obj)
|
2802 |
+
shape = len(obj) // itemsize
|
2803 |
+
|
2804 |
+
return chararray(shape, itemsize=itemsize, unicode=unicode,
|
2805 |
+
buffer=obj, order=order)
|
2806 |
+
|
2807 |
+
if isinstance(obj, (list, tuple)):
|
2808 |
+
obj = numpy.asarray(obj)
|
2809 |
+
|
2810 |
+
if isinstance(obj, ndarray) and issubclass(obj.dtype.type, character):
|
2811 |
+
# If we just have a vanilla chararray, create a chararray
|
2812 |
+
# view around it.
|
2813 |
+
if not isinstance(obj, chararray):
|
2814 |
+
obj = obj.view(chararray)
|
2815 |
+
|
2816 |
+
if itemsize is None:
|
2817 |
+
itemsize = obj.itemsize
|
2818 |
+
# itemsize is in 8-bit chars, so for Unicode, we need
|
2819 |
+
# to divide by the size of a single Unicode character,
|
2820 |
+
# which for NumPy is always 4
|
2821 |
+
if issubclass(obj.dtype.type, str_):
|
2822 |
+
itemsize //= 4
|
2823 |
+
|
2824 |
+
if unicode is None:
|
2825 |
+
if issubclass(obj.dtype.type, str_):
|
2826 |
+
unicode = True
|
2827 |
+
else:
|
2828 |
+
unicode = False
|
2829 |
+
|
2830 |
+
if unicode:
|
2831 |
+
dtype = str_
|
2832 |
+
else:
|
2833 |
+
dtype = bytes_
|
2834 |
+
|
2835 |
+
if order is not None:
|
2836 |
+
obj = numpy.asarray(obj, order=order)
|
2837 |
+
if (copy or
|
2838 |
+
(itemsize != obj.itemsize) or
|
2839 |
+
(not unicode and isinstance(obj, str_)) or
|
2840 |
+
(unicode and isinstance(obj, bytes_))):
|
2841 |
+
obj = obj.astype((dtype, int(itemsize)))
|
2842 |
+
return obj
|
2843 |
+
|
2844 |
+
if isinstance(obj, ndarray) and issubclass(obj.dtype.type, object):
|
2845 |
+
if itemsize is None:
|
2846 |
+
# Since no itemsize was specified, convert the input array to
|
2847 |
+
# a list so the ndarray constructor will automatically
|
2848 |
+
# determine the itemsize for us.
|
2849 |
+
obj = obj.tolist()
|
2850 |
+
# Fall through to the default case
|
2851 |
+
|
2852 |
+
if unicode:
|
2853 |
+
dtype = str_
|
2854 |
+
else:
|
2855 |
+
dtype = bytes_
|
2856 |
+
|
2857 |
+
if itemsize is None:
|
2858 |
+
val = narray(obj, dtype=dtype, order=order, subok=True)
|
2859 |
+
else:
|
2860 |
+
val = narray(obj, dtype=(dtype, itemsize), order=order, subok=True)
|
2861 |
+
return val.view(chararray)
|
2862 |
+
|
2863 |
+
|
2864 |
+
@set_module("numpy.char")
|
2865 |
+
def asarray(obj, itemsize=None, unicode=None, order=None):
|
2866 |
+
"""
|
2867 |
+
Convert the input to a `chararray`, copying the data only if
|
2868 |
+
necessary.
|
2869 |
+
|
2870 |
+
Versus a regular NumPy array of type `str` or `unicode`, this
|
2871 |
+
class adds the following functionality:
|
2872 |
+
|
2873 |
+
1) values automatically have whitespace removed from the end
|
2874 |
+
when indexed
|
2875 |
+
|
2876 |
+
2) comparison operators automatically remove whitespace from the
|
2877 |
+
end when comparing values
|
2878 |
+
|
2879 |
+
3) vectorized string operations are provided as methods
|
2880 |
+
(e.g. `str.endswith`) and infix operators (e.g. ``+``, ``*``,``%``)
|
2881 |
+
|
2882 |
+
Parameters
|
2883 |
+
----------
|
2884 |
+
obj : array of str or unicode-like
|
2885 |
+
|
2886 |
+
itemsize : int, optional
|
2887 |
+
`itemsize` is the number of characters per scalar in the
|
2888 |
+
resulting array. If `itemsize` is None, and `obj` is an
|
2889 |
+
object array or a Python list, the `itemsize` will be
|
2890 |
+
automatically determined. If `itemsize` is provided and `obj`
|
2891 |
+
is of type str or unicode, then the `obj` string will be
|
2892 |
+
chunked into `itemsize` pieces.
|
2893 |
+
|
2894 |
+
unicode : bool, optional
|
2895 |
+
When true, the resulting `chararray` can contain Unicode
|
2896 |
+
characters, when false only 8-bit characters. If unicode is
|
2897 |
+
None and `obj` is one of the following:
|
2898 |
+
|
2899 |
+
- a `chararray`,
|
2900 |
+
- an ndarray of type `str` or 'unicode`
|
2901 |
+
- a Python str or unicode object,
|
2902 |
+
|
2903 |
+
then the unicode setting of the output array will be
|
2904 |
+
automatically determined.
|
2905 |
+
|
2906 |
+
order : {'C', 'F'}, optional
|
2907 |
+
Specify the order of the array. If order is 'C' (default), then the
|
2908 |
+
array will be in C-contiguous order (last-index varies the
|
2909 |
+
fastest). If order is 'F', then the returned array
|
2910 |
+
will be in Fortran-contiguous order (first-index varies the
|
2911 |
+
fastest).
|
2912 |
+
"""
|
2913 |
+
return array(obj, itemsize, copy=False,
|
2914 |
+
unicode=unicode, order=order)
|
env-llmeval/lib/python3.10/site-packages/numpy/core/einsumfunc.pyi
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections.abc import Sequence
|
2 |
+
from typing import TypeVar, Any, overload, Union, Literal
|
3 |
+
|
4 |
+
from numpy import (
|
5 |
+
ndarray,
|
6 |
+
dtype,
|
7 |
+
bool_,
|
8 |
+
number,
|
9 |
+
_OrderKACF,
|
10 |
+
)
|
11 |
+
from numpy._typing import (
|
12 |
+
_ArrayLikeBool_co,
|
13 |
+
_ArrayLikeUInt_co,
|
14 |
+
_ArrayLikeInt_co,
|
15 |
+
_ArrayLikeFloat_co,
|
16 |
+
_ArrayLikeComplex_co,
|
17 |
+
_ArrayLikeObject_co,
|
18 |
+
_DTypeLikeBool,
|
19 |
+
_DTypeLikeUInt,
|
20 |
+
_DTypeLikeInt,
|
21 |
+
_DTypeLikeFloat,
|
22 |
+
_DTypeLikeComplex,
|
23 |
+
_DTypeLikeComplex_co,
|
24 |
+
_DTypeLikeObject,
|
25 |
+
)
|
26 |
+
|
27 |
+
_ArrayType = TypeVar(
|
28 |
+
"_ArrayType",
|
29 |
+
bound=ndarray[Any, dtype[Union[bool_, number[Any]]]],
|
30 |
+
)
|
31 |
+
|
32 |
+
_OptimizeKind = None | bool | Literal["greedy", "optimal"] | Sequence[Any]
|
33 |
+
_CastingSafe = Literal["no", "equiv", "safe", "same_kind"]
|
34 |
+
_CastingUnsafe = Literal["unsafe"]
|
35 |
+
|
36 |
+
__all__: list[str]
|
37 |
+
|
38 |
+
# TODO: Properly handle the `casting`-based combinatorics
|
39 |
+
# TODO: We need to evaluate the content `__subscripts` in order
|
40 |
+
# to identify whether or an array or scalar is returned. At a cursory
|
41 |
+
# glance this seems like something that can quite easily be done with
|
42 |
+
# a mypy plugin.
|
43 |
+
# Something like `is_scalar = bool(__subscripts.partition("->")[-1])`
|
44 |
+
@overload
|
45 |
+
def einsum(
|
46 |
+
subscripts: str | _ArrayLikeInt_co,
|
47 |
+
/,
|
48 |
+
*operands: _ArrayLikeBool_co,
|
49 |
+
out: None = ...,
|
50 |
+
dtype: None | _DTypeLikeBool = ...,
|
51 |
+
order: _OrderKACF = ...,
|
52 |
+
casting: _CastingSafe = ...,
|
53 |
+
optimize: _OptimizeKind = ...,
|
54 |
+
) -> Any: ...
|
55 |
+
@overload
|
56 |
+
def einsum(
|
57 |
+
subscripts: str | _ArrayLikeInt_co,
|
58 |
+
/,
|
59 |
+
*operands: _ArrayLikeUInt_co,
|
60 |
+
out: None = ...,
|
61 |
+
dtype: None | _DTypeLikeUInt = ...,
|
62 |
+
order: _OrderKACF = ...,
|
63 |
+
casting: _CastingSafe = ...,
|
64 |
+
optimize: _OptimizeKind = ...,
|
65 |
+
) -> Any: ...
|
66 |
+
@overload
|
67 |
+
def einsum(
|
68 |
+
subscripts: str | _ArrayLikeInt_co,
|
69 |
+
/,
|
70 |
+
*operands: _ArrayLikeInt_co,
|
71 |
+
out: None = ...,
|
72 |
+
dtype: None | _DTypeLikeInt = ...,
|
73 |
+
order: _OrderKACF = ...,
|
74 |
+
casting: _CastingSafe = ...,
|
75 |
+
optimize: _OptimizeKind = ...,
|
76 |
+
) -> Any: ...
|
77 |
+
@overload
|
78 |
+
def einsum(
|
79 |
+
subscripts: str | _ArrayLikeInt_co,
|
80 |
+
/,
|
81 |
+
*operands: _ArrayLikeFloat_co,
|
82 |
+
out: None = ...,
|
83 |
+
dtype: None | _DTypeLikeFloat = ...,
|
84 |
+
order: _OrderKACF = ...,
|
85 |
+
casting: _CastingSafe = ...,
|
86 |
+
optimize: _OptimizeKind = ...,
|
87 |
+
) -> Any: ...
|
88 |
+
@overload
|
89 |
+
def einsum(
|
90 |
+
subscripts: str | _ArrayLikeInt_co,
|
91 |
+
/,
|
92 |
+
*operands: _ArrayLikeComplex_co,
|
93 |
+
out: None = ...,
|
94 |
+
dtype: None | _DTypeLikeComplex = ...,
|
95 |
+
order: _OrderKACF = ...,
|
96 |
+
casting: _CastingSafe = ...,
|
97 |
+
optimize: _OptimizeKind = ...,
|
98 |
+
) -> Any: ...
|
99 |
+
@overload
|
100 |
+
def einsum(
|
101 |
+
subscripts: str | _ArrayLikeInt_co,
|
102 |
+
/,
|
103 |
+
*operands: Any,
|
104 |
+
casting: _CastingUnsafe,
|
105 |
+
dtype: None | _DTypeLikeComplex_co = ...,
|
106 |
+
out: None = ...,
|
107 |
+
order: _OrderKACF = ...,
|
108 |
+
optimize: _OptimizeKind = ...,
|
109 |
+
) -> Any: ...
|
110 |
+
@overload
|
111 |
+
def einsum(
|
112 |
+
subscripts: str | _ArrayLikeInt_co,
|
113 |
+
/,
|
114 |
+
*operands: _ArrayLikeComplex_co,
|
115 |
+
out: _ArrayType,
|
116 |
+
dtype: None | _DTypeLikeComplex_co = ...,
|
117 |
+
order: _OrderKACF = ...,
|
118 |
+
casting: _CastingSafe = ...,
|
119 |
+
optimize: _OptimizeKind = ...,
|
120 |
+
) -> _ArrayType: ...
|
121 |
+
@overload
|
122 |
+
def einsum(
|
123 |
+
subscripts: str | _ArrayLikeInt_co,
|
124 |
+
/,
|
125 |
+
*operands: Any,
|
126 |
+
out: _ArrayType,
|
127 |
+
casting: _CastingUnsafe,
|
128 |
+
dtype: None | _DTypeLikeComplex_co = ...,
|
129 |
+
order: _OrderKACF = ...,
|
130 |
+
optimize: _OptimizeKind = ...,
|
131 |
+
) -> _ArrayType: ...
|
132 |
+
|
133 |
+
@overload
|
134 |
+
def einsum(
|
135 |
+
subscripts: str | _ArrayLikeInt_co,
|
136 |
+
/,
|
137 |
+
*operands: _ArrayLikeObject_co,
|
138 |
+
out: None = ...,
|
139 |
+
dtype: None | _DTypeLikeObject = ...,
|
140 |
+
order: _OrderKACF = ...,
|
141 |
+
casting: _CastingSafe = ...,
|
142 |
+
optimize: _OptimizeKind = ...,
|
143 |
+
) -> Any: ...
|
144 |
+
@overload
|
145 |
+
def einsum(
|
146 |
+
subscripts: str | _ArrayLikeInt_co,
|
147 |
+
/,
|
148 |
+
*operands: Any,
|
149 |
+
casting: _CastingUnsafe,
|
150 |
+
dtype: None | _DTypeLikeObject = ...,
|
151 |
+
out: None = ...,
|
152 |
+
order: _OrderKACF = ...,
|
153 |
+
optimize: _OptimizeKind = ...,
|
154 |
+
) -> Any: ...
|
155 |
+
@overload
|
156 |
+
def einsum(
|
157 |
+
subscripts: str | _ArrayLikeInt_co,
|
158 |
+
/,
|
159 |
+
*operands: _ArrayLikeObject_co,
|
160 |
+
out: _ArrayType,
|
161 |
+
dtype: None | _DTypeLikeObject = ...,
|
162 |
+
order: _OrderKACF = ...,
|
163 |
+
casting: _CastingSafe = ...,
|
164 |
+
optimize: _OptimizeKind = ...,
|
165 |
+
) -> _ArrayType: ...
|
166 |
+
@overload
|
167 |
+
def einsum(
|
168 |
+
subscripts: str | _ArrayLikeInt_co,
|
169 |
+
/,
|
170 |
+
*operands: Any,
|
171 |
+
out: _ArrayType,
|
172 |
+
casting: _CastingUnsafe,
|
173 |
+
dtype: None | _DTypeLikeObject = ...,
|
174 |
+
order: _OrderKACF = ...,
|
175 |
+
optimize: _OptimizeKind = ...,
|
176 |
+
) -> _ArrayType: ...
|
177 |
+
|
178 |
+
# NOTE: `einsum_call` is a hidden kwarg unavailable for public use.
|
179 |
+
# It is therefore excluded from the signatures below.
|
180 |
+
# NOTE: In practice the list consists of a `str` (first element)
|
181 |
+
# and a variable number of integer tuples.
|
182 |
+
def einsum_path(
|
183 |
+
subscripts: str | _ArrayLikeInt_co,
|
184 |
+
/,
|
185 |
+
*operands: _ArrayLikeComplex_co | _DTypeLikeObject,
|
186 |
+
optimize: _OptimizeKind = ...,
|
187 |
+
) -> tuple[list[Any], str]: ...
|
env-llmeval/lib/python3.10/site-packages/numpy/core/fromnumeric.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/numpy/core/fromnumeric.pyi
ADDED
@@ -0,0 +1,1060 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime as dt
|
2 |
+
from collections.abc import Sequence
|
3 |
+
from typing import Union, Any, overload, TypeVar, Literal, SupportsIndex
|
4 |
+
|
5 |
+
from numpy import (
|
6 |
+
ndarray,
|
7 |
+
number,
|
8 |
+
uint64,
|
9 |
+
int_,
|
10 |
+
int64,
|
11 |
+
intp,
|
12 |
+
float16,
|
13 |
+
bool_,
|
14 |
+
floating,
|
15 |
+
complexfloating,
|
16 |
+
object_,
|
17 |
+
generic,
|
18 |
+
_OrderKACF,
|
19 |
+
_OrderACF,
|
20 |
+
_ModeKind,
|
21 |
+
_PartitionKind,
|
22 |
+
_SortKind,
|
23 |
+
_SortSide,
|
24 |
+
_CastingKind,
|
25 |
+
)
|
26 |
+
from numpy._typing import (
|
27 |
+
DTypeLike,
|
28 |
+
_DTypeLike,
|
29 |
+
ArrayLike,
|
30 |
+
_ArrayLike,
|
31 |
+
NDArray,
|
32 |
+
_ShapeLike,
|
33 |
+
_Shape,
|
34 |
+
_ArrayLikeBool_co,
|
35 |
+
_ArrayLikeUInt_co,
|
36 |
+
_ArrayLikeInt_co,
|
37 |
+
_ArrayLikeFloat_co,
|
38 |
+
_ArrayLikeComplex_co,
|
39 |
+
_ArrayLikeObject_co,
|
40 |
+
_IntLike_co,
|
41 |
+
_BoolLike_co,
|
42 |
+
_ComplexLike_co,
|
43 |
+
_NumberLike_co,
|
44 |
+
_ScalarLike_co,
|
45 |
+
)
|
46 |
+
|
47 |
+
_SCT = TypeVar("_SCT", bound=generic)
|
48 |
+
_SCT_uifcO = TypeVar("_SCT_uifcO", bound=number[Any] | object_)
|
49 |
+
_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
|
50 |
+
|
51 |
+
__all__: list[str]
|
52 |
+
|
53 |
+
@overload
|
54 |
+
def take(
|
55 |
+
a: _ArrayLike[_SCT],
|
56 |
+
indices: _IntLike_co,
|
57 |
+
axis: None = ...,
|
58 |
+
out: None = ...,
|
59 |
+
mode: _ModeKind = ...,
|
60 |
+
) -> _SCT: ...
|
61 |
+
@overload
|
62 |
+
def take(
|
63 |
+
a: ArrayLike,
|
64 |
+
indices: _IntLike_co,
|
65 |
+
axis: None | SupportsIndex = ...,
|
66 |
+
out: None = ...,
|
67 |
+
mode: _ModeKind = ...,
|
68 |
+
) -> Any: ...
|
69 |
+
@overload
|
70 |
+
def take(
|
71 |
+
a: _ArrayLike[_SCT],
|
72 |
+
indices: _ArrayLikeInt_co,
|
73 |
+
axis: None | SupportsIndex = ...,
|
74 |
+
out: None = ...,
|
75 |
+
mode: _ModeKind = ...,
|
76 |
+
) -> NDArray[_SCT]: ...
|
77 |
+
@overload
|
78 |
+
def take(
|
79 |
+
a: ArrayLike,
|
80 |
+
indices: _ArrayLikeInt_co,
|
81 |
+
axis: None | SupportsIndex = ...,
|
82 |
+
out: None = ...,
|
83 |
+
mode: _ModeKind = ...,
|
84 |
+
) -> NDArray[Any]: ...
|
85 |
+
@overload
|
86 |
+
def take(
|
87 |
+
a: ArrayLike,
|
88 |
+
indices: _ArrayLikeInt_co,
|
89 |
+
axis: None | SupportsIndex = ...,
|
90 |
+
out: _ArrayType = ...,
|
91 |
+
mode: _ModeKind = ...,
|
92 |
+
) -> _ArrayType: ...
|
93 |
+
|
94 |
+
@overload
|
95 |
+
def reshape(
|
96 |
+
a: _ArrayLike[_SCT],
|
97 |
+
newshape: _ShapeLike,
|
98 |
+
order: _OrderACF = ...,
|
99 |
+
) -> NDArray[_SCT]: ...
|
100 |
+
@overload
|
101 |
+
def reshape(
|
102 |
+
a: ArrayLike,
|
103 |
+
newshape: _ShapeLike,
|
104 |
+
order: _OrderACF = ...,
|
105 |
+
) -> NDArray[Any]: ...
|
106 |
+
|
107 |
+
@overload
|
108 |
+
def choose(
|
109 |
+
a: _IntLike_co,
|
110 |
+
choices: ArrayLike,
|
111 |
+
out: None = ...,
|
112 |
+
mode: _ModeKind = ...,
|
113 |
+
) -> Any: ...
|
114 |
+
@overload
|
115 |
+
def choose(
|
116 |
+
a: _ArrayLikeInt_co,
|
117 |
+
choices: _ArrayLike[_SCT],
|
118 |
+
out: None = ...,
|
119 |
+
mode: _ModeKind = ...,
|
120 |
+
) -> NDArray[_SCT]: ...
|
121 |
+
@overload
|
122 |
+
def choose(
|
123 |
+
a: _ArrayLikeInt_co,
|
124 |
+
choices: ArrayLike,
|
125 |
+
out: None = ...,
|
126 |
+
mode: _ModeKind = ...,
|
127 |
+
) -> NDArray[Any]: ...
|
128 |
+
@overload
|
129 |
+
def choose(
|
130 |
+
a: _ArrayLikeInt_co,
|
131 |
+
choices: ArrayLike,
|
132 |
+
out: _ArrayType = ...,
|
133 |
+
mode: _ModeKind = ...,
|
134 |
+
) -> _ArrayType: ...
|
135 |
+
|
136 |
+
@overload
|
137 |
+
def repeat(
|
138 |
+
a: _ArrayLike[_SCT],
|
139 |
+
repeats: _ArrayLikeInt_co,
|
140 |
+
axis: None | SupportsIndex = ...,
|
141 |
+
) -> NDArray[_SCT]: ...
|
142 |
+
@overload
|
143 |
+
def repeat(
|
144 |
+
a: ArrayLike,
|
145 |
+
repeats: _ArrayLikeInt_co,
|
146 |
+
axis: None | SupportsIndex = ...,
|
147 |
+
) -> NDArray[Any]: ...
|
148 |
+
|
149 |
+
def put(
|
150 |
+
a: NDArray[Any],
|
151 |
+
ind: _ArrayLikeInt_co,
|
152 |
+
v: ArrayLike,
|
153 |
+
mode: _ModeKind = ...,
|
154 |
+
) -> None: ...
|
155 |
+
|
156 |
+
@overload
|
157 |
+
def swapaxes(
|
158 |
+
a: _ArrayLike[_SCT],
|
159 |
+
axis1: SupportsIndex,
|
160 |
+
axis2: SupportsIndex,
|
161 |
+
) -> NDArray[_SCT]: ...
|
162 |
+
@overload
|
163 |
+
def swapaxes(
|
164 |
+
a: ArrayLike,
|
165 |
+
axis1: SupportsIndex,
|
166 |
+
axis2: SupportsIndex,
|
167 |
+
) -> NDArray[Any]: ...
|
168 |
+
|
169 |
+
@overload
|
170 |
+
def transpose(
|
171 |
+
a: _ArrayLike[_SCT],
|
172 |
+
axes: None | _ShapeLike = ...
|
173 |
+
) -> NDArray[_SCT]: ...
|
174 |
+
@overload
|
175 |
+
def transpose(
|
176 |
+
a: ArrayLike,
|
177 |
+
axes: None | _ShapeLike = ...
|
178 |
+
) -> NDArray[Any]: ...
|
179 |
+
|
180 |
+
@overload
|
181 |
+
def partition(
|
182 |
+
a: _ArrayLike[_SCT],
|
183 |
+
kth: _ArrayLikeInt_co,
|
184 |
+
axis: None | SupportsIndex = ...,
|
185 |
+
kind: _PartitionKind = ...,
|
186 |
+
order: None | str | Sequence[str] = ...,
|
187 |
+
) -> NDArray[_SCT]: ...
|
188 |
+
@overload
|
189 |
+
def partition(
|
190 |
+
a: ArrayLike,
|
191 |
+
kth: _ArrayLikeInt_co,
|
192 |
+
axis: None | SupportsIndex = ...,
|
193 |
+
kind: _PartitionKind = ...,
|
194 |
+
order: None | str | Sequence[str] = ...,
|
195 |
+
) -> NDArray[Any]: ...
|
196 |
+
|
197 |
+
def argpartition(
|
198 |
+
a: ArrayLike,
|
199 |
+
kth: _ArrayLikeInt_co,
|
200 |
+
axis: None | SupportsIndex = ...,
|
201 |
+
kind: _PartitionKind = ...,
|
202 |
+
order: None | str | Sequence[str] = ...,
|
203 |
+
) -> NDArray[intp]: ...
|
204 |
+
|
205 |
+
@overload
|
206 |
+
def sort(
|
207 |
+
a: _ArrayLike[_SCT],
|
208 |
+
axis: None | SupportsIndex = ...,
|
209 |
+
kind: None | _SortKind = ...,
|
210 |
+
order: None | str | Sequence[str] = ...,
|
211 |
+
) -> NDArray[_SCT]: ...
|
212 |
+
@overload
|
213 |
+
def sort(
|
214 |
+
a: ArrayLike,
|
215 |
+
axis: None | SupportsIndex = ...,
|
216 |
+
kind: None | _SortKind = ...,
|
217 |
+
order: None | str | Sequence[str] = ...,
|
218 |
+
) -> NDArray[Any]: ...
|
219 |
+
|
220 |
+
def argsort(
|
221 |
+
a: ArrayLike,
|
222 |
+
axis: None | SupportsIndex = ...,
|
223 |
+
kind: None | _SortKind = ...,
|
224 |
+
order: None | str | Sequence[str] = ...,
|
225 |
+
) -> NDArray[intp]: ...
|
226 |
+
|
227 |
+
@overload
|
228 |
+
def argmax(
|
229 |
+
a: ArrayLike,
|
230 |
+
axis: None = ...,
|
231 |
+
out: None = ...,
|
232 |
+
*,
|
233 |
+
keepdims: Literal[False] = ...,
|
234 |
+
) -> intp: ...
|
235 |
+
@overload
|
236 |
+
def argmax(
|
237 |
+
a: ArrayLike,
|
238 |
+
axis: None | SupportsIndex = ...,
|
239 |
+
out: None = ...,
|
240 |
+
*,
|
241 |
+
keepdims: bool = ...,
|
242 |
+
) -> Any: ...
|
243 |
+
@overload
|
244 |
+
def argmax(
|
245 |
+
a: ArrayLike,
|
246 |
+
axis: None | SupportsIndex = ...,
|
247 |
+
out: _ArrayType = ...,
|
248 |
+
*,
|
249 |
+
keepdims: bool = ...,
|
250 |
+
) -> _ArrayType: ...
|
251 |
+
|
252 |
+
@overload
|
253 |
+
def argmin(
|
254 |
+
a: ArrayLike,
|
255 |
+
axis: None = ...,
|
256 |
+
out: None = ...,
|
257 |
+
*,
|
258 |
+
keepdims: Literal[False] = ...,
|
259 |
+
) -> intp: ...
|
260 |
+
@overload
|
261 |
+
def argmin(
|
262 |
+
a: ArrayLike,
|
263 |
+
axis: None | SupportsIndex = ...,
|
264 |
+
out: None = ...,
|
265 |
+
*,
|
266 |
+
keepdims: bool = ...,
|
267 |
+
) -> Any: ...
|
268 |
+
@overload
|
269 |
+
def argmin(
|
270 |
+
a: ArrayLike,
|
271 |
+
axis: None | SupportsIndex = ...,
|
272 |
+
out: _ArrayType = ...,
|
273 |
+
*,
|
274 |
+
keepdims: bool = ...,
|
275 |
+
) -> _ArrayType: ...
|
276 |
+
|
277 |
+
@overload
|
278 |
+
def searchsorted(
|
279 |
+
a: ArrayLike,
|
280 |
+
v: _ScalarLike_co,
|
281 |
+
side: _SortSide = ...,
|
282 |
+
sorter: None | _ArrayLikeInt_co = ..., # 1D int array
|
283 |
+
) -> intp: ...
|
284 |
+
@overload
|
285 |
+
def searchsorted(
|
286 |
+
a: ArrayLike,
|
287 |
+
v: ArrayLike,
|
288 |
+
side: _SortSide = ...,
|
289 |
+
sorter: None | _ArrayLikeInt_co = ..., # 1D int array
|
290 |
+
) -> NDArray[intp]: ...
|
291 |
+
|
292 |
+
@overload
|
293 |
+
def resize(
|
294 |
+
a: _ArrayLike[_SCT],
|
295 |
+
new_shape: _ShapeLike,
|
296 |
+
) -> NDArray[_SCT]: ...
|
297 |
+
@overload
|
298 |
+
def resize(
|
299 |
+
a: ArrayLike,
|
300 |
+
new_shape: _ShapeLike,
|
301 |
+
) -> NDArray[Any]: ...
|
302 |
+
|
303 |
+
@overload
|
304 |
+
def squeeze(
|
305 |
+
a: _SCT,
|
306 |
+
axis: None | _ShapeLike = ...,
|
307 |
+
) -> _SCT: ...
|
308 |
+
@overload
|
309 |
+
def squeeze(
|
310 |
+
a: _ArrayLike[_SCT],
|
311 |
+
axis: None | _ShapeLike = ...,
|
312 |
+
) -> NDArray[_SCT]: ...
|
313 |
+
@overload
|
314 |
+
def squeeze(
|
315 |
+
a: ArrayLike,
|
316 |
+
axis: None | _ShapeLike = ...,
|
317 |
+
) -> NDArray[Any]: ...
|
318 |
+
|
319 |
+
@overload
|
320 |
+
def diagonal(
|
321 |
+
a: _ArrayLike[_SCT],
|
322 |
+
offset: SupportsIndex = ...,
|
323 |
+
axis1: SupportsIndex = ...,
|
324 |
+
axis2: SupportsIndex = ..., # >= 2D array
|
325 |
+
) -> NDArray[_SCT]: ...
|
326 |
+
@overload
|
327 |
+
def diagonal(
|
328 |
+
a: ArrayLike,
|
329 |
+
offset: SupportsIndex = ...,
|
330 |
+
axis1: SupportsIndex = ...,
|
331 |
+
axis2: SupportsIndex = ..., # >= 2D array
|
332 |
+
) -> NDArray[Any]: ...
|
333 |
+
|
334 |
+
@overload
|
335 |
+
def trace(
|
336 |
+
a: ArrayLike, # >= 2D array
|
337 |
+
offset: SupportsIndex = ...,
|
338 |
+
axis1: SupportsIndex = ...,
|
339 |
+
axis2: SupportsIndex = ...,
|
340 |
+
dtype: DTypeLike = ...,
|
341 |
+
out: None = ...,
|
342 |
+
) -> Any: ...
|
343 |
+
@overload
|
344 |
+
def trace(
|
345 |
+
a: ArrayLike, # >= 2D array
|
346 |
+
offset: SupportsIndex = ...,
|
347 |
+
axis1: SupportsIndex = ...,
|
348 |
+
axis2: SupportsIndex = ...,
|
349 |
+
dtype: DTypeLike = ...,
|
350 |
+
out: _ArrayType = ...,
|
351 |
+
) -> _ArrayType: ...
|
352 |
+
|
353 |
+
@overload
|
354 |
+
def ravel(a: _ArrayLike[_SCT], order: _OrderKACF = ...) -> NDArray[_SCT]: ...
|
355 |
+
@overload
|
356 |
+
def ravel(a: ArrayLike, order: _OrderKACF = ...) -> NDArray[Any]: ...
|
357 |
+
|
358 |
+
def nonzero(a: ArrayLike) -> tuple[NDArray[intp], ...]: ...
|
359 |
+
|
360 |
+
def shape(a: ArrayLike) -> _Shape: ...
|
361 |
+
|
362 |
+
@overload
|
363 |
+
def compress(
|
364 |
+
condition: _ArrayLikeBool_co, # 1D bool array
|
365 |
+
a: _ArrayLike[_SCT],
|
366 |
+
axis: None | SupportsIndex = ...,
|
367 |
+
out: None = ...,
|
368 |
+
) -> NDArray[_SCT]: ...
|
369 |
+
@overload
|
370 |
+
def compress(
|
371 |
+
condition: _ArrayLikeBool_co, # 1D bool array
|
372 |
+
a: ArrayLike,
|
373 |
+
axis: None | SupportsIndex = ...,
|
374 |
+
out: None = ...,
|
375 |
+
) -> NDArray[Any]: ...
|
376 |
+
@overload
|
377 |
+
def compress(
|
378 |
+
condition: _ArrayLikeBool_co, # 1D bool array
|
379 |
+
a: ArrayLike,
|
380 |
+
axis: None | SupportsIndex = ...,
|
381 |
+
out: _ArrayType = ...,
|
382 |
+
) -> _ArrayType: ...
|
383 |
+
|
384 |
+
@overload
|
385 |
+
def clip(
|
386 |
+
a: _SCT,
|
387 |
+
a_min: None | ArrayLike,
|
388 |
+
a_max: None | ArrayLike,
|
389 |
+
out: None = ...,
|
390 |
+
*,
|
391 |
+
dtype: None = ...,
|
392 |
+
where: None | _ArrayLikeBool_co = ...,
|
393 |
+
order: _OrderKACF = ...,
|
394 |
+
subok: bool = ...,
|
395 |
+
signature: str | tuple[None | str, ...] = ...,
|
396 |
+
extobj: list[Any] = ...,
|
397 |
+
casting: _CastingKind = ...,
|
398 |
+
) -> _SCT: ...
|
399 |
+
@overload
|
400 |
+
def clip(
|
401 |
+
a: _ScalarLike_co,
|
402 |
+
a_min: None | ArrayLike,
|
403 |
+
a_max: None | ArrayLike,
|
404 |
+
out: None = ...,
|
405 |
+
*,
|
406 |
+
dtype: None = ...,
|
407 |
+
where: None | _ArrayLikeBool_co = ...,
|
408 |
+
order: _OrderKACF = ...,
|
409 |
+
subok: bool = ...,
|
410 |
+
signature: str | tuple[None | str, ...] = ...,
|
411 |
+
extobj: list[Any] = ...,
|
412 |
+
casting: _CastingKind = ...,
|
413 |
+
) -> Any: ...
|
414 |
+
@overload
|
415 |
+
def clip(
|
416 |
+
a: _ArrayLike[_SCT],
|
417 |
+
a_min: None | ArrayLike,
|
418 |
+
a_max: None | ArrayLike,
|
419 |
+
out: None = ...,
|
420 |
+
*,
|
421 |
+
dtype: None = ...,
|
422 |
+
where: None | _ArrayLikeBool_co = ...,
|
423 |
+
order: _OrderKACF = ...,
|
424 |
+
subok: bool = ...,
|
425 |
+
signature: str | tuple[None | str, ...] = ...,
|
426 |
+
extobj: list[Any] = ...,
|
427 |
+
casting: _CastingKind = ...,
|
428 |
+
) -> NDArray[_SCT]: ...
|
429 |
+
@overload
|
430 |
+
def clip(
|
431 |
+
a: ArrayLike,
|
432 |
+
a_min: None | ArrayLike,
|
433 |
+
a_max: None | ArrayLike,
|
434 |
+
out: None = ...,
|
435 |
+
*,
|
436 |
+
dtype: None = ...,
|
437 |
+
where: None | _ArrayLikeBool_co = ...,
|
438 |
+
order: _OrderKACF = ...,
|
439 |
+
subok: bool = ...,
|
440 |
+
signature: str | tuple[None | str, ...] = ...,
|
441 |
+
extobj: list[Any] = ...,
|
442 |
+
casting: _CastingKind = ...,
|
443 |
+
) -> NDArray[Any]: ...
|
444 |
+
@overload
|
445 |
+
def clip(
|
446 |
+
a: ArrayLike,
|
447 |
+
a_min: None | ArrayLike,
|
448 |
+
a_max: None | ArrayLike,
|
449 |
+
out: _ArrayType = ...,
|
450 |
+
*,
|
451 |
+
dtype: DTypeLike,
|
452 |
+
where: None | _ArrayLikeBool_co = ...,
|
453 |
+
order: _OrderKACF = ...,
|
454 |
+
subok: bool = ...,
|
455 |
+
signature: str | tuple[None | str, ...] = ...,
|
456 |
+
extobj: list[Any] = ...,
|
457 |
+
casting: _CastingKind = ...,
|
458 |
+
) -> Any: ...
|
459 |
+
@overload
|
460 |
+
def clip(
|
461 |
+
a: ArrayLike,
|
462 |
+
a_min: None | ArrayLike,
|
463 |
+
a_max: None | ArrayLike,
|
464 |
+
out: _ArrayType,
|
465 |
+
*,
|
466 |
+
dtype: DTypeLike = ...,
|
467 |
+
where: None | _ArrayLikeBool_co = ...,
|
468 |
+
order: _OrderKACF = ...,
|
469 |
+
subok: bool = ...,
|
470 |
+
signature: str | tuple[None | str, ...] = ...,
|
471 |
+
extobj: list[Any] = ...,
|
472 |
+
casting: _CastingKind = ...,
|
473 |
+
) -> _ArrayType: ...
|
474 |
+
|
475 |
+
@overload
|
476 |
+
def sum(
|
477 |
+
a: _ArrayLike[_SCT],
|
478 |
+
axis: None = ...,
|
479 |
+
dtype: None = ...,
|
480 |
+
out: None = ...,
|
481 |
+
keepdims: bool = ...,
|
482 |
+
initial: _NumberLike_co = ...,
|
483 |
+
where: _ArrayLikeBool_co = ...,
|
484 |
+
) -> _SCT: ...
|
485 |
+
@overload
|
486 |
+
def sum(
|
487 |
+
a: ArrayLike,
|
488 |
+
axis: None | _ShapeLike = ...,
|
489 |
+
dtype: DTypeLike = ...,
|
490 |
+
out: None = ...,
|
491 |
+
keepdims: bool = ...,
|
492 |
+
initial: _NumberLike_co = ...,
|
493 |
+
where: _ArrayLikeBool_co = ...,
|
494 |
+
) -> Any: ...
|
495 |
+
@overload
|
496 |
+
def sum(
|
497 |
+
a: ArrayLike,
|
498 |
+
axis: None | _ShapeLike = ...,
|
499 |
+
dtype: DTypeLike = ...,
|
500 |
+
out: _ArrayType = ...,
|
501 |
+
keepdims: bool = ...,
|
502 |
+
initial: _NumberLike_co = ...,
|
503 |
+
where: _ArrayLikeBool_co = ...,
|
504 |
+
) -> _ArrayType: ...
|
505 |
+
|
506 |
+
@overload
|
507 |
+
def all(
|
508 |
+
a: ArrayLike,
|
509 |
+
axis: None = ...,
|
510 |
+
out: None = ...,
|
511 |
+
keepdims: Literal[False] = ...,
|
512 |
+
*,
|
513 |
+
where: _ArrayLikeBool_co = ...,
|
514 |
+
) -> bool_: ...
|
515 |
+
@overload
|
516 |
+
def all(
|
517 |
+
a: ArrayLike,
|
518 |
+
axis: None | _ShapeLike = ...,
|
519 |
+
out: None = ...,
|
520 |
+
keepdims: bool = ...,
|
521 |
+
*,
|
522 |
+
where: _ArrayLikeBool_co = ...,
|
523 |
+
) -> Any: ...
|
524 |
+
@overload
|
525 |
+
def all(
|
526 |
+
a: ArrayLike,
|
527 |
+
axis: None | _ShapeLike = ...,
|
528 |
+
out: _ArrayType = ...,
|
529 |
+
keepdims: bool = ...,
|
530 |
+
*,
|
531 |
+
where: _ArrayLikeBool_co = ...,
|
532 |
+
) -> _ArrayType: ...
|
533 |
+
|
534 |
+
@overload
|
535 |
+
def any(
|
536 |
+
a: ArrayLike,
|
537 |
+
axis: None = ...,
|
538 |
+
out: None = ...,
|
539 |
+
keepdims: Literal[False] = ...,
|
540 |
+
*,
|
541 |
+
where: _ArrayLikeBool_co = ...,
|
542 |
+
) -> bool_: ...
|
543 |
+
@overload
|
544 |
+
def any(
|
545 |
+
a: ArrayLike,
|
546 |
+
axis: None | _ShapeLike = ...,
|
547 |
+
out: None = ...,
|
548 |
+
keepdims: bool = ...,
|
549 |
+
*,
|
550 |
+
where: _ArrayLikeBool_co = ...,
|
551 |
+
) -> Any: ...
|
552 |
+
@overload
|
553 |
+
def any(
|
554 |
+
a: ArrayLike,
|
555 |
+
axis: None | _ShapeLike = ...,
|
556 |
+
out: _ArrayType = ...,
|
557 |
+
keepdims: bool = ...,
|
558 |
+
*,
|
559 |
+
where: _ArrayLikeBool_co = ...,
|
560 |
+
) -> _ArrayType: ...
|
561 |
+
|
562 |
+
@overload
|
563 |
+
def cumsum(
|
564 |
+
a: _ArrayLike[_SCT],
|
565 |
+
axis: None | SupportsIndex = ...,
|
566 |
+
dtype: None = ...,
|
567 |
+
out: None = ...,
|
568 |
+
) -> NDArray[_SCT]: ...
|
569 |
+
@overload
|
570 |
+
def cumsum(
|
571 |
+
a: ArrayLike,
|
572 |
+
axis: None | SupportsIndex = ...,
|
573 |
+
dtype: None = ...,
|
574 |
+
out: None = ...,
|
575 |
+
) -> NDArray[Any]: ...
|
576 |
+
@overload
|
577 |
+
def cumsum(
|
578 |
+
a: ArrayLike,
|
579 |
+
axis: None | SupportsIndex = ...,
|
580 |
+
dtype: _DTypeLike[_SCT] = ...,
|
581 |
+
out: None = ...,
|
582 |
+
) -> NDArray[_SCT]: ...
|
583 |
+
@overload
|
584 |
+
def cumsum(
|
585 |
+
a: ArrayLike,
|
586 |
+
axis: None | SupportsIndex = ...,
|
587 |
+
dtype: DTypeLike = ...,
|
588 |
+
out: None = ...,
|
589 |
+
) -> NDArray[Any]: ...
|
590 |
+
@overload
|
591 |
+
def cumsum(
|
592 |
+
a: ArrayLike,
|
593 |
+
axis: None | SupportsIndex = ...,
|
594 |
+
dtype: DTypeLike = ...,
|
595 |
+
out: _ArrayType = ...,
|
596 |
+
) -> _ArrayType: ...
|
597 |
+
|
598 |
+
@overload
|
599 |
+
def ptp(
|
600 |
+
a: _ArrayLike[_SCT],
|
601 |
+
axis: None = ...,
|
602 |
+
out: None = ...,
|
603 |
+
keepdims: Literal[False] = ...,
|
604 |
+
) -> _SCT: ...
|
605 |
+
@overload
|
606 |
+
def ptp(
|
607 |
+
a: ArrayLike,
|
608 |
+
axis: None | _ShapeLike = ...,
|
609 |
+
out: None = ...,
|
610 |
+
keepdims: bool = ...,
|
611 |
+
) -> Any: ...
|
612 |
+
@overload
|
613 |
+
def ptp(
|
614 |
+
a: ArrayLike,
|
615 |
+
axis: None | _ShapeLike = ...,
|
616 |
+
out: _ArrayType = ...,
|
617 |
+
keepdims: bool = ...,
|
618 |
+
) -> _ArrayType: ...
|
619 |
+
|
620 |
+
@overload
|
621 |
+
def amax(
|
622 |
+
a: _ArrayLike[_SCT],
|
623 |
+
axis: None = ...,
|
624 |
+
out: None = ...,
|
625 |
+
keepdims: Literal[False] = ...,
|
626 |
+
initial: _NumberLike_co = ...,
|
627 |
+
where: _ArrayLikeBool_co = ...,
|
628 |
+
) -> _SCT: ...
|
629 |
+
@overload
|
630 |
+
def amax(
|
631 |
+
a: ArrayLike,
|
632 |
+
axis: None | _ShapeLike = ...,
|
633 |
+
out: None = ...,
|
634 |
+
keepdims: bool = ...,
|
635 |
+
initial: _NumberLike_co = ...,
|
636 |
+
where: _ArrayLikeBool_co = ...,
|
637 |
+
) -> Any: ...
|
638 |
+
@overload
|
639 |
+
def amax(
|
640 |
+
a: ArrayLike,
|
641 |
+
axis: None | _ShapeLike = ...,
|
642 |
+
out: _ArrayType = ...,
|
643 |
+
keepdims: bool = ...,
|
644 |
+
initial: _NumberLike_co = ...,
|
645 |
+
where: _ArrayLikeBool_co = ...,
|
646 |
+
) -> _ArrayType: ...
|
647 |
+
|
648 |
+
@overload
|
649 |
+
def amin(
|
650 |
+
a: _ArrayLike[_SCT],
|
651 |
+
axis: None = ...,
|
652 |
+
out: None = ...,
|
653 |
+
keepdims: Literal[False] = ...,
|
654 |
+
initial: _NumberLike_co = ...,
|
655 |
+
where: _ArrayLikeBool_co = ...,
|
656 |
+
) -> _SCT: ...
|
657 |
+
@overload
|
658 |
+
def amin(
|
659 |
+
a: ArrayLike,
|
660 |
+
axis: None | _ShapeLike = ...,
|
661 |
+
out: None = ...,
|
662 |
+
keepdims: bool = ...,
|
663 |
+
initial: _NumberLike_co = ...,
|
664 |
+
where: _ArrayLikeBool_co = ...,
|
665 |
+
) -> Any: ...
|
666 |
+
@overload
|
667 |
+
def amin(
|
668 |
+
a: ArrayLike,
|
669 |
+
axis: None | _ShapeLike = ...,
|
670 |
+
out: _ArrayType = ...,
|
671 |
+
keepdims: bool = ...,
|
672 |
+
initial: _NumberLike_co = ...,
|
673 |
+
where: _ArrayLikeBool_co = ...,
|
674 |
+
) -> _ArrayType: ...
|
675 |
+
|
676 |
+
# TODO: `np.prod()``: For object arrays `initial` does not necessarily
|
677 |
+
# have to be a numerical scalar.
|
678 |
+
# The only requirement is that it is compatible
|
679 |
+
# with the `.__mul__()` method(s) of the passed array's elements.
|
680 |
+
|
681 |
+
# Note that the same situation holds for all wrappers around
|
682 |
+
# `np.ufunc.reduce`, e.g. `np.sum()` (`.__add__()`).
|
683 |
+
@overload
|
684 |
+
def prod(
|
685 |
+
a: _ArrayLikeBool_co,
|
686 |
+
axis: None = ...,
|
687 |
+
dtype: None = ...,
|
688 |
+
out: None = ...,
|
689 |
+
keepdims: Literal[False] = ...,
|
690 |
+
initial: _NumberLike_co = ...,
|
691 |
+
where: _ArrayLikeBool_co = ...,
|
692 |
+
) -> int_: ...
|
693 |
+
@overload
|
694 |
+
def prod(
|
695 |
+
a: _ArrayLikeUInt_co,
|
696 |
+
axis: None = ...,
|
697 |
+
dtype: None = ...,
|
698 |
+
out: None = ...,
|
699 |
+
keepdims: Literal[False] = ...,
|
700 |
+
initial: _NumberLike_co = ...,
|
701 |
+
where: _ArrayLikeBool_co = ...,
|
702 |
+
) -> uint64: ...
|
703 |
+
@overload
|
704 |
+
def prod(
|
705 |
+
a: _ArrayLikeInt_co,
|
706 |
+
axis: None = ...,
|
707 |
+
dtype: None = ...,
|
708 |
+
out: None = ...,
|
709 |
+
keepdims: Literal[False] = ...,
|
710 |
+
initial: _NumberLike_co = ...,
|
711 |
+
where: _ArrayLikeBool_co = ...,
|
712 |
+
) -> int64: ...
|
713 |
+
@overload
|
714 |
+
def prod(
|
715 |
+
a: _ArrayLikeFloat_co,
|
716 |
+
axis: None = ...,
|
717 |
+
dtype: None = ...,
|
718 |
+
out: None = ...,
|
719 |
+
keepdims: Literal[False] = ...,
|
720 |
+
initial: _NumberLike_co = ...,
|
721 |
+
where: _ArrayLikeBool_co = ...,
|
722 |
+
) -> floating[Any]: ...
|
723 |
+
@overload
|
724 |
+
def prod(
|
725 |
+
a: _ArrayLikeComplex_co,
|
726 |
+
axis: None = ...,
|
727 |
+
dtype: None = ...,
|
728 |
+
out: None = ...,
|
729 |
+
keepdims: Literal[False] = ...,
|
730 |
+
initial: _NumberLike_co = ...,
|
731 |
+
where: _ArrayLikeBool_co = ...,
|
732 |
+
) -> complexfloating[Any, Any]: ...
|
733 |
+
@overload
|
734 |
+
def prod(
|
735 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
736 |
+
axis: None | _ShapeLike = ...,
|
737 |
+
dtype: None = ...,
|
738 |
+
out: None = ...,
|
739 |
+
keepdims: bool = ...,
|
740 |
+
initial: _NumberLike_co = ...,
|
741 |
+
where: _ArrayLikeBool_co = ...,
|
742 |
+
) -> Any: ...
|
743 |
+
@overload
|
744 |
+
def prod(
|
745 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
746 |
+
axis: None = ...,
|
747 |
+
dtype: _DTypeLike[_SCT] = ...,
|
748 |
+
out: None = ...,
|
749 |
+
keepdims: Literal[False] = ...,
|
750 |
+
initial: _NumberLike_co = ...,
|
751 |
+
where: _ArrayLikeBool_co = ...,
|
752 |
+
) -> _SCT: ...
|
753 |
+
@overload
|
754 |
+
def prod(
|
755 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
756 |
+
axis: None | _ShapeLike = ...,
|
757 |
+
dtype: None | DTypeLike = ...,
|
758 |
+
out: None = ...,
|
759 |
+
keepdims: bool = ...,
|
760 |
+
initial: _NumberLike_co = ...,
|
761 |
+
where: _ArrayLikeBool_co = ...,
|
762 |
+
) -> Any: ...
|
763 |
+
@overload
|
764 |
+
def prod(
|
765 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
766 |
+
axis: None | _ShapeLike = ...,
|
767 |
+
dtype: None | DTypeLike = ...,
|
768 |
+
out: _ArrayType = ...,
|
769 |
+
keepdims: bool = ...,
|
770 |
+
initial: _NumberLike_co = ...,
|
771 |
+
where: _ArrayLikeBool_co = ...,
|
772 |
+
) -> _ArrayType: ...
|
773 |
+
|
774 |
+
@overload
|
775 |
+
def cumprod(
|
776 |
+
a: _ArrayLikeBool_co,
|
777 |
+
axis: None | SupportsIndex = ...,
|
778 |
+
dtype: None = ...,
|
779 |
+
out: None = ...,
|
780 |
+
) -> NDArray[int_]: ...
|
781 |
+
@overload
|
782 |
+
def cumprod(
|
783 |
+
a: _ArrayLikeUInt_co,
|
784 |
+
axis: None | SupportsIndex = ...,
|
785 |
+
dtype: None = ...,
|
786 |
+
out: None = ...,
|
787 |
+
) -> NDArray[uint64]: ...
|
788 |
+
@overload
|
789 |
+
def cumprod(
|
790 |
+
a: _ArrayLikeInt_co,
|
791 |
+
axis: None | SupportsIndex = ...,
|
792 |
+
dtype: None = ...,
|
793 |
+
out: None = ...,
|
794 |
+
) -> NDArray[int64]: ...
|
795 |
+
@overload
|
796 |
+
def cumprod(
|
797 |
+
a: _ArrayLikeFloat_co,
|
798 |
+
axis: None | SupportsIndex = ...,
|
799 |
+
dtype: None = ...,
|
800 |
+
out: None = ...,
|
801 |
+
) -> NDArray[floating[Any]]: ...
|
802 |
+
@overload
|
803 |
+
def cumprod(
|
804 |
+
a: _ArrayLikeComplex_co,
|
805 |
+
axis: None | SupportsIndex = ...,
|
806 |
+
dtype: None = ...,
|
807 |
+
out: None = ...,
|
808 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
809 |
+
@overload
|
810 |
+
def cumprod(
|
811 |
+
a: _ArrayLikeObject_co,
|
812 |
+
axis: None | SupportsIndex = ...,
|
813 |
+
dtype: None = ...,
|
814 |
+
out: None = ...,
|
815 |
+
) -> NDArray[object_]: ...
|
816 |
+
@overload
|
817 |
+
def cumprod(
|
818 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
819 |
+
axis: None | SupportsIndex = ...,
|
820 |
+
dtype: _DTypeLike[_SCT] = ...,
|
821 |
+
out: None = ...,
|
822 |
+
) -> NDArray[_SCT]: ...
|
823 |
+
@overload
|
824 |
+
def cumprod(
|
825 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
826 |
+
axis: None | SupportsIndex = ...,
|
827 |
+
dtype: DTypeLike = ...,
|
828 |
+
out: None = ...,
|
829 |
+
) -> NDArray[Any]: ...
|
830 |
+
@overload
|
831 |
+
def cumprod(
|
832 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
833 |
+
axis: None | SupportsIndex = ...,
|
834 |
+
dtype: DTypeLike = ...,
|
835 |
+
out: _ArrayType = ...,
|
836 |
+
) -> _ArrayType: ...
|
837 |
+
|
838 |
+
def ndim(a: ArrayLike) -> int: ...
|
839 |
+
|
840 |
+
def size(a: ArrayLike, axis: None | int = ...) -> int: ...
|
841 |
+
|
842 |
+
@overload
|
843 |
+
def around(
|
844 |
+
a: _BoolLike_co,
|
845 |
+
decimals: SupportsIndex = ...,
|
846 |
+
out: None = ...,
|
847 |
+
) -> float16: ...
|
848 |
+
@overload
|
849 |
+
def around(
|
850 |
+
a: _SCT_uifcO,
|
851 |
+
decimals: SupportsIndex = ...,
|
852 |
+
out: None = ...,
|
853 |
+
) -> _SCT_uifcO: ...
|
854 |
+
@overload
|
855 |
+
def around(
|
856 |
+
a: _ComplexLike_co | object_,
|
857 |
+
decimals: SupportsIndex = ...,
|
858 |
+
out: None = ...,
|
859 |
+
) -> Any: ...
|
860 |
+
@overload
|
861 |
+
def around(
|
862 |
+
a: _ArrayLikeBool_co,
|
863 |
+
decimals: SupportsIndex = ...,
|
864 |
+
out: None = ...,
|
865 |
+
) -> NDArray[float16]: ...
|
866 |
+
@overload
|
867 |
+
def around(
|
868 |
+
a: _ArrayLike[_SCT_uifcO],
|
869 |
+
decimals: SupportsIndex = ...,
|
870 |
+
out: None = ...,
|
871 |
+
) -> NDArray[_SCT_uifcO]: ...
|
872 |
+
@overload
|
873 |
+
def around(
|
874 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
875 |
+
decimals: SupportsIndex = ...,
|
876 |
+
out: None = ...,
|
877 |
+
) -> NDArray[Any]: ...
|
878 |
+
@overload
|
879 |
+
def around(
|
880 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
881 |
+
decimals: SupportsIndex = ...,
|
882 |
+
out: _ArrayType = ...,
|
883 |
+
) -> _ArrayType: ...
|
884 |
+
|
885 |
+
@overload
|
886 |
+
def mean(
|
887 |
+
a: _ArrayLikeFloat_co,
|
888 |
+
axis: None = ...,
|
889 |
+
dtype: None = ...,
|
890 |
+
out: None = ...,
|
891 |
+
keepdims: Literal[False] = ...,
|
892 |
+
*,
|
893 |
+
where: _ArrayLikeBool_co = ...,
|
894 |
+
) -> floating[Any]: ...
|
895 |
+
@overload
|
896 |
+
def mean(
|
897 |
+
a: _ArrayLikeComplex_co,
|
898 |
+
axis: None = ...,
|
899 |
+
dtype: None = ...,
|
900 |
+
out: None = ...,
|
901 |
+
keepdims: Literal[False] = ...,
|
902 |
+
*,
|
903 |
+
where: _ArrayLikeBool_co = ...,
|
904 |
+
) -> complexfloating[Any, Any]: ...
|
905 |
+
@overload
|
906 |
+
def mean(
|
907 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
908 |
+
axis: None | _ShapeLike = ...,
|
909 |
+
dtype: None = ...,
|
910 |
+
out: None = ...,
|
911 |
+
keepdims: bool = ...,
|
912 |
+
*,
|
913 |
+
where: _ArrayLikeBool_co = ...,
|
914 |
+
) -> Any: ...
|
915 |
+
@overload
|
916 |
+
def mean(
|
917 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
918 |
+
axis: None = ...,
|
919 |
+
dtype: _DTypeLike[_SCT] = ...,
|
920 |
+
out: None = ...,
|
921 |
+
keepdims: Literal[False] = ...,
|
922 |
+
*,
|
923 |
+
where: _ArrayLikeBool_co = ...,
|
924 |
+
) -> _SCT: ...
|
925 |
+
@overload
|
926 |
+
def mean(
|
927 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
928 |
+
axis: None | _ShapeLike = ...,
|
929 |
+
dtype: DTypeLike = ...,
|
930 |
+
out: None = ...,
|
931 |
+
keepdims: bool = ...,
|
932 |
+
*,
|
933 |
+
where: _ArrayLikeBool_co = ...,
|
934 |
+
) -> Any: ...
|
935 |
+
@overload
|
936 |
+
def mean(
|
937 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
938 |
+
axis: None | _ShapeLike = ...,
|
939 |
+
dtype: DTypeLike = ...,
|
940 |
+
out: _ArrayType = ...,
|
941 |
+
keepdims: bool = ...,
|
942 |
+
*,
|
943 |
+
where: _ArrayLikeBool_co = ...,
|
944 |
+
) -> _ArrayType: ...
|
945 |
+
|
946 |
+
@overload
|
947 |
+
def std(
|
948 |
+
a: _ArrayLikeComplex_co,
|
949 |
+
axis: None = ...,
|
950 |
+
dtype: None = ...,
|
951 |
+
out: None = ...,
|
952 |
+
ddof: float = ...,
|
953 |
+
keepdims: Literal[False] = ...,
|
954 |
+
*,
|
955 |
+
where: _ArrayLikeBool_co = ...,
|
956 |
+
) -> floating[Any]: ...
|
957 |
+
@overload
|
958 |
+
def std(
|
959 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
960 |
+
axis: None | _ShapeLike = ...,
|
961 |
+
dtype: None = ...,
|
962 |
+
out: None = ...,
|
963 |
+
ddof: float = ...,
|
964 |
+
keepdims: bool = ...,
|
965 |
+
*,
|
966 |
+
where: _ArrayLikeBool_co = ...,
|
967 |
+
) -> Any: ...
|
968 |
+
@overload
|
969 |
+
def std(
|
970 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
971 |
+
axis: None = ...,
|
972 |
+
dtype: _DTypeLike[_SCT] = ...,
|
973 |
+
out: None = ...,
|
974 |
+
ddof: float = ...,
|
975 |
+
keepdims: Literal[False] = ...,
|
976 |
+
*,
|
977 |
+
where: _ArrayLikeBool_co = ...,
|
978 |
+
) -> _SCT: ...
|
979 |
+
@overload
|
980 |
+
def std(
|
981 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
982 |
+
axis: None | _ShapeLike = ...,
|
983 |
+
dtype: DTypeLike = ...,
|
984 |
+
out: None = ...,
|
985 |
+
ddof: float = ...,
|
986 |
+
keepdims: bool = ...,
|
987 |
+
*,
|
988 |
+
where: _ArrayLikeBool_co = ...,
|
989 |
+
) -> Any: ...
|
990 |
+
@overload
|
991 |
+
def std(
|
992 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
993 |
+
axis: None | _ShapeLike = ...,
|
994 |
+
dtype: DTypeLike = ...,
|
995 |
+
out: _ArrayType = ...,
|
996 |
+
ddof: float = ...,
|
997 |
+
keepdims: bool = ...,
|
998 |
+
*,
|
999 |
+
where: _ArrayLikeBool_co = ...,
|
1000 |
+
) -> _ArrayType: ...
|
1001 |
+
|
1002 |
+
@overload
|
1003 |
+
def var(
|
1004 |
+
a: _ArrayLikeComplex_co,
|
1005 |
+
axis: None = ...,
|
1006 |
+
dtype: None = ...,
|
1007 |
+
out: None = ...,
|
1008 |
+
ddof: float = ...,
|
1009 |
+
keepdims: Literal[False] = ...,
|
1010 |
+
*,
|
1011 |
+
where: _ArrayLikeBool_co = ...,
|
1012 |
+
) -> floating[Any]: ...
|
1013 |
+
@overload
|
1014 |
+
def var(
|
1015 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
1016 |
+
axis: None | _ShapeLike = ...,
|
1017 |
+
dtype: None = ...,
|
1018 |
+
out: None = ...,
|
1019 |
+
ddof: float = ...,
|
1020 |
+
keepdims: bool = ...,
|
1021 |
+
*,
|
1022 |
+
where: _ArrayLikeBool_co = ...,
|
1023 |
+
) -> Any: ...
|
1024 |
+
@overload
|
1025 |
+
def var(
|
1026 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
1027 |
+
axis: None = ...,
|
1028 |
+
dtype: _DTypeLike[_SCT] = ...,
|
1029 |
+
out: None = ...,
|
1030 |
+
ddof: float = ...,
|
1031 |
+
keepdims: Literal[False] = ...,
|
1032 |
+
*,
|
1033 |
+
where: _ArrayLikeBool_co = ...,
|
1034 |
+
) -> _SCT: ...
|
1035 |
+
@overload
|
1036 |
+
def var(
|
1037 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
1038 |
+
axis: None | _ShapeLike = ...,
|
1039 |
+
dtype: DTypeLike = ...,
|
1040 |
+
out: None = ...,
|
1041 |
+
ddof: float = ...,
|
1042 |
+
keepdims: bool = ...,
|
1043 |
+
*,
|
1044 |
+
where: _ArrayLikeBool_co = ...,
|
1045 |
+
) -> Any: ...
|
1046 |
+
@overload
|
1047 |
+
def var(
|
1048 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
1049 |
+
axis: None | _ShapeLike = ...,
|
1050 |
+
dtype: DTypeLike = ...,
|
1051 |
+
out: _ArrayType = ...,
|
1052 |
+
ddof: float = ...,
|
1053 |
+
keepdims: bool = ...,
|
1054 |
+
*,
|
1055 |
+
where: _ArrayLikeBool_co = ...,
|
1056 |
+
) -> _ArrayType: ...
|
1057 |
+
|
1058 |
+
max = amax
|
1059 |
+
min = amin
|
1060 |
+
round = around
|
env-llmeval/lib/python3.10/site-packages/numpy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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import functools
|
2 |
+
import warnings
|
3 |
+
import operator
|
4 |
+
import types
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
from . import numeric as _nx
|
8 |
+
from .numeric import result_type, NaN, asanyarray, ndim
|
9 |
+
from numpy.core.multiarray import add_docstring
|
10 |
+
from numpy.core import overrides
|
11 |
+
|
12 |
+
__all__ = ['logspace', 'linspace', 'geomspace']
|
13 |
+
|
14 |
+
|
15 |
+
array_function_dispatch = functools.partial(
|
16 |
+
overrides.array_function_dispatch, module='numpy')
|
17 |
+
|
18 |
+
|
19 |
+
def _linspace_dispatcher(start, stop, num=None, endpoint=None, retstep=None,
|
20 |
+
dtype=None, axis=None):
|
21 |
+
return (start, stop)
|
22 |
+
|
23 |
+
|
24 |
+
@array_function_dispatch(_linspace_dispatcher)
|
25 |
+
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
|
26 |
+
axis=0):
|
27 |
+
"""
|
28 |
+
Return evenly spaced numbers over a specified interval.
|
29 |
+
|
30 |
+
Returns `num` evenly spaced samples, calculated over the
|
31 |
+
interval [`start`, `stop`].
|
32 |
+
|
33 |
+
The endpoint of the interval can optionally be excluded.
|
34 |
+
|
35 |
+
.. versionchanged:: 1.16.0
|
36 |
+
Non-scalar `start` and `stop` are now supported.
|
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 |
+
|
66 |
+
.. versionadded:: 1.9.0
|
67 |
+
|
68 |
+
axis : int, optional
|
69 |
+
The axis in the result to store the samples. Relevant only if start
|
70 |
+
or stop are array-like. By default (0), the samples will be along a
|
71 |
+
new axis inserted at the beginning. Use -1 to get an axis at the end.
|
72 |
+
|
73 |
+
.. versionadded:: 1.16.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 |
+
>>> np.linspace(2.0, 3.0, num=5)
|
100 |
+
array([2. , 2.25, 2.5 , 2.75, 3. ])
|
101 |
+
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
|
102 |
+
array([2. , 2.2, 2.4, 2.6, 2.8])
|
103 |
+
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
|
104 |
+
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
|
105 |
+
|
106 |
+
Graphical illustration:
|
107 |
+
|
108 |
+
>>> import matplotlib.pyplot as plt
|
109 |
+
>>> N = 8
|
110 |
+
>>> y = np.zeros(N)
|
111 |
+
>>> x1 = np.linspace(0, 10, N, endpoint=True)
|
112 |
+
>>> x2 = np.linspace(0, 10, N, endpoint=False)
|
113 |
+
>>> plt.plot(x1, y, 'o')
|
114 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
115 |
+
>>> plt.plot(x2, y + 0.5, 'o')
|
116 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
117 |
+
>>> plt.ylim([-0.5, 1])
|
118 |
+
(-0.5, 1)
|
119 |
+
>>> plt.show()
|
120 |
+
|
121 |
+
"""
|
122 |
+
num = operator.index(num)
|
123 |
+
if num < 0:
|
124 |
+
raise ValueError("Number of samples, %s, must be non-negative." % num)
|
125 |
+
div = (num - 1) if endpoint else num
|
126 |
+
|
127 |
+
# Convert float/complex array scalars to float, gh-3504
|
128 |
+
# and make sure one can use variables that have an __array_interface__, gh-6634
|
129 |
+
start = asanyarray(start) * 1.0
|
130 |
+
stop = asanyarray(stop) * 1.0
|
131 |
+
|
132 |
+
dt = result_type(start, stop, float(num))
|
133 |
+
if dtype is None:
|
134 |
+
dtype = dt
|
135 |
+
integer_dtype = False
|
136 |
+
else:
|
137 |
+
integer_dtype = _nx.issubdtype(dtype, _nx.integer)
|
138 |
+
|
139 |
+
delta = stop - start
|
140 |
+
y = _nx.arange(0, num, dtype=dt).reshape((-1,) + (1,) * ndim(delta))
|
141 |
+
# In-place multiplication y *= delta/div is faster, but prevents the multiplicant
|
142 |
+
# from overriding what class is produced, and thus prevents, e.g. use of Quantities,
|
143 |
+
# see gh-7142. Hence, we multiply in place only for standard scalar types.
|
144 |
+
if div > 0:
|
145 |
+
_mult_inplace = _nx.isscalar(delta)
|
146 |
+
step = delta / div
|
147 |
+
any_step_zero = (
|
148 |
+
step == 0 if _mult_inplace else _nx.asanyarray(step == 0).any())
|
149 |
+
if any_step_zero:
|
150 |
+
# Special handling for denormal numbers, gh-5437
|
151 |
+
y /= div
|
152 |
+
if _mult_inplace:
|
153 |
+
y *= delta
|
154 |
+
else:
|
155 |
+
y = y * delta
|
156 |
+
else:
|
157 |
+
if _mult_inplace:
|
158 |
+
y *= step
|
159 |
+
else:
|
160 |
+
y = y * step
|
161 |
+
else:
|
162 |
+
# sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
|
163 |
+
# have an undefined step
|
164 |
+
step = NaN
|
165 |
+
# Multiply with delta to allow possible override of output class.
|
166 |
+
y = y * delta
|
167 |
+
|
168 |
+
y += start
|
169 |
+
|
170 |
+
if endpoint and num > 1:
|
171 |
+
y[-1, ...] = stop
|
172 |
+
|
173 |
+
if axis != 0:
|
174 |
+
y = _nx.moveaxis(y, 0, axis)
|
175 |
+
|
176 |
+
if integer_dtype:
|
177 |
+
_nx.floor(y, out=y)
|
178 |
+
|
179 |
+
if retstep:
|
180 |
+
return y.astype(dtype, copy=False), step
|
181 |
+
else:
|
182 |
+
return y.astype(dtype, copy=False)
|
183 |
+
|
184 |
+
|
185 |
+
def _logspace_dispatcher(start, stop, num=None, endpoint=None, base=None,
|
186 |
+
dtype=None, axis=None):
|
187 |
+
return (start, stop, base)
|
188 |
+
|
189 |
+
|
190 |
+
@array_function_dispatch(_logspace_dispatcher)
|
191 |
+
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None,
|
192 |
+
axis=0):
|
193 |
+
"""
|
194 |
+
Return numbers spaced evenly on a log scale.
|
195 |
+
|
196 |
+
In linear space, the sequence starts at ``base ** start``
|
197 |
+
(`base` to the power of `start`) and ends with ``base ** stop``
|
198 |
+
(see `endpoint` below).
|
199 |
+
|
200 |
+
.. versionchanged:: 1.16.0
|
201 |
+
Non-scalar `start` and `stop` are now supported.
|
202 |
+
|
203 |
+
.. versionchanged:: 1.25.0
|
204 |
+
Non-scalar 'base` is now supported
|
205 |
+
|
206 |
+
Parameters
|
207 |
+
----------
|
208 |
+
start : array_like
|
209 |
+
``base ** start`` is the starting value of the sequence.
|
210 |
+
stop : array_like
|
211 |
+
``base ** stop`` is the final value of the sequence, unless `endpoint`
|
212 |
+
is False. In that case, ``num + 1`` values are spaced over the
|
213 |
+
interval in log-space, of which all but the last (a sequence of
|
214 |
+
length `num`) are returned.
|
215 |
+
num : integer, optional
|
216 |
+
Number of samples to generate. Default is 50.
|
217 |
+
endpoint : boolean, optional
|
218 |
+
If true, `stop` is the last sample. Otherwise, it is not included.
|
219 |
+
Default is True.
|
220 |
+
base : array_like, optional
|
221 |
+
The base of the log space. The step size between the elements in
|
222 |
+
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
|
223 |
+
Default is 10.0.
|
224 |
+
dtype : dtype
|
225 |
+
The type of the output array. If `dtype` is not given, the data type
|
226 |
+
is inferred from `start` and `stop`. The inferred type will never be
|
227 |
+
an integer; `float` is chosen even if the arguments would produce an
|
228 |
+
array of integers.
|
229 |
+
axis : int, optional
|
230 |
+
The axis in the result to store the samples. Relevant only if start,
|
231 |
+
stop, or base are array-like. By default (0), the samples will be
|
232 |
+
along a new axis inserted at the beginning. Use -1 to get an axis at
|
233 |
+
the end.
|
234 |
+
|
235 |
+
.. versionadded:: 1.16.0
|
236 |
+
|
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 |
+
>>> np.logspace(2.0, 3.0, num=4)
|
265 |
+
array([ 100. , 215.443469 , 464.15888336, 1000. ])
|
266 |
+
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
|
267 |
+
array([100. , 177.827941 , 316.22776602, 562.34132519])
|
268 |
+
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
|
269 |
+
array([4. , 5.0396842 , 6.34960421, 8. ])
|
270 |
+
>>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
|
271 |
+
array([[ 4. , 5.0396842 , 6.34960421, 8. ],
|
272 |
+
[ 9. , 12.98024613, 18.72075441, 27. ]])
|
273 |
+
|
274 |
+
Graphical illustration:
|
275 |
+
|
276 |
+
>>> import matplotlib.pyplot as plt
|
277 |
+
>>> N = 10
|
278 |
+
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
|
279 |
+
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
|
280 |
+
>>> y = np.zeros(N)
|
281 |
+
>>> plt.plot(x1, y, 'o')
|
282 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
283 |
+
>>> plt.plot(x2, y + 0.5, 'o')
|
284 |
+
[<matplotlib.lines.Line2D object at 0x...>]
|
285 |
+
>>> plt.ylim([-0.5, 1])
|
286 |
+
(-0.5, 1)
|
287 |
+
>>> plt.show()
|
288 |
+
|
289 |
+
"""
|
290 |
+
ndmax = np.broadcast(start, stop, base).ndim
|
291 |
+
start, stop, base = (
|
292 |
+
np.array(a, copy=False, subok=True, ndmin=ndmax)
|
293 |
+
for a in (start, stop, base)
|
294 |
+
)
|
295 |
+
y = linspace(start, stop, num=num, endpoint=endpoint, axis=axis)
|
296 |
+
base = np.expand_dims(base, axis=axis)
|
297 |
+
if dtype is None:
|
298 |
+
return _nx.power(base, y)
|
299 |
+
return _nx.power(base, y).astype(dtype, copy=False)
|
300 |
+
|
301 |
+
|
302 |
+
def _geomspace_dispatcher(start, stop, num=None, endpoint=None, dtype=None,
|
303 |
+
axis=None):
|
304 |
+
return (start, stop)
|
305 |
+
|
306 |
+
|
307 |
+
@array_function_dispatch(_geomspace_dispatcher)
|
308 |
+
def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
|
309 |
+
"""
|
310 |
+
Return numbers spaced evenly on a log scale (a geometric progression).
|
311 |
+
|
312 |
+
This is similar to `logspace`, but with endpoints specified directly.
|
313 |
+
Each output sample is a constant multiple of the previous.
|
314 |
+
|
315 |
+
.. versionchanged:: 1.16.0
|
316 |
+
Non-scalar `start` and `stop` are now supported.
|
317 |
+
|
318 |
+
Parameters
|
319 |
+
----------
|
320 |
+
start : array_like
|
321 |
+
The starting value of the sequence.
|
322 |
+
stop : array_like
|
323 |
+
The final value of the sequence, unless `endpoint` is False.
|
324 |
+
In that case, ``num + 1`` values are spaced over the
|
325 |
+
interval in log-space, of which all but the last (a sequence of
|
326 |
+
length `num`) are returned.
|
327 |
+
num : integer, optional
|
328 |
+
Number of samples to generate. Default is 50.
|
329 |
+
endpoint : boolean, optional
|
330 |
+
If true, `stop` is the last sample. Otherwise, it is not included.
|
331 |
+
Default is True.
|
332 |
+
dtype : dtype
|
333 |
+
The type of the output array. If `dtype` is not given, the data type
|
334 |
+
is inferred from `start` and `stop`. The inferred dtype will never be
|
335 |
+
an integer; `float` is chosen even if the arguments would produce an
|
336 |
+
array of integers.
|
337 |
+
axis : int, optional
|
338 |
+
The axis in the result to store the samples. Relevant only if start
|
339 |
+
or stop are array-like. By default (0), the samples will be along a
|
340 |
+
new axis inserted at the beginning. Use -1 to get an axis at the end.
|
341 |
+
|
342 |
+
.. versionadded:: 1.16.0
|
343 |
+
|
344 |
+
Returns
|
345 |
+
-------
|
346 |
+
samples : ndarray
|
347 |
+
`num` samples, equally spaced on a log scale.
|
348 |
+
|
349 |
+
See Also
|
350 |
+
--------
|
351 |
+
logspace : Similar to geomspace, but with endpoints specified using log
|
352 |
+
and base.
|
353 |
+
linspace : Similar to geomspace, but with arithmetic instead of geometric
|
354 |
+
progression.
|
355 |
+
arange : Similar to linspace, with the step size specified instead of the
|
356 |
+
number of samples.
|
357 |
+
:ref:`how-to-partition`
|
358 |
+
|
359 |
+
Notes
|
360 |
+
-----
|
361 |
+
If the inputs or dtype are complex, the output will follow a logarithmic
|
362 |
+
spiral in the complex plane. (There are an infinite number of spirals
|
363 |
+
passing through two points; the output will follow the shortest such path.)
|
364 |
+
|
365 |
+
Examples
|
366 |
+
--------
|
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 |
+
out_sign = _nx.ones(_nx.broadcast(start, stop).shape, dt)
|
430 |
+
# Avoid negligible real or imaginary parts in output by rotating to
|
431 |
+
# positive real, calculating, then undoing rotation
|
432 |
+
if _nx.issubdtype(dt, _nx.complexfloating):
|
433 |
+
all_imag = (start.real == 0.) & (stop.real == 0.)
|
434 |
+
if _nx.any(all_imag):
|
435 |
+
start[all_imag] = start[all_imag].imag
|
436 |
+
stop[all_imag] = stop[all_imag].imag
|
437 |
+
out_sign[all_imag] = 1j
|
438 |
+
|
439 |
+
both_negative = (_nx.sign(start) == -1) & (_nx.sign(stop) == -1)
|
440 |
+
if _nx.any(both_negative):
|
441 |
+
_nx.negative(start, out=start, where=both_negative)
|
442 |
+
_nx.negative(stop, out=stop, where=both_negative)
|
443 |
+
_nx.negative(out_sign, out=out_sign, where=both_negative)
|
444 |
+
|
445 |
+
log_start = _nx.log10(start)
|
446 |
+
log_stop = _nx.log10(stop)
|
447 |
+
result = logspace(log_start, log_stop, num=num,
|
448 |
+
endpoint=endpoint, base=10.0, dtype=dtype)
|
449 |
+
|
450 |
+
# Make sure the endpoints match the start and stop arguments. This is
|
451 |
+
# necessary because np.exp(np.log(x)) is not necessarily equal to x.
|
452 |
+
if num > 0:
|
453 |
+
result[0] = start
|
454 |
+
if num > 1 and endpoint:
|
455 |
+
result[-1] = stop
|
456 |
+
|
457 |
+
result = out_sign * result
|
458 |
+
|
459 |
+
if axis != 0:
|
460 |
+
result = _nx.moveaxis(result, 0, axis)
|
461 |
+
|
462 |
+
return result.astype(dtype, copy=False)
|
463 |
+
|
464 |
+
|
465 |
+
def _needs_add_docstring(obj):
|
466 |
+
"""
|
467 |
+
Returns true if the only way to set the docstring of `obj` from python is
|
468 |
+
via add_docstring.
|
469 |
+
|
470 |
+
This function errs on the side of being overly conservative.
|
471 |
+
"""
|
472 |
+
Py_TPFLAGS_HEAPTYPE = 1 << 9
|
473 |
+
|
474 |
+
if isinstance(obj, (types.FunctionType, types.MethodType, property)):
|
475 |
+
return False
|
476 |
+
|
477 |
+
if isinstance(obj, type) and obj.__flags__ & Py_TPFLAGS_HEAPTYPE:
|
478 |
+
return False
|
479 |
+
|
480 |
+
return True
|
481 |
+
|
482 |
+
|
483 |
+
def _add_docstring(obj, doc, warn_on_python):
|
484 |
+
if warn_on_python and not _needs_add_docstring(obj):
|
485 |
+
warnings.warn(
|
486 |
+
"add_newdoc was used on a pure-python object {}. "
|
487 |
+
"Prefer to attach it directly to the source."
|
488 |
+
.format(obj),
|
489 |
+
UserWarning,
|
490 |
+
stacklevel=3)
|
491 |
+
try:
|
492 |
+
add_docstring(obj, doc)
|
493 |
+
except Exception:
|
494 |
+
pass
|
495 |
+
|
496 |
+
|
497 |
+
def add_newdoc(place, obj, doc, warn_on_python=True):
|
498 |
+
"""
|
499 |
+
Add documentation to an existing object, typically one defined in C
|
500 |
+
|
501 |
+
The purpose is to allow easier editing of the docstrings without requiring
|
502 |
+
a re-compile. This exists primarily for internal use within numpy itself.
|
503 |
+
|
504 |
+
Parameters
|
505 |
+
----------
|
506 |
+
place : str
|
507 |
+
The absolute name of the module to import from
|
508 |
+
obj : str
|
509 |
+
The name of the object to add documentation to, typically a class or
|
510 |
+
function name
|
511 |
+
doc : {str, Tuple[str, str], List[Tuple[str, str]]}
|
512 |
+
If a string, the documentation to apply to `obj`
|
513 |
+
|
514 |
+
If a tuple, then the first element is interpreted as an attribute of
|
515 |
+
`obj` and the second as the docstring to apply - ``(method, docstring)``
|
516 |
+
|
517 |
+
If a list, then each element of the list should be a tuple of length
|
518 |
+
two - ``[(method1, docstring1), (method2, docstring2), ...]``
|
519 |
+
warn_on_python : bool
|
520 |
+
If True, the default, emit `UserWarning` if this is used to attach
|
521 |
+
documentation to a pure-python object.
|
522 |
+
|
523 |
+
Notes
|
524 |
+
-----
|
525 |
+
This routine never raises an error if the docstring can't be written, but
|
526 |
+
will raise an error if the object being documented does not exist.
|
527 |
+
|
528 |
+
This routine cannot modify read-only docstrings, as appear
|
529 |
+
in new-style classes or built-in functions. Because this
|
530 |
+
routine never raises an error the caller must check manually
|
531 |
+
that the docstrings were changed.
|
532 |
+
|
533 |
+
Since this function grabs the ``char *`` from a c-level str object and puts
|
534 |
+
it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
|
535 |
+
C-API best-practices, by:
|
536 |
+
|
537 |
+
- modifying a `PyTypeObject` after calling `PyType_Ready`
|
538 |
+
- calling `Py_INCREF` on the str and losing the reference, so the str
|
539 |
+
will never be released
|
540 |
+
|
541 |
+
If possible it should be avoided.
|
542 |
+
"""
|
543 |
+
new = getattr(__import__(place, globals(), {}, [obj]), obj)
|
544 |
+
if isinstance(doc, str):
|
545 |
+
_add_docstring(new, doc.strip(), warn_on_python)
|
546 |
+
elif isinstance(doc, tuple):
|
547 |
+
attr, docstring = doc
|
548 |
+
_add_docstring(getattr(new, attr), docstring.strip(), warn_on_python)
|
549 |
+
elif isinstance(doc, list):
|
550 |
+
for attr, docstring in doc:
|
551 |
+
_add_docstring(getattr(new, attr), docstring.strip(), warn_on_python)
|
env-llmeval/lib/python3.10/site-packages/numpy/core/function_base.pyi
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import (
|
2 |
+
Literal as L,
|
3 |
+
overload,
|
4 |
+
Any,
|
5 |
+
SupportsIndex,
|
6 |
+
TypeVar,
|
7 |
+
)
|
8 |
+
|
9 |
+
from numpy import floating, complexfloating, generic
|
10 |
+
from numpy._typing import (
|
11 |
+
NDArray,
|
12 |
+
DTypeLike,
|
13 |
+
_DTypeLike,
|
14 |
+
_ArrayLikeFloat_co,
|
15 |
+
_ArrayLikeComplex_co,
|
16 |
+
)
|
17 |
+
|
18 |
+
_SCT = TypeVar("_SCT", bound=generic)
|
19 |
+
|
20 |
+
__all__: list[str]
|
21 |
+
|
22 |
+
@overload
|
23 |
+
def linspace(
|
24 |
+
start: _ArrayLikeFloat_co,
|
25 |
+
stop: _ArrayLikeFloat_co,
|
26 |
+
num: SupportsIndex = ...,
|
27 |
+
endpoint: bool = ...,
|
28 |
+
retstep: L[False] = ...,
|
29 |
+
dtype: None = ...,
|
30 |
+
axis: SupportsIndex = ...,
|
31 |
+
) -> NDArray[floating[Any]]: ...
|
32 |
+
@overload
|
33 |
+
def linspace(
|
34 |
+
start: _ArrayLikeComplex_co,
|
35 |
+
stop: _ArrayLikeComplex_co,
|
36 |
+
num: SupportsIndex = ...,
|
37 |
+
endpoint: bool = ...,
|
38 |
+
retstep: L[False] = ...,
|
39 |
+
dtype: None = ...,
|
40 |
+
axis: SupportsIndex = ...,
|
41 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
42 |
+
@overload
|
43 |
+
def linspace(
|
44 |
+
start: _ArrayLikeComplex_co,
|
45 |
+
stop: _ArrayLikeComplex_co,
|
46 |
+
num: SupportsIndex = ...,
|
47 |
+
endpoint: bool = ...,
|
48 |
+
retstep: L[False] = ...,
|
49 |
+
dtype: _DTypeLike[_SCT] = ...,
|
50 |
+
axis: SupportsIndex = ...,
|
51 |
+
) -> NDArray[_SCT]: ...
|
52 |
+
@overload
|
53 |
+
def linspace(
|
54 |
+
start: _ArrayLikeComplex_co,
|
55 |
+
stop: _ArrayLikeComplex_co,
|
56 |
+
num: SupportsIndex = ...,
|
57 |
+
endpoint: bool = ...,
|
58 |
+
retstep: L[False] = ...,
|
59 |
+
dtype: DTypeLike = ...,
|
60 |
+
axis: SupportsIndex = ...,
|
61 |
+
) -> NDArray[Any]: ...
|
62 |
+
@overload
|
63 |
+
def linspace(
|
64 |
+
start: _ArrayLikeFloat_co,
|
65 |
+
stop: _ArrayLikeFloat_co,
|
66 |
+
num: SupportsIndex = ...,
|
67 |
+
endpoint: bool = ...,
|
68 |
+
retstep: L[True] = ...,
|
69 |
+
dtype: None = ...,
|
70 |
+
axis: SupportsIndex = ...,
|
71 |
+
) -> tuple[NDArray[floating[Any]], floating[Any]]: ...
|
72 |
+
@overload
|
73 |
+
def linspace(
|
74 |
+
start: _ArrayLikeComplex_co,
|
75 |
+
stop: _ArrayLikeComplex_co,
|
76 |
+
num: SupportsIndex = ...,
|
77 |
+
endpoint: bool = ...,
|
78 |
+
retstep: L[True] = ...,
|
79 |
+
dtype: None = ...,
|
80 |
+
axis: SupportsIndex = ...,
|
81 |
+
) -> tuple[NDArray[complexfloating[Any, Any]], complexfloating[Any, Any]]: ...
|
82 |
+
@overload
|
83 |
+
def linspace(
|
84 |
+
start: _ArrayLikeComplex_co,
|
85 |
+
stop: _ArrayLikeComplex_co,
|
86 |
+
num: SupportsIndex = ...,
|
87 |
+
endpoint: bool = ...,
|
88 |
+
retstep: L[True] = ...,
|
89 |
+
dtype: _DTypeLike[_SCT] = ...,
|
90 |
+
axis: SupportsIndex = ...,
|
91 |
+
) -> tuple[NDArray[_SCT], _SCT]: ...
|
92 |
+
@overload
|
93 |
+
def linspace(
|
94 |
+
start: _ArrayLikeComplex_co,
|
95 |
+
stop: _ArrayLikeComplex_co,
|
96 |
+
num: SupportsIndex = ...,
|
97 |
+
endpoint: bool = ...,
|
98 |
+
retstep: L[True] = ...,
|
99 |
+
dtype: DTypeLike = ...,
|
100 |
+
axis: SupportsIndex = ...,
|
101 |
+
) -> tuple[NDArray[Any], Any]: ...
|
102 |
+
|
103 |
+
@overload
|
104 |
+
def logspace(
|
105 |
+
start: _ArrayLikeFloat_co,
|
106 |
+
stop: _ArrayLikeFloat_co,
|
107 |
+
num: SupportsIndex = ...,
|
108 |
+
endpoint: bool = ...,
|
109 |
+
base: _ArrayLikeFloat_co = ...,
|
110 |
+
dtype: None = ...,
|
111 |
+
axis: SupportsIndex = ...,
|
112 |
+
) -> NDArray[floating[Any]]: ...
|
113 |
+
@overload
|
114 |
+
def logspace(
|
115 |
+
start: _ArrayLikeComplex_co,
|
116 |
+
stop: _ArrayLikeComplex_co,
|
117 |
+
num: SupportsIndex = ...,
|
118 |
+
endpoint: bool = ...,
|
119 |
+
base: _ArrayLikeComplex_co = ...,
|
120 |
+
dtype: None = ...,
|
121 |
+
axis: SupportsIndex = ...,
|
122 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
123 |
+
@overload
|
124 |
+
def logspace(
|
125 |
+
start: _ArrayLikeComplex_co,
|
126 |
+
stop: _ArrayLikeComplex_co,
|
127 |
+
num: SupportsIndex = ...,
|
128 |
+
endpoint: bool = ...,
|
129 |
+
base: _ArrayLikeComplex_co = ...,
|
130 |
+
dtype: _DTypeLike[_SCT] = ...,
|
131 |
+
axis: SupportsIndex = ...,
|
132 |
+
) -> NDArray[_SCT]: ...
|
133 |
+
@overload
|
134 |
+
def logspace(
|
135 |
+
start: _ArrayLikeComplex_co,
|
136 |
+
stop: _ArrayLikeComplex_co,
|
137 |
+
num: SupportsIndex = ...,
|
138 |
+
endpoint: bool = ...,
|
139 |
+
base: _ArrayLikeComplex_co = ...,
|
140 |
+
dtype: DTypeLike = ...,
|
141 |
+
axis: SupportsIndex = ...,
|
142 |
+
) -> NDArray[Any]: ...
|
143 |
+
|
144 |
+
@overload
|
145 |
+
def geomspace(
|
146 |
+
start: _ArrayLikeFloat_co,
|
147 |
+
stop: _ArrayLikeFloat_co,
|
148 |
+
num: SupportsIndex = ...,
|
149 |
+
endpoint: bool = ...,
|
150 |
+
dtype: None = ...,
|
151 |
+
axis: SupportsIndex = ...,
|
152 |
+
) -> NDArray[floating[Any]]: ...
|
153 |
+
@overload
|
154 |
+
def geomspace(
|
155 |
+
start: _ArrayLikeComplex_co,
|
156 |
+
stop: _ArrayLikeComplex_co,
|
157 |
+
num: SupportsIndex = ...,
|
158 |
+
endpoint: bool = ...,
|
159 |
+
dtype: None = ...,
|
160 |
+
axis: SupportsIndex = ...,
|
161 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
162 |
+
@overload
|
163 |
+
def geomspace(
|
164 |
+
start: _ArrayLikeComplex_co,
|
165 |
+
stop: _ArrayLikeComplex_co,
|
166 |
+
num: SupportsIndex = ...,
|
167 |
+
endpoint: bool = ...,
|
168 |
+
dtype: _DTypeLike[_SCT] = ...,
|
169 |
+
axis: SupportsIndex = ...,
|
170 |
+
) -> NDArray[_SCT]: ...
|
171 |
+
@overload
|
172 |
+
def geomspace(
|
173 |
+
start: _ArrayLikeComplex_co,
|
174 |
+
stop: _ArrayLikeComplex_co,
|
175 |
+
num: SupportsIndex = ...,
|
176 |
+
endpoint: bool = ...,
|
177 |
+
dtype: DTypeLike = ...,
|
178 |
+
axis: SupportsIndex = ...,
|
179 |
+
) -> NDArray[Any]: ...
|
180 |
+
|
181 |
+
# Re-exported to `np.lib.function_base`
|
182 |
+
def add_newdoc(
|
183 |
+
place: str,
|
184 |
+
obj: str,
|
185 |
+
doc: str | tuple[str, str] | list[tuple[str, str]],
|
186 |
+
warn_on_python: bool = ...,
|
187 |
+
) -> None: ...
|
env-llmeval/lib/python3.10/site-packages/numpy/core/lib/libnpymath.a
ADDED
Binary file (94 kB). View file
|
|