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/_utils/__init__.py +29 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_pep440.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/_convertions.py +18 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/_inspect.py +191 -0
- env-llmeval/lib/python3.10/site-packages/numpy/_utils/_pep440.py +487 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_array_object.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_constants.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_creation_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_data_type_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_dtypes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_elementwise_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_indexing_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_manipulation_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_searching_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_set_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_sorting_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_statistical_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_typing.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_utility_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/linalg.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/setup.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_array_object.py +1133 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_data_type_functions.py +197 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_dtypes.py +180 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_manipulation_functions.py +112 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_searching_functions.py +51 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_sorting_functions.py +54 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_typing.py +76 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_utility_functions.py +37 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__init__.py +7 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_array_object.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_creation_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_data_type_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_elementwise_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_indexing_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_manipulation_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_set_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_sorting_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_validation.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_array_object.py +395 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_creation_functions.py +142 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_data_type_functions.py +31 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_elementwise_functions.py +114 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_indexing_functions.py +24 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_manipulation_functions.py +37 -0
env-llmeval/lib/python3.10/site-packages/numpy/_utils/__init__.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This is a module for defining private helpers which do not depend on the
|
3 |
+
rest of NumPy.
|
4 |
+
|
5 |
+
Everything in here must be self-contained so that it can be
|
6 |
+
imported anywhere else without creating circular imports.
|
7 |
+
If a utility requires the import of NumPy, it probably belongs
|
8 |
+
in ``numpy.core``.
|
9 |
+
"""
|
10 |
+
|
11 |
+
from ._convertions import asunicode, asbytes
|
12 |
+
|
13 |
+
|
14 |
+
def set_module(module):
|
15 |
+
"""Private decorator for overriding __module__ on a function or class.
|
16 |
+
|
17 |
+
Example usage::
|
18 |
+
|
19 |
+
@set_module('numpy')
|
20 |
+
def example():
|
21 |
+
pass
|
22 |
+
|
23 |
+
assert example.__module__ == 'numpy'
|
24 |
+
"""
|
25 |
+
def decorator(func):
|
26 |
+
if module is not None:
|
27 |
+
func.__module__ = module
|
28 |
+
return func
|
29 |
+
return decorator
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.04 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_convertions.cpython-310.pyc
ADDED
Binary file (619 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_inspect.cpython-310.pyc
ADDED
Binary file (7.62 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/__pycache__/_pep440.cpython-310.pyc
ADDED
Binary file (12.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/_convertions.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A set of methods retained from np.compat module that
|
3 |
+
are still used across codebase.
|
4 |
+
"""
|
5 |
+
|
6 |
+
__all__ = ["asunicode", "asbytes"]
|
7 |
+
|
8 |
+
|
9 |
+
def asunicode(s):
|
10 |
+
if isinstance(s, bytes):
|
11 |
+
return s.decode('latin1')
|
12 |
+
return str(s)
|
13 |
+
|
14 |
+
|
15 |
+
def asbytes(s):
|
16 |
+
if isinstance(s, bytes):
|
17 |
+
return s
|
18 |
+
return str(s).encode('latin1')
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/_inspect.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Subset of inspect module from upstream python
|
2 |
+
|
3 |
+
We use this instead of upstream because upstream inspect is slow to import, and
|
4 |
+
significantly contributes to numpy import times. Importing this copy has almost
|
5 |
+
no overhead.
|
6 |
+
|
7 |
+
"""
|
8 |
+
import types
|
9 |
+
|
10 |
+
__all__ = ['getargspec', 'formatargspec']
|
11 |
+
|
12 |
+
# ----------------------------------------------------------- type-checking
|
13 |
+
def ismethod(object):
|
14 |
+
"""Return true if the object is an instance method.
|
15 |
+
|
16 |
+
Instance method objects provide these attributes:
|
17 |
+
__doc__ documentation string
|
18 |
+
__name__ name with which this method was defined
|
19 |
+
im_class class object in which this method belongs
|
20 |
+
im_func function object containing implementation of method
|
21 |
+
im_self instance to which this method is bound, or None
|
22 |
+
|
23 |
+
"""
|
24 |
+
return isinstance(object, types.MethodType)
|
25 |
+
|
26 |
+
def isfunction(object):
|
27 |
+
"""Return true if the object is a user-defined function.
|
28 |
+
|
29 |
+
Function objects provide these attributes:
|
30 |
+
__doc__ documentation string
|
31 |
+
__name__ name with which this function was defined
|
32 |
+
func_code code object containing compiled function bytecode
|
33 |
+
func_defaults tuple of any default values for arguments
|
34 |
+
func_doc (same as __doc__)
|
35 |
+
func_globals global namespace in which this function was defined
|
36 |
+
func_name (same as __name__)
|
37 |
+
|
38 |
+
"""
|
39 |
+
return isinstance(object, types.FunctionType)
|
40 |
+
|
41 |
+
def iscode(object):
|
42 |
+
"""Return true if the object is a code object.
|
43 |
+
|
44 |
+
Code objects provide these attributes:
|
45 |
+
co_argcount number of arguments (not including * or ** args)
|
46 |
+
co_code string of raw compiled bytecode
|
47 |
+
co_consts tuple of constants used in the bytecode
|
48 |
+
co_filename name of file in which this code object was created
|
49 |
+
co_firstlineno number of first line in Python source code
|
50 |
+
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
|
51 |
+
co_lnotab encoded mapping of line numbers to bytecode indices
|
52 |
+
co_name name with which this code object was defined
|
53 |
+
co_names tuple of names of local variables
|
54 |
+
co_nlocals number of local variables
|
55 |
+
co_stacksize virtual machine stack space required
|
56 |
+
co_varnames tuple of names of arguments and local variables
|
57 |
+
|
58 |
+
"""
|
59 |
+
return isinstance(object, types.CodeType)
|
60 |
+
|
61 |
+
# ------------------------------------------------ argument list extraction
|
62 |
+
# These constants are from Python's compile.h.
|
63 |
+
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
|
64 |
+
|
65 |
+
def getargs(co):
|
66 |
+
"""Get information about the arguments accepted by a code object.
|
67 |
+
|
68 |
+
Three things are returned: (args, varargs, varkw), where 'args' is
|
69 |
+
a list of argument names (possibly containing nested lists), and
|
70 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
71 |
+
|
72 |
+
"""
|
73 |
+
|
74 |
+
if not iscode(co):
|
75 |
+
raise TypeError('arg is not a code object')
|
76 |
+
|
77 |
+
nargs = co.co_argcount
|
78 |
+
names = co.co_varnames
|
79 |
+
args = list(names[:nargs])
|
80 |
+
|
81 |
+
# The following acrobatics are for anonymous (tuple) arguments.
|
82 |
+
# Which we do not need to support, so remove to avoid importing
|
83 |
+
# the dis module.
|
84 |
+
for i in range(nargs):
|
85 |
+
if args[i][:1] in ['', '.']:
|
86 |
+
raise TypeError("tuple function arguments are not supported")
|
87 |
+
varargs = None
|
88 |
+
if co.co_flags & CO_VARARGS:
|
89 |
+
varargs = co.co_varnames[nargs]
|
90 |
+
nargs = nargs + 1
|
91 |
+
varkw = None
|
92 |
+
if co.co_flags & CO_VARKEYWORDS:
|
93 |
+
varkw = co.co_varnames[nargs]
|
94 |
+
return args, varargs, varkw
|
95 |
+
|
96 |
+
def getargspec(func):
|
97 |
+
"""Get the names and default values of a function's arguments.
|
98 |
+
|
99 |
+
A tuple of four things is returned: (args, varargs, varkw, defaults).
|
100 |
+
'args' is a list of the argument names (it may contain nested lists).
|
101 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
102 |
+
'defaults' is an n-tuple of the default values of the last n arguments.
|
103 |
+
|
104 |
+
"""
|
105 |
+
|
106 |
+
if ismethod(func):
|
107 |
+
func = func.__func__
|
108 |
+
if not isfunction(func):
|
109 |
+
raise TypeError('arg is not a Python function')
|
110 |
+
args, varargs, varkw = getargs(func.__code__)
|
111 |
+
return args, varargs, varkw, func.__defaults__
|
112 |
+
|
113 |
+
def getargvalues(frame):
|
114 |
+
"""Get information about arguments passed into a particular frame.
|
115 |
+
|
116 |
+
A tuple of four things is returned: (args, varargs, varkw, locals).
|
117 |
+
'args' is a list of the argument names (it may contain nested lists).
|
118 |
+
'varargs' and 'varkw' are the names of the * and ** arguments or None.
|
119 |
+
'locals' is the locals dictionary of the given frame.
|
120 |
+
|
121 |
+
"""
|
122 |
+
args, varargs, varkw = getargs(frame.f_code)
|
123 |
+
return args, varargs, varkw, frame.f_locals
|
124 |
+
|
125 |
+
def joinseq(seq):
|
126 |
+
if len(seq) == 1:
|
127 |
+
return '(' + seq[0] + ',)'
|
128 |
+
else:
|
129 |
+
return '(' + ', '.join(seq) + ')'
|
130 |
+
|
131 |
+
def strseq(object, convert, join=joinseq):
|
132 |
+
"""Recursively walk a sequence, stringifying each element.
|
133 |
+
|
134 |
+
"""
|
135 |
+
if type(object) in [list, tuple]:
|
136 |
+
return join([strseq(_o, convert, join) for _o in object])
|
137 |
+
else:
|
138 |
+
return convert(object)
|
139 |
+
|
140 |
+
def formatargspec(args, varargs=None, varkw=None, defaults=None,
|
141 |
+
formatarg=str,
|
142 |
+
formatvarargs=lambda name: '*' + name,
|
143 |
+
formatvarkw=lambda name: '**' + name,
|
144 |
+
formatvalue=lambda value: '=' + repr(value),
|
145 |
+
join=joinseq):
|
146 |
+
"""Format an argument spec from the 4 values returned by getargspec.
|
147 |
+
|
148 |
+
The first four arguments are (args, varargs, varkw, defaults). The
|
149 |
+
other four arguments are the corresponding optional formatting functions
|
150 |
+
that are called to turn names and values into strings. The ninth
|
151 |
+
argument is an optional function to format the sequence of arguments.
|
152 |
+
|
153 |
+
"""
|
154 |
+
specs = []
|
155 |
+
if defaults:
|
156 |
+
firstdefault = len(args) - len(defaults)
|
157 |
+
for i in range(len(args)):
|
158 |
+
spec = strseq(args[i], formatarg, join)
|
159 |
+
if defaults and i >= firstdefault:
|
160 |
+
spec = spec + formatvalue(defaults[i - firstdefault])
|
161 |
+
specs.append(spec)
|
162 |
+
if varargs is not None:
|
163 |
+
specs.append(formatvarargs(varargs))
|
164 |
+
if varkw is not None:
|
165 |
+
specs.append(formatvarkw(varkw))
|
166 |
+
return '(' + ', '.join(specs) + ')'
|
167 |
+
|
168 |
+
def formatargvalues(args, varargs, varkw, locals,
|
169 |
+
formatarg=str,
|
170 |
+
formatvarargs=lambda name: '*' + name,
|
171 |
+
formatvarkw=lambda name: '**' + name,
|
172 |
+
formatvalue=lambda value: '=' + repr(value),
|
173 |
+
join=joinseq):
|
174 |
+
"""Format an argument spec from the 4 values returned by getargvalues.
|
175 |
+
|
176 |
+
The first four arguments are (args, varargs, varkw, locals). The
|
177 |
+
next four arguments are the corresponding optional formatting functions
|
178 |
+
that are called to turn names and values into strings. The ninth
|
179 |
+
argument is an optional function to format the sequence of arguments.
|
180 |
+
|
181 |
+
"""
|
182 |
+
def convert(name, locals=locals,
|
183 |
+
formatarg=formatarg, formatvalue=formatvalue):
|
184 |
+
return formatarg(name) + formatvalue(locals[name])
|
185 |
+
specs = [strseq(arg, convert, join) for arg in args]
|
186 |
+
|
187 |
+
if varargs:
|
188 |
+
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
|
189 |
+
if varkw:
|
190 |
+
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
|
191 |
+
return '(' + ', '.join(specs) + ')'
|
env-llmeval/lib/python3.10/site-packages/numpy/_utils/_pep440.py
ADDED
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Utility to compare pep440 compatible version strings.
|
2 |
+
|
3 |
+
The LooseVersion and StrictVersion classes that distutils provides don't
|
4 |
+
work; they don't recognize anything like alpha/beta/rc/dev versions.
|
5 |
+
"""
|
6 |
+
|
7 |
+
# Copyright (c) Donald Stufft and individual contributors.
|
8 |
+
# All rights reserved.
|
9 |
+
|
10 |
+
# Redistribution and use in source and binary forms, with or without
|
11 |
+
# modification, are permitted provided that the following conditions are met:
|
12 |
+
|
13 |
+
# 1. Redistributions of source code must retain the above copyright notice,
|
14 |
+
# this list of conditions and the following disclaimer.
|
15 |
+
|
16 |
+
# 2. Redistributions in binary form must reproduce the above copyright
|
17 |
+
# notice, this list of conditions and the following disclaimer in the
|
18 |
+
# documentation and/or other materials provided with the distribution.
|
19 |
+
|
20 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
21 |
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
22 |
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
23 |
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
24 |
+
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
25 |
+
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
26 |
+
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
27 |
+
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
28 |
+
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
29 |
+
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
30 |
+
# POSSIBILITY OF SUCH DAMAGE.
|
31 |
+
|
32 |
+
import collections
|
33 |
+
import itertools
|
34 |
+
import re
|
35 |
+
|
36 |
+
|
37 |
+
__all__ = [
|
38 |
+
"parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
|
39 |
+
]
|
40 |
+
|
41 |
+
|
42 |
+
# BEGIN packaging/_structures.py
|
43 |
+
|
44 |
+
|
45 |
+
class Infinity:
|
46 |
+
def __repr__(self):
|
47 |
+
return "Infinity"
|
48 |
+
|
49 |
+
def __hash__(self):
|
50 |
+
return hash(repr(self))
|
51 |
+
|
52 |
+
def __lt__(self, other):
|
53 |
+
return False
|
54 |
+
|
55 |
+
def __le__(self, other):
|
56 |
+
return False
|
57 |
+
|
58 |
+
def __eq__(self, other):
|
59 |
+
return isinstance(other, self.__class__)
|
60 |
+
|
61 |
+
def __ne__(self, other):
|
62 |
+
return not isinstance(other, self.__class__)
|
63 |
+
|
64 |
+
def __gt__(self, other):
|
65 |
+
return True
|
66 |
+
|
67 |
+
def __ge__(self, other):
|
68 |
+
return True
|
69 |
+
|
70 |
+
def __neg__(self):
|
71 |
+
return NegativeInfinity
|
72 |
+
|
73 |
+
|
74 |
+
Infinity = Infinity()
|
75 |
+
|
76 |
+
|
77 |
+
class NegativeInfinity:
|
78 |
+
def __repr__(self):
|
79 |
+
return "-Infinity"
|
80 |
+
|
81 |
+
def __hash__(self):
|
82 |
+
return hash(repr(self))
|
83 |
+
|
84 |
+
def __lt__(self, other):
|
85 |
+
return True
|
86 |
+
|
87 |
+
def __le__(self, other):
|
88 |
+
return True
|
89 |
+
|
90 |
+
def __eq__(self, other):
|
91 |
+
return isinstance(other, self.__class__)
|
92 |
+
|
93 |
+
def __ne__(self, other):
|
94 |
+
return not isinstance(other, self.__class__)
|
95 |
+
|
96 |
+
def __gt__(self, other):
|
97 |
+
return False
|
98 |
+
|
99 |
+
def __ge__(self, other):
|
100 |
+
return False
|
101 |
+
|
102 |
+
def __neg__(self):
|
103 |
+
return Infinity
|
104 |
+
|
105 |
+
|
106 |
+
# BEGIN packaging/version.py
|
107 |
+
|
108 |
+
|
109 |
+
NegativeInfinity = NegativeInfinity()
|
110 |
+
|
111 |
+
_Version = collections.namedtuple(
|
112 |
+
"_Version",
|
113 |
+
["epoch", "release", "dev", "pre", "post", "local"],
|
114 |
+
)
|
115 |
+
|
116 |
+
|
117 |
+
def parse(version):
|
118 |
+
"""
|
119 |
+
Parse the given version string and return either a :class:`Version` object
|
120 |
+
or a :class:`LegacyVersion` object depending on if the given version is
|
121 |
+
a valid PEP 440 version or a legacy version.
|
122 |
+
"""
|
123 |
+
try:
|
124 |
+
return Version(version)
|
125 |
+
except InvalidVersion:
|
126 |
+
return LegacyVersion(version)
|
127 |
+
|
128 |
+
|
129 |
+
class InvalidVersion(ValueError):
|
130 |
+
"""
|
131 |
+
An invalid version was found, users should refer to PEP 440.
|
132 |
+
"""
|
133 |
+
|
134 |
+
|
135 |
+
class _BaseVersion:
|
136 |
+
|
137 |
+
def __hash__(self):
|
138 |
+
return hash(self._key)
|
139 |
+
|
140 |
+
def __lt__(self, other):
|
141 |
+
return self._compare(other, lambda s, o: s < o)
|
142 |
+
|
143 |
+
def __le__(self, other):
|
144 |
+
return self._compare(other, lambda s, o: s <= o)
|
145 |
+
|
146 |
+
def __eq__(self, other):
|
147 |
+
return self._compare(other, lambda s, o: s == o)
|
148 |
+
|
149 |
+
def __ge__(self, other):
|
150 |
+
return self._compare(other, lambda s, o: s >= o)
|
151 |
+
|
152 |
+
def __gt__(self, other):
|
153 |
+
return self._compare(other, lambda s, o: s > o)
|
154 |
+
|
155 |
+
def __ne__(self, other):
|
156 |
+
return self._compare(other, lambda s, o: s != o)
|
157 |
+
|
158 |
+
def _compare(self, other, method):
|
159 |
+
if not isinstance(other, _BaseVersion):
|
160 |
+
return NotImplemented
|
161 |
+
|
162 |
+
return method(self._key, other._key)
|
163 |
+
|
164 |
+
|
165 |
+
class LegacyVersion(_BaseVersion):
|
166 |
+
|
167 |
+
def __init__(self, version):
|
168 |
+
self._version = str(version)
|
169 |
+
self._key = _legacy_cmpkey(self._version)
|
170 |
+
|
171 |
+
def __str__(self):
|
172 |
+
return self._version
|
173 |
+
|
174 |
+
def __repr__(self):
|
175 |
+
return "<LegacyVersion({0})>".format(repr(str(self)))
|
176 |
+
|
177 |
+
@property
|
178 |
+
def public(self):
|
179 |
+
return self._version
|
180 |
+
|
181 |
+
@property
|
182 |
+
def base_version(self):
|
183 |
+
return self._version
|
184 |
+
|
185 |
+
@property
|
186 |
+
def local(self):
|
187 |
+
return None
|
188 |
+
|
189 |
+
@property
|
190 |
+
def is_prerelease(self):
|
191 |
+
return False
|
192 |
+
|
193 |
+
@property
|
194 |
+
def is_postrelease(self):
|
195 |
+
return False
|
196 |
+
|
197 |
+
|
198 |
+
_legacy_version_component_re = re.compile(
|
199 |
+
r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
|
200 |
+
)
|
201 |
+
|
202 |
+
_legacy_version_replacement_map = {
|
203 |
+
"pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
|
204 |
+
}
|
205 |
+
|
206 |
+
|
207 |
+
def _parse_version_parts(s):
|
208 |
+
for part in _legacy_version_component_re.split(s):
|
209 |
+
part = _legacy_version_replacement_map.get(part, part)
|
210 |
+
|
211 |
+
if not part or part == ".":
|
212 |
+
continue
|
213 |
+
|
214 |
+
if part[:1] in "0123456789":
|
215 |
+
# pad for numeric comparison
|
216 |
+
yield part.zfill(8)
|
217 |
+
else:
|
218 |
+
yield "*" + part
|
219 |
+
|
220 |
+
# ensure that alpha/beta/candidate are before final
|
221 |
+
yield "*final"
|
222 |
+
|
223 |
+
|
224 |
+
def _legacy_cmpkey(version):
|
225 |
+
# We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch
|
226 |
+
# greater than or equal to 0. This will effectively put the LegacyVersion,
|
227 |
+
# which uses the defacto standard originally implemented by setuptools,
|
228 |
+
# as before all PEP 440 versions.
|
229 |
+
epoch = -1
|
230 |
+
|
231 |
+
# This scheme is taken from pkg_resources.parse_version setuptools prior to
|
232 |
+
# its adoption of the packaging library.
|
233 |
+
parts = []
|
234 |
+
for part in _parse_version_parts(version.lower()):
|
235 |
+
if part.startswith("*"):
|
236 |
+
# remove "-" before a prerelease tag
|
237 |
+
if part < "*final":
|
238 |
+
while parts and parts[-1] == "*final-":
|
239 |
+
parts.pop()
|
240 |
+
|
241 |
+
# remove trailing zeros from each series of numeric parts
|
242 |
+
while parts and parts[-1] == "00000000":
|
243 |
+
parts.pop()
|
244 |
+
|
245 |
+
parts.append(part)
|
246 |
+
parts = tuple(parts)
|
247 |
+
|
248 |
+
return epoch, parts
|
249 |
+
|
250 |
+
|
251 |
+
# Deliberately not anchored to the start and end of the string, to make it
|
252 |
+
# easier for 3rd party code to reuse
|
253 |
+
VERSION_PATTERN = r"""
|
254 |
+
v?
|
255 |
+
(?:
|
256 |
+
(?:(?P<epoch>[0-9]+)!)? # epoch
|
257 |
+
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
|
258 |
+
(?P<pre> # pre-release
|
259 |
+
[-_\.]?
|
260 |
+
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
|
261 |
+
[-_\.]?
|
262 |
+
(?P<pre_n>[0-9]+)?
|
263 |
+
)?
|
264 |
+
(?P<post> # post release
|
265 |
+
(?:-(?P<post_n1>[0-9]+))
|
266 |
+
|
|
267 |
+
(?:
|
268 |
+
[-_\.]?
|
269 |
+
(?P<post_l>post|rev|r)
|
270 |
+
[-_\.]?
|
271 |
+
(?P<post_n2>[0-9]+)?
|
272 |
+
)
|
273 |
+
)?
|
274 |
+
(?P<dev> # dev release
|
275 |
+
[-_\.]?
|
276 |
+
(?P<dev_l>dev)
|
277 |
+
[-_\.]?
|
278 |
+
(?P<dev_n>[0-9]+)?
|
279 |
+
)?
|
280 |
+
)
|
281 |
+
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
|
282 |
+
"""
|
283 |
+
|
284 |
+
|
285 |
+
class Version(_BaseVersion):
|
286 |
+
|
287 |
+
_regex = re.compile(
|
288 |
+
r"^\s*" + VERSION_PATTERN + r"\s*$",
|
289 |
+
re.VERBOSE | re.IGNORECASE,
|
290 |
+
)
|
291 |
+
|
292 |
+
def __init__(self, version):
|
293 |
+
# Validate the version and parse it into pieces
|
294 |
+
match = self._regex.search(version)
|
295 |
+
if not match:
|
296 |
+
raise InvalidVersion("Invalid version: '{0}'".format(version))
|
297 |
+
|
298 |
+
# Store the parsed out pieces of the version
|
299 |
+
self._version = _Version(
|
300 |
+
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
|
301 |
+
release=tuple(int(i) for i in match.group("release").split(".")),
|
302 |
+
pre=_parse_letter_version(
|
303 |
+
match.group("pre_l"),
|
304 |
+
match.group("pre_n"),
|
305 |
+
),
|
306 |
+
post=_parse_letter_version(
|
307 |
+
match.group("post_l"),
|
308 |
+
match.group("post_n1") or match.group("post_n2"),
|
309 |
+
),
|
310 |
+
dev=_parse_letter_version(
|
311 |
+
match.group("dev_l"),
|
312 |
+
match.group("dev_n"),
|
313 |
+
),
|
314 |
+
local=_parse_local_version(match.group("local")),
|
315 |
+
)
|
316 |
+
|
317 |
+
# Generate a key which will be used for sorting
|
318 |
+
self._key = _cmpkey(
|
319 |
+
self._version.epoch,
|
320 |
+
self._version.release,
|
321 |
+
self._version.pre,
|
322 |
+
self._version.post,
|
323 |
+
self._version.dev,
|
324 |
+
self._version.local,
|
325 |
+
)
|
326 |
+
|
327 |
+
def __repr__(self):
|
328 |
+
return "<Version({0})>".format(repr(str(self)))
|
329 |
+
|
330 |
+
def __str__(self):
|
331 |
+
parts = []
|
332 |
+
|
333 |
+
# Epoch
|
334 |
+
if self._version.epoch != 0:
|
335 |
+
parts.append("{0}!".format(self._version.epoch))
|
336 |
+
|
337 |
+
# Release segment
|
338 |
+
parts.append(".".join(str(x) for x in self._version.release))
|
339 |
+
|
340 |
+
# Pre-release
|
341 |
+
if self._version.pre is not None:
|
342 |
+
parts.append("".join(str(x) for x in self._version.pre))
|
343 |
+
|
344 |
+
# Post-release
|
345 |
+
if self._version.post is not None:
|
346 |
+
parts.append(".post{0}".format(self._version.post[1]))
|
347 |
+
|
348 |
+
# Development release
|
349 |
+
if self._version.dev is not None:
|
350 |
+
parts.append(".dev{0}".format(self._version.dev[1]))
|
351 |
+
|
352 |
+
# Local version segment
|
353 |
+
if self._version.local is not None:
|
354 |
+
parts.append(
|
355 |
+
"+{0}".format(".".join(str(x) for x in self._version.local))
|
356 |
+
)
|
357 |
+
|
358 |
+
return "".join(parts)
|
359 |
+
|
360 |
+
@property
|
361 |
+
def public(self):
|
362 |
+
return str(self).split("+", 1)[0]
|
363 |
+
|
364 |
+
@property
|
365 |
+
def base_version(self):
|
366 |
+
parts = []
|
367 |
+
|
368 |
+
# Epoch
|
369 |
+
if self._version.epoch != 0:
|
370 |
+
parts.append("{0}!".format(self._version.epoch))
|
371 |
+
|
372 |
+
# Release segment
|
373 |
+
parts.append(".".join(str(x) for x in self._version.release))
|
374 |
+
|
375 |
+
return "".join(parts)
|
376 |
+
|
377 |
+
@property
|
378 |
+
def local(self):
|
379 |
+
version_string = str(self)
|
380 |
+
if "+" in version_string:
|
381 |
+
return version_string.split("+", 1)[1]
|
382 |
+
|
383 |
+
@property
|
384 |
+
def is_prerelease(self):
|
385 |
+
return bool(self._version.dev or self._version.pre)
|
386 |
+
|
387 |
+
@property
|
388 |
+
def is_postrelease(self):
|
389 |
+
return bool(self._version.post)
|
390 |
+
|
391 |
+
|
392 |
+
def _parse_letter_version(letter, number):
|
393 |
+
if letter:
|
394 |
+
# We assume there is an implicit 0 in a pre-release if there is
|
395 |
+
# no numeral associated with it.
|
396 |
+
if number is None:
|
397 |
+
number = 0
|
398 |
+
|
399 |
+
# We normalize any letters to their lower-case form
|
400 |
+
letter = letter.lower()
|
401 |
+
|
402 |
+
# We consider some words to be alternate spellings of other words and
|
403 |
+
# in those cases we want to normalize the spellings to our preferred
|
404 |
+
# spelling.
|
405 |
+
if letter == "alpha":
|
406 |
+
letter = "a"
|
407 |
+
elif letter == "beta":
|
408 |
+
letter = "b"
|
409 |
+
elif letter in ["c", "pre", "preview"]:
|
410 |
+
letter = "rc"
|
411 |
+
elif letter in ["rev", "r"]:
|
412 |
+
letter = "post"
|
413 |
+
|
414 |
+
return letter, int(number)
|
415 |
+
if not letter and number:
|
416 |
+
# We assume that if we are given a number but not given a letter,
|
417 |
+
# then this is using the implicit post release syntax (e.g., 1.0-1)
|
418 |
+
letter = "post"
|
419 |
+
|
420 |
+
return letter, int(number)
|
421 |
+
|
422 |
+
|
423 |
+
_local_version_seperators = re.compile(r"[\._-]")
|
424 |
+
|
425 |
+
|
426 |
+
def _parse_local_version(local):
|
427 |
+
"""
|
428 |
+
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
|
429 |
+
"""
|
430 |
+
if local is not None:
|
431 |
+
return tuple(
|
432 |
+
part.lower() if not part.isdigit() else int(part)
|
433 |
+
for part in _local_version_seperators.split(local)
|
434 |
+
)
|
435 |
+
|
436 |
+
|
437 |
+
def _cmpkey(epoch, release, pre, post, dev, local):
|
438 |
+
# When we compare a release version, we want to compare it with all of the
|
439 |
+
# trailing zeros removed. So we'll use a reverse the list, drop all the now
|
440 |
+
# leading zeros until we come to something non-zero, then take the rest,
|
441 |
+
# re-reverse it back into the correct order, and make it a tuple and use
|
442 |
+
# that for our sorting key.
|
443 |
+
release = tuple(
|
444 |
+
reversed(list(
|
445 |
+
itertools.dropwhile(
|
446 |
+
lambda x: x == 0,
|
447 |
+
reversed(release),
|
448 |
+
)
|
449 |
+
))
|
450 |
+
)
|
451 |
+
|
452 |
+
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
|
453 |
+
# We'll do this by abusing the pre-segment, but we _only_ want to do this
|
454 |
+
# if there is no pre- or a post-segment. If we have one of those, then
|
455 |
+
# the normal sorting rules will handle this case correctly.
|
456 |
+
if pre is None and post is None and dev is not None:
|
457 |
+
pre = -Infinity
|
458 |
+
# Versions without a pre-release (except as noted above) should sort after
|
459 |
+
# those with one.
|
460 |
+
elif pre is None:
|
461 |
+
pre = Infinity
|
462 |
+
|
463 |
+
# Versions without a post-segment should sort before those with one.
|
464 |
+
if post is None:
|
465 |
+
post = -Infinity
|
466 |
+
|
467 |
+
# Versions without a development segment should sort after those with one.
|
468 |
+
if dev is None:
|
469 |
+
dev = Infinity
|
470 |
+
|
471 |
+
if local is None:
|
472 |
+
# Versions without a local segment should sort before those with one.
|
473 |
+
local = -Infinity
|
474 |
+
else:
|
475 |
+
# Versions with a local segment need that segment parsed to implement
|
476 |
+
# the sorting rules in PEP440.
|
477 |
+
# - Alphanumeric segments sort before numeric segments
|
478 |
+
# - Alphanumeric segments sort lexicographically
|
479 |
+
# - Numeric segments sort numerically
|
480 |
+
# - Shorter versions sort before longer versions when the prefixes
|
481 |
+
# match exactly
|
482 |
+
local = tuple(
|
483 |
+
(i, "") if isinstance(i, int) else (-Infinity, i)
|
484 |
+
for i in local
|
485 |
+
)
|
486 |
+
|
487 |
+
return epoch, release, pre, post, dev, local
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (9.87 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_array_object.cpython-310.pyc
ADDED
Binary file (28.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_constants.cpython-310.pyc
ADDED
Binary file (269 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_creation_functions.cpython-310.pyc
ADDED
Binary file (8.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_data_type_functions.cpython-310.pyc
ADDED
Binary file (5.82 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_dtypes.cpython-310.pyc
ADDED
Binary file (2.51 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_elementwise_functions.cpython-310.pyc
ADDED
Binary file (19.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_indexing_functions.cpython-310.pyc
ADDED
Binary file (984 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_manipulation_functions.cpython-310.pyc
ADDED
Binary file (3.69 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_searching_functions.cpython-310.pyc
ADDED
Binary file (2.15 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_set_functions.cpython-310.pyc
ADDED
Binary file (2.26 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_sorting_functions.cpython-310.pyc
ADDED
Binary file (1.56 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_statistical_functions.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_typing.cpython-310.pyc
ADDED
Binary file (2.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/_utility_functions.cpython-310.pyc
ADDED
Binary file (1.07 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/linalg.cpython-310.pyc
ADDED
Binary file (13.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__pycache__/setup.cpython-310.pyc
ADDED
Binary file (563 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_array_object.py
ADDED
@@ -0,0 +1,1133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Wrapper class around the ndarray object for the array API standard.
|
3 |
+
|
4 |
+
The array API standard defines some behaviors differently than ndarray, in
|
5 |
+
particular, type promotion rules are different (the standard has no
|
6 |
+
value-based casting). The standard also specifies a more limited subset of
|
7 |
+
array methods and functionalities than are implemented on ndarray. Since the
|
8 |
+
goal of the array_api namespace is to be a minimal implementation of the array
|
9 |
+
API standard, we need to define a separate wrapper class for the array_api
|
10 |
+
namespace.
|
11 |
+
|
12 |
+
The standard compliant class is only a wrapper class. It is *not* a subclass
|
13 |
+
of ndarray.
|
14 |
+
"""
|
15 |
+
|
16 |
+
from __future__ import annotations
|
17 |
+
|
18 |
+
import operator
|
19 |
+
from enum import IntEnum
|
20 |
+
from ._creation_functions import asarray
|
21 |
+
from ._dtypes import (
|
22 |
+
_all_dtypes,
|
23 |
+
_boolean_dtypes,
|
24 |
+
_integer_dtypes,
|
25 |
+
_integer_or_boolean_dtypes,
|
26 |
+
_floating_dtypes,
|
27 |
+
_complex_floating_dtypes,
|
28 |
+
_numeric_dtypes,
|
29 |
+
_result_type,
|
30 |
+
_dtype_categories,
|
31 |
+
)
|
32 |
+
|
33 |
+
from typing import TYPE_CHECKING, Optional, Tuple, Union, Any, SupportsIndex
|
34 |
+
import types
|
35 |
+
|
36 |
+
if TYPE_CHECKING:
|
37 |
+
from ._typing import Any, PyCapsule, Device, Dtype
|
38 |
+
import numpy.typing as npt
|
39 |
+
|
40 |
+
import numpy as np
|
41 |
+
|
42 |
+
from numpy import array_api
|
43 |
+
|
44 |
+
|
45 |
+
class Array:
|
46 |
+
"""
|
47 |
+
n-d array object for the array API namespace.
|
48 |
+
|
49 |
+
See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more
|
50 |
+
information.
|
51 |
+
|
52 |
+
This is a wrapper around numpy.ndarray that restricts the usage to only
|
53 |
+
those things that are required by the array API namespace. Note,
|
54 |
+
attributes on this object that start with a single underscore are not part
|
55 |
+
of the API specification and should only be used internally. This object
|
56 |
+
should not be constructed directly. Rather, use one of the creation
|
57 |
+
functions, such as asarray().
|
58 |
+
|
59 |
+
"""
|
60 |
+
_array: np.ndarray[Any, Any]
|
61 |
+
|
62 |
+
# Use a custom constructor instead of __init__, as manually initializing
|
63 |
+
# this class is not supported API.
|
64 |
+
@classmethod
|
65 |
+
def _new(cls, x, /):
|
66 |
+
"""
|
67 |
+
This is a private method for initializing the array API Array
|
68 |
+
object.
|
69 |
+
|
70 |
+
Functions outside of the array_api submodule should not use this
|
71 |
+
method. Use one of the creation functions instead, such as
|
72 |
+
``asarray``.
|
73 |
+
|
74 |
+
"""
|
75 |
+
obj = super().__new__(cls)
|
76 |
+
# Note: The spec does not have array scalars, only 0-D arrays.
|
77 |
+
if isinstance(x, np.generic):
|
78 |
+
# Convert the array scalar to a 0-D array
|
79 |
+
x = np.asarray(x)
|
80 |
+
if x.dtype not in _all_dtypes:
|
81 |
+
raise TypeError(
|
82 |
+
f"The array_api namespace does not support the dtype '{x.dtype}'"
|
83 |
+
)
|
84 |
+
obj._array = x
|
85 |
+
return obj
|
86 |
+
|
87 |
+
# Prevent Array() from working
|
88 |
+
def __new__(cls, *args, **kwargs):
|
89 |
+
raise TypeError(
|
90 |
+
"The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead."
|
91 |
+
)
|
92 |
+
|
93 |
+
# These functions are not required by the spec, but are implemented for
|
94 |
+
# the sake of usability.
|
95 |
+
|
96 |
+
def __str__(self: Array, /) -> str:
|
97 |
+
"""
|
98 |
+
Performs the operation __str__.
|
99 |
+
"""
|
100 |
+
return self._array.__str__().replace("array", "Array")
|
101 |
+
|
102 |
+
def __repr__(self: Array, /) -> str:
|
103 |
+
"""
|
104 |
+
Performs the operation __repr__.
|
105 |
+
"""
|
106 |
+
suffix = f", dtype={self.dtype.name})"
|
107 |
+
if 0 in self.shape:
|
108 |
+
prefix = "empty("
|
109 |
+
mid = str(self.shape)
|
110 |
+
else:
|
111 |
+
prefix = "Array("
|
112 |
+
mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix)
|
113 |
+
return prefix + mid + suffix
|
114 |
+
|
115 |
+
# This function is not required by the spec, but we implement it here for
|
116 |
+
# convenience so that np.asarray(np.array_api.Array) will work.
|
117 |
+
def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]:
|
118 |
+
"""
|
119 |
+
Warning: this method is NOT part of the array API spec. Implementers
|
120 |
+
of other libraries need not include it, and users should not assume it
|
121 |
+
will be present in other implementations.
|
122 |
+
|
123 |
+
"""
|
124 |
+
return np.asarray(self._array, dtype=dtype)
|
125 |
+
|
126 |
+
# These are various helper functions to make the array behavior match the
|
127 |
+
# spec in places where it either deviates from or is more strict than
|
128 |
+
# NumPy behavior
|
129 |
+
|
130 |
+
def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array:
|
131 |
+
"""
|
132 |
+
Helper function for operators to only allow specific input dtypes
|
133 |
+
|
134 |
+
Use like
|
135 |
+
|
136 |
+
other = self._check_allowed_dtypes(other, 'numeric', '__add__')
|
137 |
+
if other is NotImplemented:
|
138 |
+
return other
|
139 |
+
"""
|
140 |
+
|
141 |
+
if self.dtype not in _dtype_categories[dtype_category]:
|
142 |
+
raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}")
|
143 |
+
if isinstance(other, (int, complex, float, bool)):
|
144 |
+
other = self._promote_scalar(other)
|
145 |
+
elif isinstance(other, Array):
|
146 |
+
if other.dtype not in _dtype_categories[dtype_category]:
|
147 |
+
raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}")
|
148 |
+
else:
|
149 |
+
return NotImplemented
|
150 |
+
|
151 |
+
# This will raise TypeError for type combinations that are not allowed
|
152 |
+
# to promote in the spec (even if the NumPy array operator would
|
153 |
+
# promote them).
|
154 |
+
res_dtype = _result_type(self.dtype, other.dtype)
|
155 |
+
if op.startswith("__i"):
|
156 |
+
# Note: NumPy will allow in-place operators in some cases where
|
157 |
+
# the type promoted operator does not match the left-hand side
|
158 |
+
# operand. For example,
|
159 |
+
|
160 |
+
# >>> a = np.array(1, dtype=np.int8)
|
161 |
+
# >>> a += np.array(1, dtype=np.int16)
|
162 |
+
|
163 |
+
# The spec explicitly disallows this.
|
164 |
+
if res_dtype != self.dtype:
|
165 |
+
raise TypeError(
|
166 |
+
f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}"
|
167 |
+
)
|
168 |
+
|
169 |
+
return other
|
170 |
+
|
171 |
+
# Helper function to match the type promotion rules in the spec
|
172 |
+
def _promote_scalar(self, scalar):
|
173 |
+
"""
|
174 |
+
Returns a promoted version of a Python scalar appropriate for use with
|
175 |
+
operations on self.
|
176 |
+
|
177 |
+
This may raise an OverflowError in cases where the scalar is an
|
178 |
+
integer that is too large to fit in a NumPy integer dtype, or
|
179 |
+
TypeError when the scalar type is incompatible with the dtype of self.
|
180 |
+
"""
|
181 |
+
# Note: Only Python scalar types that match the array dtype are
|
182 |
+
# allowed.
|
183 |
+
if isinstance(scalar, bool):
|
184 |
+
if self.dtype not in _boolean_dtypes:
|
185 |
+
raise TypeError(
|
186 |
+
"Python bool scalars can only be promoted with bool arrays"
|
187 |
+
)
|
188 |
+
elif isinstance(scalar, int):
|
189 |
+
if self.dtype in _boolean_dtypes:
|
190 |
+
raise TypeError(
|
191 |
+
"Python int scalars cannot be promoted with bool arrays"
|
192 |
+
)
|
193 |
+
if self.dtype in _integer_dtypes:
|
194 |
+
info = np.iinfo(self.dtype)
|
195 |
+
if not (info.min <= scalar <= info.max):
|
196 |
+
raise OverflowError(
|
197 |
+
"Python int scalars must be within the bounds of the dtype for integer arrays"
|
198 |
+
)
|
199 |
+
# int + array(floating) is allowed
|
200 |
+
elif isinstance(scalar, float):
|
201 |
+
if self.dtype not in _floating_dtypes:
|
202 |
+
raise TypeError(
|
203 |
+
"Python float scalars can only be promoted with floating-point arrays."
|
204 |
+
)
|
205 |
+
elif isinstance(scalar, complex):
|
206 |
+
if self.dtype not in _complex_floating_dtypes:
|
207 |
+
raise TypeError(
|
208 |
+
"Python complex scalars can only be promoted with complex floating-point arrays."
|
209 |
+
)
|
210 |
+
else:
|
211 |
+
raise TypeError("'scalar' must be a Python scalar")
|
212 |
+
|
213 |
+
# Note: scalars are unconditionally cast to the same dtype as the
|
214 |
+
# array.
|
215 |
+
|
216 |
+
# Note: the spec only specifies integer-dtype/int promotion
|
217 |
+
# behavior for integers within the bounds of the integer dtype.
|
218 |
+
# Outside of those bounds we use the default NumPy behavior (either
|
219 |
+
# cast or raise OverflowError).
|
220 |
+
return Array._new(np.array(scalar, self.dtype))
|
221 |
+
|
222 |
+
@staticmethod
|
223 |
+
def _normalize_two_args(x1, x2) -> Tuple[Array, Array]:
|
224 |
+
"""
|
225 |
+
Normalize inputs to two arg functions to fix type promotion rules
|
226 |
+
|
227 |
+
NumPy deviates from the spec type promotion rules in cases where one
|
228 |
+
argument is 0-dimensional and the other is not. For example:
|
229 |
+
|
230 |
+
>>> import numpy as np
|
231 |
+
>>> a = np.array([1.0], dtype=np.float32)
|
232 |
+
>>> b = np.array(1.0, dtype=np.float64)
|
233 |
+
>>> np.add(a, b) # The spec says this should be float64
|
234 |
+
array([2.], dtype=float32)
|
235 |
+
|
236 |
+
To fix this, we add a dimension to the 0-dimension array before passing it
|
237 |
+
through. This works because a dimension would be added anyway from
|
238 |
+
broadcasting, so the resulting shape is the same, but this prevents NumPy
|
239 |
+
from not promoting the dtype.
|
240 |
+
"""
|
241 |
+
# Another option would be to use signature=(x1.dtype, x2.dtype, None),
|
242 |
+
# but that only works for ufuncs, so we would have to call the ufuncs
|
243 |
+
# directly in the operator methods. One should also note that this
|
244 |
+
# sort of trick wouldn't work for functions like searchsorted, which
|
245 |
+
# don't do normal broadcasting, but there aren't any functions like
|
246 |
+
# that in the array API namespace.
|
247 |
+
if x1.ndim == 0 and x2.ndim != 0:
|
248 |
+
# The _array[None] workaround was chosen because it is relatively
|
249 |
+
# performant. broadcast_to(x1._array, x2.shape) is much slower. We
|
250 |
+
# could also manually type promote x2, but that is more complicated
|
251 |
+
# and about the same performance as this.
|
252 |
+
x1 = Array._new(x1._array[None])
|
253 |
+
elif x2.ndim == 0 and x1.ndim != 0:
|
254 |
+
x2 = Array._new(x2._array[None])
|
255 |
+
return (x1, x2)
|
256 |
+
|
257 |
+
# Note: A large fraction of allowed indices are disallowed here (see the
|
258 |
+
# docstring below)
|
259 |
+
def _validate_index(self, key):
|
260 |
+
"""
|
261 |
+
Validate an index according to the array API.
|
262 |
+
|
263 |
+
The array API specification only requires a subset of indices that are
|
264 |
+
supported by NumPy. This function will reject any index that is
|
265 |
+
allowed by NumPy but not required by the array API specification. We
|
266 |
+
always raise ``IndexError`` on such indices (the spec does not require
|
267 |
+
any specific behavior on them, but this makes the NumPy array API
|
268 |
+
namespace a minimal implementation of the spec). See
|
269 |
+
https://data-apis.org/array-api/latest/API_specification/indexing.html
|
270 |
+
for the full list of required indexing behavior
|
271 |
+
|
272 |
+
This function raises IndexError if the index ``key`` is invalid. It
|
273 |
+
only raises ``IndexError`` on indices that are not already rejected by
|
274 |
+
NumPy, as NumPy will already raise the appropriate error on such
|
275 |
+
indices. ``shape`` may be None, in which case, only cases that are
|
276 |
+
independent of the array shape are checked.
|
277 |
+
|
278 |
+
The following cases are allowed by NumPy, but not specified by the array
|
279 |
+
API specification:
|
280 |
+
|
281 |
+
- Indices to not include an implicit ellipsis at the end. That is,
|
282 |
+
every axis of an array must be explicitly indexed or an ellipsis
|
283 |
+
included. This behaviour is sometimes referred to as flat indexing.
|
284 |
+
|
285 |
+
- The start and stop of a slice may not be out of bounds. In
|
286 |
+
particular, for a slice ``i:j:k`` on an axis of size ``n``, only the
|
287 |
+
following are allowed:
|
288 |
+
|
289 |
+
- ``i`` or ``j`` omitted (``None``).
|
290 |
+
- ``-n <= i <= max(0, n - 1)``.
|
291 |
+
- For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``.
|
292 |
+
- For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``.
|
293 |
+
|
294 |
+
- Boolean array indices are not allowed as part of a larger tuple
|
295 |
+
index.
|
296 |
+
|
297 |
+
- Integer array indices are not allowed (with the exception of 0-D
|
298 |
+
arrays, which are treated the same as scalars).
|
299 |
+
|
300 |
+
Additionally, it should be noted that indices that would return a
|
301 |
+
scalar in NumPy will return a 0-D array. Array scalars are not allowed
|
302 |
+
in the specification, only 0-D arrays. This is done in the
|
303 |
+
``Array._new`` constructor, not this function.
|
304 |
+
|
305 |
+
"""
|
306 |
+
_key = key if isinstance(key, tuple) else (key,)
|
307 |
+
for i in _key:
|
308 |
+
if isinstance(i, bool) or not (
|
309 |
+
isinstance(i, SupportsIndex) # i.e. ints
|
310 |
+
or isinstance(i, slice)
|
311 |
+
or i == Ellipsis
|
312 |
+
or i is None
|
313 |
+
or isinstance(i, Array)
|
314 |
+
or isinstance(i, np.ndarray)
|
315 |
+
):
|
316 |
+
raise IndexError(
|
317 |
+
f"Single-axes index {i} has {type(i)=}, but only "
|
318 |
+
"integers, slices (:), ellipsis (...), newaxis (None), "
|
319 |
+
"zero-dimensional integer arrays and boolean arrays "
|
320 |
+
"are specified in the Array API."
|
321 |
+
)
|
322 |
+
|
323 |
+
nonexpanding_key = []
|
324 |
+
single_axes = []
|
325 |
+
n_ellipsis = 0
|
326 |
+
key_has_mask = False
|
327 |
+
for i in _key:
|
328 |
+
if i is not None:
|
329 |
+
nonexpanding_key.append(i)
|
330 |
+
if isinstance(i, Array) or isinstance(i, np.ndarray):
|
331 |
+
if i.dtype in _boolean_dtypes:
|
332 |
+
key_has_mask = True
|
333 |
+
single_axes.append(i)
|
334 |
+
else:
|
335 |
+
# i must not be an array here, to avoid elementwise equals
|
336 |
+
if i == Ellipsis:
|
337 |
+
n_ellipsis += 1
|
338 |
+
else:
|
339 |
+
single_axes.append(i)
|
340 |
+
|
341 |
+
n_single_axes = len(single_axes)
|
342 |
+
if n_ellipsis > 1:
|
343 |
+
return # handled by ndarray
|
344 |
+
elif n_ellipsis == 0:
|
345 |
+
# Note boolean masks must be the sole index, which we check for
|
346 |
+
# later on.
|
347 |
+
if not key_has_mask and n_single_axes < self.ndim:
|
348 |
+
raise IndexError(
|
349 |
+
f"{self.ndim=}, but the multi-axes index only specifies "
|
350 |
+
f"{n_single_axes} dimensions. If this was intentional, "
|
351 |
+
"add a trailing ellipsis (...) which expands into as many "
|
352 |
+
"slices (:) as necessary - this is what np.ndarray arrays "
|
353 |
+
"implicitly do, but such flat indexing behaviour is not "
|
354 |
+
"specified in the Array API."
|
355 |
+
)
|
356 |
+
|
357 |
+
if n_ellipsis == 0:
|
358 |
+
indexed_shape = self.shape
|
359 |
+
else:
|
360 |
+
ellipsis_start = None
|
361 |
+
for pos, i in enumerate(nonexpanding_key):
|
362 |
+
if not (isinstance(i, Array) or isinstance(i, np.ndarray)):
|
363 |
+
if i == Ellipsis:
|
364 |
+
ellipsis_start = pos
|
365 |
+
break
|
366 |
+
assert ellipsis_start is not None # sanity check
|
367 |
+
ellipsis_end = self.ndim - (n_single_axes - ellipsis_start)
|
368 |
+
indexed_shape = (
|
369 |
+
self.shape[:ellipsis_start] + self.shape[ellipsis_end:]
|
370 |
+
)
|
371 |
+
for i, side in zip(single_axes, indexed_shape):
|
372 |
+
if isinstance(i, slice):
|
373 |
+
if side == 0:
|
374 |
+
f_range = "0 (or None)"
|
375 |
+
else:
|
376 |
+
f_range = f"between -{side} and {side - 1} (or None)"
|
377 |
+
if i.start is not None:
|
378 |
+
try:
|
379 |
+
start = operator.index(i.start)
|
380 |
+
except TypeError:
|
381 |
+
pass # handled by ndarray
|
382 |
+
else:
|
383 |
+
if not (-side <= start <= side):
|
384 |
+
raise IndexError(
|
385 |
+
f"Slice {i} contains {start=}, but should be "
|
386 |
+
f"{f_range} for an axis of size {side} "
|
387 |
+
"(out-of-bounds starts are not specified in "
|
388 |
+
"the Array API)"
|
389 |
+
)
|
390 |
+
if i.stop is not None:
|
391 |
+
try:
|
392 |
+
stop = operator.index(i.stop)
|
393 |
+
except TypeError:
|
394 |
+
pass # handled by ndarray
|
395 |
+
else:
|
396 |
+
if not (-side <= stop <= side):
|
397 |
+
raise IndexError(
|
398 |
+
f"Slice {i} contains {stop=}, but should be "
|
399 |
+
f"{f_range} for an axis of size {side} "
|
400 |
+
"(out-of-bounds stops are not specified in "
|
401 |
+
"the Array API)"
|
402 |
+
)
|
403 |
+
elif isinstance(i, Array):
|
404 |
+
if i.dtype in _boolean_dtypes and len(_key) != 1:
|
405 |
+
assert isinstance(key, tuple) # sanity check
|
406 |
+
raise IndexError(
|
407 |
+
f"Single-axes index {i} is a boolean array and "
|
408 |
+
f"{len(key)=}, but masking is only specified in the "
|
409 |
+
"Array API when the array is the sole index."
|
410 |
+
)
|
411 |
+
elif i.dtype in _integer_dtypes and i.ndim != 0:
|
412 |
+
raise IndexError(
|
413 |
+
f"Single-axes index {i} is a non-zero-dimensional "
|
414 |
+
"integer array, but advanced integer indexing is not "
|
415 |
+
"specified in the Array API."
|
416 |
+
)
|
417 |
+
elif isinstance(i, tuple):
|
418 |
+
raise IndexError(
|
419 |
+
f"Single-axes index {i} is a tuple, but nested tuple "
|
420 |
+
"indices are not specified in the Array API."
|
421 |
+
)
|
422 |
+
|
423 |
+
# Everything below this line is required by the spec.
|
424 |
+
|
425 |
+
def __abs__(self: Array, /) -> Array:
|
426 |
+
"""
|
427 |
+
Performs the operation __abs__.
|
428 |
+
"""
|
429 |
+
if self.dtype not in _numeric_dtypes:
|
430 |
+
raise TypeError("Only numeric dtypes are allowed in __abs__")
|
431 |
+
res = self._array.__abs__()
|
432 |
+
return self.__class__._new(res)
|
433 |
+
|
434 |
+
def __add__(self: Array, other: Union[int, float, Array], /) -> Array:
|
435 |
+
"""
|
436 |
+
Performs the operation __add__.
|
437 |
+
"""
|
438 |
+
other = self._check_allowed_dtypes(other, "numeric", "__add__")
|
439 |
+
if other is NotImplemented:
|
440 |
+
return other
|
441 |
+
self, other = self._normalize_two_args(self, other)
|
442 |
+
res = self._array.__add__(other._array)
|
443 |
+
return self.__class__._new(res)
|
444 |
+
|
445 |
+
def __and__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
446 |
+
"""
|
447 |
+
Performs the operation __and__.
|
448 |
+
"""
|
449 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__and__")
|
450 |
+
if other is NotImplemented:
|
451 |
+
return other
|
452 |
+
self, other = self._normalize_two_args(self, other)
|
453 |
+
res = self._array.__and__(other._array)
|
454 |
+
return self.__class__._new(res)
|
455 |
+
|
456 |
+
def __array_namespace__(
|
457 |
+
self: Array, /, *, api_version: Optional[str] = None
|
458 |
+
) -> types.ModuleType:
|
459 |
+
if api_version is not None and not api_version.startswith("2021."):
|
460 |
+
raise ValueError(f"Unrecognized array API version: {api_version!r}")
|
461 |
+
return array_api
|
462 |
+
|
463 |
+
def __bool__(self: Array, /) -> bool:
|
464 |
+
"""
|
465 |
+
Performs the operation __bool__.
|
466 |
+
"""
|
467 |
+
# Note: This is an error here.
|
468 |
+
if self._array.ndim != 0:
|
469 |
+
raise TypeError("bool is only allowed on arrays with 0 dimensions")
|
470 |
+
res = self._array.__bool__()
|
471 |
+
return res
|
472 |
+
|
473 |
+
def __complex__(self: Array, /) -> complex:
|
474 |
+
"""
|
475 |
+
Performs the operation __complex__.
|
476 |
+
"""
|
477 |
+
# Note: This is an error here.
|
478 |
+
if self._array.ndim != 0:
|
479 |
+
raise TypeError("complex is only allowed on arrays with 0 dimensions")
|
480 |
+
res = self._array.__complex__()
|
481 |
+
return res
|
482 |
+
|
483 |
+
def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule:
|
484 |
+
"""
|
485 |
+
Performs the operation __dlpack__.
|
486 |
+
"""
|
487 |
+
return self._array.__dlpack__(stream=stream)
|
488 |
+
|
489 |
+
def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]:
|
490 |
+
"""
|
491 |
+
Performs the operation __dlpack_device__.
|
492 |
+
"""
|
493 |
+
# Note: device support is required for this
|
494 |
+
return self._array.__dlpack_device__()
|
495 |
+
|
496 |
+
def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array:
|
497 |
+
"""
|
498 |
+
Performs the operation __eq__.
|
499 |
+
"""
|
500 |
+
# Even though "all" dtypes are allowed, we still require them to be
|
501 |
+
# promotable with each other.
|
502 |
+
other = self._check_allowed_dtypes(other, "all", "__eq__")
|
503 |
+
if other is NotImplemented:
|
504 |
+
return other
|
505 |
+
self, other = self._normalize_two_args(self, other)
|
506 |
+
res = self._array.__eq__(other._array)
|
507 |
+
return self.__class__._new(res)
|
508 |
+
|
509 |
+
def __float__(self: Array, /) -> float:
|
510 |
+
"""
|
511 |
+
Performs the operation __float__.
|
512 |
+
"""
|
513 |
+
# Note: This is an error here.
|
514 |
+
if self._array.ndim != 0:
|
515 |
+
raise TypeError("float is only allowed on arrays with 0 dimensions")
|
516 |
+
if self.dtype in _complex_floating_dtypes:
|
517 |
+
raise TypeError("float is not allowed on complex floating-point arrays")
|
518 |
+
res = self._array.__float__()
|
519 |
+
return res
|
520 |
+
|
521 |
+
def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array:
|
522 |
+
"""
|
523 |
+
Performs the operation __floordiv__.
|
524 |
+
"""
|
525 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__floordiv__")
|
526 |
+
if other is NotImplemented:
|
527 |
+
return other
|
528 |
+
self, other = self._normalize_two_args(self, other)
|
529 |
+
res = self._array.__floordiv__(other._array)
|
530 |
+
return self.__class__._new(res)
|
531 |
+
|
532 |
+
def __ge__(self: Array, other: Union[int, float, Array], /) -> Array:
|
533 |
+
"""
|
534 |
+
Performs the operation __ge__.
|
535 |
+
"""
|
536 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__ge__")
|
537 |
+
if other is NotImplemented:
|
538 |
+
return other
|
539 |
+
self, other = self._normalize_two_args(self, other)
|
540 |
+
res = self._array.__ge__(other._array)
|
541 |
+
return self.__class__._new(res)
|
542 |
+
|
543 |
+
def __getitem__(
|
544 |
+
self: Array,
|
545 |
+
key: Union[
|
546 |
+
int,
|
547 |
+
slice,
|
548 |
+
ellipsis,
|
549 |
+
Tuple[Union[int, slice, ellipsis, None], ...],
|
550 |
+
Array,
|
551 |
+
],
|
552 |
+
/,
|
553 |
+
) -> Array:
|
554 |
+
"""
|
555 |
+
Performs the operation __getitem__.
|
556 |
+
"""
|
557 |
+
# Note: Only indices required by the spec are allowed. See the
|
558 |
+
# docstring of _validate_index
|
559 |
+
self._validate_index(key)
|
560 |
+
if isinstance(key, Array):
|
561 |
+
# Indexing self._array with array_api arrays can be erroneous
|
562 |
+
key = key._array
|
563 |
+
res = self._array.__getitem__(key)
|
564 |
+
return self._new(res)
|
565 |
+
|
566 |
+
def __gt__(self: Array, other: Union[int, float, Array], /) -> Array:
|
567 |
+
"""
|
568 |
+
Performs the operation __gt__.
|
569 |
+
"""
|
570 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__gt__")
|
571 |
+
if other is NotImplemented:
|
572 |
+
return other
|
573 |
+
self, other = self._normalize_two_args(self, other)
|
574 |
+
res = self._array.__gt__(other._array)
|
575 |
+
return self.__class__._new(res)
|
576 |
+
|
577 |
+
def __int__(self: Array, /) -> int:
|
578 |
+
"""
|
579 |
+
Performs the operation __int__.
|
580 |
+
"""
|
581 |
+
# Note: This is an error here.
|
582 |
+
if self._array.ndim != 0:
|
583 |
+
raise TypeError("int is only allowed on arrays with 0 dimensions")
|
584 |
+
if self.dtype in _complex_floating_dtypes:
|
585 |
+
raise TypeError("int is not allowed on complex floating-point arrays")
|
586 |
+
res = self._array.__int__()
|
587 |
+
return res
|
588 |
+
|
589 |
+
def __index__(self: Array, /) -> int:
|
590 |
+
"""
|
591 |
+
Performs the operation __index__.
|
592 |
+
"""
|
593 |
+
res = self._array.__index__()
|
594 |
+
return res
|
595 |
+
|
596 |
+
def __invert__(self: Array, /) -> Array:
|
597 |
+
"""
|
598 |
+
Performs the operation __invert__.
|
599 |
+
"""
|
600 |
+
if self.dtype not in _integer_or_boolean_dtypes:
|
601 |
+
raise TypeError("Only integer or boolean dtypes are allowed in __invert__")
|
602 |
+
res = self._array.__invert__()
|
603 |
+
return self.__class__._new(res)
|
604 |
+
|
605 |
+
def __le__(self: Array, other: Union[int, float, Array], /) -> Array:
|
606 |
+
"""
|
607 |
+
Performs the operation __le__.
|
608 |
+
"""
|
609 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__le__")
|
610 |
+
if other is NotImplemented:
|
611 |
+
return other
|
612 |
+
self, other = self._normalize_two_args(self, other)
|
613 |
+
res = self._array.__le__(other._array)
|
614 |
+
return self.__class__._new(res)
|
615 |
+
|
616 |
+
def __lshift__(self: Array, other: Union[int, Array], /) -> Array:
|
617 |
+
"""
|
618 |
+
Performs the operation __lshift__.
|
619 |
+
"""
|
620 |
+
other = self._check_allowed_dtypes(other, "integer", "__lshift__")
|
621 |
+
if other is NotImplemented:
|
622 |
+
return other
|
623 |
+
self, other = self._normalize_two_args(self, other)
|
624 |
+
res = self._array.__lshift__(other._array)
|
625 |
+
return self.__class__._new(res)
|
626 |
+
|
627 |
+
def __lt__(self: Array, other: Union[int, float, Array], /) -> Array:
|
628 |
+
"""
|
629 |
+
Performs the operation __lt__.
|
630 |
+
"""
|
631 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__lt__")
|
632 |
+
if other is NotImplemented:
|
633 |
+
return other
|
634 |
+
self, other = self._normalize_two_args(self, other)
|
635 |
+
res = self._array.__lt__(other._array)
|
636 |
+
return self.__class__._new(res)
|
637 |
+
|
638 |
+
def __matmul__(self: Array, other: Array, /) -> Array:
|
639 |
+
"""
|
640 |
+
Performs the operation __matmul__.
|
641 |
+
"""
|
642 |
+
# matmul is not defined for scalars, but without this, we may get
|
643 |
+
# the wrong error message from asarray.
|
644 |
+
other = self._check_allowed_dtypes(other, "numeric", "__matmul__")
|
645 |
+
if other is NotImplemented:
|
646 |
+
return other
|
647 |
+
res = self._array.__matmul__(other._array)
|
648 |
+
return self.__class__._new(res)
|
649 |
+
|
650 |
+
def __mod__(self: Array, other: Union[int, float, Array], /) -> Array:
|
651 |
+
"""
|
652 |
+
Performs the operation __mod__.
|
653 |
+
"""
|
654 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__mod__")
|
655 |
+
if other is NotImplemented:
|
656 |
+
return other
|
657 |
+
self, other = self._normalize_two_args(self, other)
|
658 |
+
res = self._array.__mod__(other._array)
|
659 |
+
return self.__class__._new(res)
|
660 |
+
|
661 |
+
def __mul__(self: Array, other: Union[int, float, Array], /) -> Array:
|
662 |
+
"""
|
663 |
+
Performs the operation __mul__.
|
664 |
+
"""
|
665 |
+
other = self._check_allowed_dtypes(other, "numeric", "__mul__")
|
666 |
+
if other is NotImplemented:
|
667 |
+
return other
|
668 |
+
self, other = self._normalize_two_args(self, other)
|
669 |
+
res = self._array.__mul__(other._array)
|
670 |
+
return self.__class__._new(res)
|
671 |
+
|
672 |
+
def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array:
|
673 |
+
"""
|
674 |
+
Performs the operation __ne__.
|
675 |
+
"""
|
676 |
+
other = self._check_allowed_dtypes(other, "all", "__ne__")
|
677 |
+
if other is NotImplemented:
|
678 |
+
return other
|
679 |
+
self, other = self._normalize_two_args(self, other)
|
680 |
+
res = self._array.__ne__(other._array)
|
681 |
+
return self.__class__._new(res)
|
682 |
+
|
683 |
+
def __neg__(self: Array, /) -> Array:
|
684 |
+
"""
|
685 |
+
Performs the operation __neg__.
|
686 |
+
"""
|
687 |
+
if self.dtype not in _numeric_dtypes:
|
688 |
+
raise TypeError("Only numeric dtypes are allowed in __neg__")
|
689 |
+
res = self._array.__neg__()
|
690 |
+
return self.__class__._new(res)
|
691 |
+
|
692 |
+
def __or__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
693 |
+
"""
|
694 |
+
Performs the operation __or__.
|
695 |
+
"""
|
696 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__or__")
|
697 |
+
if other is NotImplemented:
|
698 |
+
return other
|
699 |
+
self, other = self._normalize_two_args(self, other)
|
700 |
+
res = self._array.__or__(other._array)
|
701 |
+
return self.__class__._new(res)
|
702 |
+
|
703 |
+
def __pos__(self: Array, /) -> Array:
|
704 |
+
"""
|
705 |
+
Performs the operation __pos__.
|
706 |
+
"""
|
707 |
+
if self.dtype not in _numeric_dtypes:
|
708 |
+
raise TypeError("Only numeric dtypes are allowed in __pos__")
|
709 |
+
res = self._array.__pos__()
|
710 |
+
return self.__class__._new(res)
|
711 |
+
|
712 |
+
def __pow__(self: Array, other: Union[int, float, Array], /) -> Array:
|
713 |
+
"""
|
714 |
+
Performs the operation __pow__.
|
715 |
+
"""
|
716 |
+
from ._elementwise_functions import pow
|
717 |
+
|
718 |
+
other = self._check_allowed_dtypes(other, "numeric", "__pow__")
|
719 |
+
if other is NotImplemented:
|
720 |
+
return other
|
721 |
+
# Note: NumPy's __pow__ does not follow type promotion rules for 0-d
|
722 |
+
# arrays, so we use pow() here instead.
|
723 |
+
return pow(self, other)
|
724 |
+
|
725 |
+
def __rshift__(self: Array, other: Union[int, Array], /) -> Array:
|
726 |
+
"""
|
727 |
+
Performs the operation __rshift__.
|
728 |
+
"""
|
729 |
+
other = self._check_allowed_dtypes(other, "integer", "__rshift__")
|
730 |
+
if other is NotImplemented:
|
731 |
+
return other
|
732 |
+
self, other = self._normalize_two_args(self, other)
|
733 |
+
res = self._array.__rshift__(other._array)
|
734 |
+
return self.__class__._new(res)
|
735 |
+
|
736 |
+
def __setitem__(
|
737 |
+
self,
|
738 |
+
key: Union[
|
739 |
+
int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array
|
740 |
+
],
|
741 |
+
value: Union[int, float, bool, Array],
|
742 |
+
/,
|
743 |
+
) -> None:
|
744 |
+
"""
|
745 |
+
Performs the operation __setitem__.
|
746 |
+
"""
|
747 |
+
# Note: Only indices required by the spec are allowed. See the
|
748 |
+
# docstring of _validate_index
|
749 |
+
self._validate_index(key)
|
750 |
+
if isinstance(key, Array):
|
751 |
+
# Indexing self._array with array_api arrays can be erroneous
|
752 |
+
key = key._array
|
753 |
+
self._array.__setitem__(key, asarray(value)._array)
|
754 |
+
|
755 |
+
def __sub__(self: Array, other: Union[int, float, Array], /) -> Array:
|
756 |
+
"""
|
757 |
+
Performs the operation __sub__.
|
758 |
+
"""
|
759 |
+
other = self._check_allowed_dtypes(other, "numeric", "__sub__")
|
760 |
+
if other is NotImplemented:
|
761 |
+
return other
|
762 |
+
self, other = self._normalize_two_args(self, other)
|
763 |
+
res = self._array.__sub__(other._array)
|
764 |
+
return self.__class__._new(res)
|
765 |
+
|
766 |
+
# PEP 484 requires int to be a subtype of float, but __truediv__ should
|
767 |
+
# not accept int.
|
768 |
+
def __truediv__(self: Array, other: Union[float, Array], /) -> Array:
|
769 |
+
"""
|
770 |
+
Performs the operation __truediv__.
|
771 |
+
"""
|
772 |
+
other = self._check_allowed_dtypes(other, "floating-point", "__truediv__")
|
773 |
+
if other is NotImplemented:
|
774 |
+
return other
|
775 |
+
self, other = self._normalize_two_args(self, other)
|
776 |
+
res = self._array.__truediv__(other._array)
|
777 |
+
return self.__class__._new(res)
|
778 |
+
|
779 |
+
def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
780 |
+
"""
|
781 |
+
Performs the operation __xor__.
|
782 |
+
"""
|
783 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__")
|
784 |
+
if other is NotImplemented:
|
785 |
+
return other
|
786 |
+
self, other = self._normalize_two_args(self, other)
|
787 |
+
res = self._array.__xor__(other._array)
|
788 |
+
return self.__class__._new(res)
|
789 |
+
|
790 |
+
def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array:
|
791 |
+
"""
|
792 |
+
Performs the operation __iadd__.
|
793 |
+
"""
|
794 |
+
other = self._check_allowed_dtypes(other, "numeric", "__iadd__")
|
795 |
+
if other is NotImplemented:
|
796 |
+
return other
|
797 |
+
self._array.__iadd__(other._array)
|
798 |
+
return self
|
799 |
+
|
800 |
+
def __radd__(self: Array, other: Union[int, float, Array], /) -> Array:
|
801 |
+
"""
|
802 |
+
Performs the operation __radd__.
|
803 |
+
"""
|
804 |
+
other = self._check_allowed_dtypes(other, "numeric", "__radd__")
|
805 |
+
if other is NotImplemented:
|
806 |
+
return other
|
807 |
+
self, other = self._normalize_two_args(self, other)
|
808 |
+
res = self._array.__radd__(other._array)
|
809 |
+
return self.__class__._new(res)
|
810 |
+
|
811 |
+
def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
812 |
+
"""
|
813 |
+
Performs the operation __iand__.
|
814 |
+
"""
|
815 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__")
|
816 |
+
if other is NotImplemented:
|
817 |
+
return other
|
818 |
+
self._array.__iand__(other._array)
|
819 |
+
return self
|
820 |
+
|
821 |
+
def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
822 |
+
"""
|
823 |
+
Performs the operation __rand__.
|
824 |
+
"""
|
825 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__")
|
826 |
+
if other is NotImplemented:
|
827 |
+
return other
|
828 |
+
self, other = self._normalize_two_args(self, other)
|
829 |
+
res = self._array.__rand__(other._array)
|
830 |
+
return self.__class__._new(res)
|
831 |
+
|
832 |
+
def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array:
|
833 |
+
"""
|
834 |
+
Performs the operation __ifloordiv__.
|
835 |
+
"""
|
836 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__ifloordiv__")
|
837 |
+
if other is NotImplemented:
|
838 |
+
return other
|
839 |
+
self._array.__ifloordiv__(other._array)
|
840 |
+
return self
|
841 |
+
|
842 |
+
def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array:
|
843 |
+
"""
|
844 |
+
Performs the operation __rfloordiv__.
|
845 |
+
"""
|
846 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__rfloordiv__")
|
847 |
+
if other is NotImplemented:
|
848 |
+
return other
|
849 |
+
self, other = self._normalize_two_args(self, other)
|
850 |
+
res = self._array.__rfloordiv__(other._array)
|
851 |
+
return self.__class__._new(res)
|
852 |
+
|
853 |
+
def __ilshift__(self: Array, other: Union[int, Array], /) -> Array:
|
854 |
+
"""
|
855 |
+
Performs the operation __ilshift__.
|
856 |
+
"""
|
857 |
+
other = self._check_allowed_dtypes(other, "integer", "__ilshift__")
|
858 |
+
if other is NotImplemented:
|
859 |
+
return other
|
860 |
+
self._array.__ilshift__(other._array)
|
861 |
+
return self
|
862 |
+
|
863 |
+
def __rlshift__(self: Array, other: Union[int, Array], /) -> Array:
|
864 |
+
"""
|
865 |
+
Performs the operation __rlshift__.
|
866 |
+
"""
|
867 |
+
other = self._check_allowed_dtypes(other, "integer", "__rlshift__")
|
868 |
+
if other is NotImplemented:
|
869 |
+
return other
|
870 |
+
self, other = self._normalize_two_args(self, other)
|
871 |
+
res = self._array.__rlshift__(other._array)
|
872 |
+
return self.__class__._new(res)
|
873 |
+
|
874 |
+
def __imatmul__(self: Array, other: Array, /) -> Array:
|
875 |
+
"""
|
876 |
+
Performs the operation __imatmul__.
|
877 |
+
"""
|
878 |
+
# matmul is not defined for scalars, but without this, we may get
|
879 |
+
# the wrong error message from asarray.
|
880 |
+
other = self._check_allowed_dtypes(other, "numeric", "__imatmul__")
|
881 |
+
if other is NotImplemented:
|
882 |
+
return other
|
883 |
+
res = self._array.__imatmul__(other._array)
|
884 |
+
return self.__class__._new(res)
|
885 |
+
|
886 |
+
def __rmatmul__(self: Array, other: Array, /) -> Array:
|
887 |
+
"""
|
888 |
+
Performs the operation __rmatmul__.
|
889 |
+
"""
|
890 |
+
# matmul is not defined for scalars, but without this, we may get
|
891 |
+
# the wrong error message from asarray.
|
892 |
+
other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__")
|
893 |
+
if other is NotImplemented:
|
894 |
+
return other
|
895 |
+
res = self._array.__rmatmul__(other._array)
|
896 |
+
return self.__class__._new(res)
|
897 |
+
|
898 |
+
def __imod__(self: Array, other: Union[int, float, Array], /) -> Array:
|
899 |
+
"""
|
900 |
+
Performs the operation __imod__.
|
901 |
+
"""
|
902 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__imod__")
|
903 |
+
if other is NotImplemented:
|
904 |
+
return other
|
905 |
+
self._array.__imod__(other._array)
|
906 |
+
return self
|
907 |
+
|
908 |
+
def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array:
|
909 |
+
"""
|
910 |
+
Performs the operation __rmod__.
|
911 |
+
"""
|
912 |
+
other = self._check_allowed_dtypes(other, "real numeric", "__rmod__")
|
913 |
+
if other is NotImplemented:
|
914 |
+
return other
|
915 |
+
self, other = self._normalize_two_args(self, other)
|
916 |
+
res = self._array.__rmod__(other._array)
|
917 |
+
return self.__class__._new(res)
|
918 |
+
|
919 |
+
def __imul__(self: Array, other: Union[int, float, Array], /) -> Array:
|
920 |
+
"""
|
921 |
+
Performs the operation __imul__.
|
922 |
+
"""
|
923 |
+
other = self._check_allowed_dtypes(other, "numeric", "__imul__")
|
924 |
+
if other is NotImplemented:
|
925 |
+
return other
|
926 |
+
self._array.__imul__(other._array)
|
927 |
+
return self
|
928 |
+
|
929 |
+
def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array:
|
930 |
+
"""
|
931 |
+
Performs the operation __rmul__.
|
932 |
+
"""
|
933 |
+
other = self._check_allowed_dtypes(other, "numeric", "__rmul__")
|
934 |
+
if other is NotImplemented:
|
935 |
+
return other
|
936 |
+
self, other = self._normalize_two_args(self, other)
|
937 |
+
res = self._array.__rmul__(other._array)
|
938 |
+
return self.__class__._new(res)
|
939 |
+
|
940 |
+
def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
941 |
+
"""
|
942 |
+
Performs the operation __ior__.
|
943 |
+
"""
|
944 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__")
|
945 |
+
if other is NotImplemented:
|
946 |
+
return other
|
947 |
+
self._array.__ior__(other._array)
|
948 |
+
return self
|
949 |
+
|
950 |
+
def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
951 |
+
"""
|
952 |
+
Performs the operation __ror__.
|
953 |
+
"""
|
954 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__")
|
955 |
+
if other is NotImplemented:
|
956 |
+
return other
|
957 |
+
self, other = self._normalize_two_args(self, other)
|
958 |
+
res = self._array.__ror__(other._array)
|
959 |
+
return self.__class__._new(res)
|
960 |
+
|
961 |
+
def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array:
|
962 |
+
"""
|
963 |
+
Performs the operation __ipow__.
|
964 |
+
"""
|
965 |
+
other = self._check_allowed_dtypes(other, "numeric", "__ipow__")
|
966 |
+
if other is NotImplemented:
|
967 |
+
return other
|
968 |
+
self._array.__ipow__(other._array)
|
969 |
+
return self
|
970 |
+
|
971 |
+
def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array:
|
972 |
+
"""
|
973 |
+
Performs the operation __rpow__.
|
974 |
+
"""
|
975 |
+
from ._elementwise_functions import pow
|
976 |
+
|
977 |
+
other = self._check_allowed_dtypes(other, "numeric", "__rpow__")
|
978 |
+
if other is NotImplemented:
|
979 |
+
return other
|
980 |
+
# Note: NumPy's __pow__ does not follow the spec type promotion rules
|
981 |
+
# for 0-d arrays, so we use pow() here instead.
|
982 |
+
return pow(other, self)
|
983 |
+
|
984 |
+
def __irshift__(self: Array, other: Union[int, Array], /) -> Array:
|
985 |
+
"""
|
986 |
+
Performs the operation __irshift__.
|
987 |
+
"""
|
988 |
+
other = self._check_allowed_dtypes(other, "integer", "__irshift__")
|
989 |
+
if other is NotImplemented:
|
990 |
+
return other
|
991 |
+
self._array.__irshift__(other._array)
|
992 |
+
return self
|
993 |
+
|
994 |
+
def __rrshift__(self: Array, other: Union[int, Array], /) -> Array:
|
995 |
+
"""
|
996 |
+
Performs the operation __rrshift__.
|
997 |
+
"""
|
998 |
+
other = self._check_allowed_dtypes(other, "integer", "__rrshift__")
|
999 |
+
if other is NotImplemented:
|
1000 |
+
return other
|
1001 |
+
self, other = self._normalize_two_args(self, other)
|
1002 |
+
res = self._array.__rrshift__(other._array)
|
1003 |
+
return self.__class__._new(res)
|
1004 |
+
|
1005 |
+
def __isub__(self: Array, other: Union[int, float, Array], /) -> Array:
|
1006 |
+
"""
|
1007 |
+
Performs the operation __isub__.
|
1008 |
+
"""
|
1009 |
+
other = self._check_allowed_dtypes(other, "numeric", "__isub__")
|
1010 |
+
if other is NotImplemented:
|
1011 |
+
return other
|
1012 |
+
self._array.__isub__(other._array)
|
1013 |
+
return self
|
1014 |
+
|
1015 |
+
def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array:
|
1016 |
+
"""
|
1017 |
+
Performs the operation __rsub__.
|
1018 |
+
"""
|
1019 |
+
other = self._check_allowed_dtypes(other, "numeric", "__rsub__")
|
1020 |
+
if other is NotImplemented:
|
1021 |
+
return other
|
1022 |
+
self, other = self._normalize_two_args(self, other)
|
1023 |
+
res = self._array.__rsub__(other._array)
|
1024 |
+
return self.__class__._new(res)
|
1025 |
+
|
1026 |
+
def __itruediv__(self: Array, other: Union[float, Array], /) -> Array:
|
1027 |
+
"""
|
1028 |
+
Performs the operation __itruediv__.
|
1029 |
+
"""
|
1030 |
+
other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__")
|
1031 |
+
if other is NotImplemented:
|
1032 |
+
return other
|
1033 |
+
self._array.__itruediv__(other._array)
|
1034 |
+
return self
|
1035 |
+
|
1036 |
+
def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array:
|
1037 |
+
"""
|
1038 |
+
Performs the operation __rtruediv__.
|
1039 |
+
"""
|
1040 |
+
other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__")
|
1041 |
+
if other is NotImplemented:
|
1042 |
+
return other
|
1043 |
+
self, other = self._normalize_two_args(self, other)
|
1044 |
+
res = self._array.__rtruediv__(other._array)
|
1045 |
+
return self.__class__._new(res)
|
1046 |
+
|
1047 |
+
def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
1048 |
+
"""
|
1049 |
+
Performs the operation __ixor__.
|
1050 |
+
"""
|
1051 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__")
|
1052 |
+
if other is NotImplemented:
|
1053 |
+
return other
|
1054 |
+
self._array.__ixor__(other._array)
|
1055 |
+
return self
|
1056 |
+
|
1057 |
+
def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array:
|
1058 |
+
"""
|
1059 |
+
Performs the operation __rxor__.
|
1060 |
+
"""
|
1061 |
+
other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__")
|
1062 |
+
if other is NotImplemented:
|
1063 |
+
return other
|
1064 |
+
self, other = self._normalize_two_args(self, other)
|
1065 |
+
res = self._array.__rxor__(other._array)
|
1066 |
+
return self.__class__._new(res)
|
1067 |
+
|
1068 |
+
def to_device(self: Array, device: Device, /, stream: None = None) -> Array:
|
1069 |
+
if stream is not None:
|
1070 |
+
raise ValueError("The stream argument to to_device() is not supported")
|
1071 |
+
if device == 'cpu':
|
1072 |
+
return self
|
1073 |
+
raise ValueError(f"Unsupported device {device!r}")
|
1074 |
+
|
1075 |
+
@property
|
1076 |
+
def dtype(self) -> Dtype:
|
1077 |
+
"""
|
1078 |
+
Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`.
|
1079 |
+
|
1080 |
+
See its docstring for more information.
|
1081 |
+
"""
|
1082 |
+
return self._array.dtype
|
1083 |
+
|
1084 |
+
@property
|
1085 |
+
def device(self) -> Device:
|
1086 |
+
return "cpu"
|
1087 |
+
|
1088 |
+
# Note: mT is new in array API spec (see matrix_transpose)
|
1089 |
+
@property
|
1090 |
+
def mT(self) -> Array:
|
1091 |
+
from .linalg import matrix_transpose
|
1092 |
+
return matrix_transpose(self)
|
1093 |
+
|
1094 |
+
@property
|
1095 |
+
def ndim(self) -> int:
|
1096 |
+
"""
|
1097 |
+
Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`.
|
1098 |
+
|
1099 |
+
See its docstring for more information.
|
1100 |
+
"""
|
1101 |
+
return self._array.ndim
|
1102 |
+
|
1103 |
+
@property
|
1104 |
+
def shape(self) -> Tuple[int, ...]:
|
1105 |
+
"""
|
1106 |
+
Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`.
|
1107 |
+
|
1108 |
+
See its docstring for more information.
|
1109 |
+
"""
|
1110 |
+
return self._array.shape
|
1111 |
+
|
1112 |
+
@property
|
1113 |
+
def size(self) -> int:
|
1114 |
+
"""
|
1115 |
+
Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`.
|
1116 |
+
|
1117 |
+
See its docstring for more information.
|
1118 |
+
"""
|
1119 |
+
return self._array.size
|
1120 |
+
|
1121 |
+
@property
|
1122 |
+
def T(self) -> Array:
|
1123 |
+
"""
|
1124 |
+
Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`.
|
1125 |
+
|
1126 |
+
See its docstring for more information.
|
1127 |
+
"""
|
1128 |
+
# Note: T only works on 2-dimensional arrays. See the corresponding
|
1129 |
+
# note in the specification:
|
1130 |
+
# https://data-apis.org/array-api/latest/API_specification/array_object.html#t
|
1131 |
+
if self.ndim != 2:
|
1132 |
+
raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.")
|
1133 |
+
return self.__class__._new(self._array.T)
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_data_type_functions.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
from ._dtypes import (
|
5 |
+
_all_dtypes,
|
6 |
+
_boolean_dtypes,
|
7 |
+
_signed_integer_dtypes,
|
8 |
+
_unsigned_integer_dtypes,
|
9 |
+
_integer_dtypes,
|
10 |
+
_real_floating_dtypes,
|
11 |
+
_complex_floating_dtypes,
|
12 |
+
_numeric_dtypes,
|
13 |
+
_result_type,
|
14 |
+
)
|
15 |
+
|
16 |
+
from dataclasses import dataclass
|
17 |
+
from typing import TYPE_CHECKING, List, Tuple, Union
|
18 |
+
|
19 |
+
if TYPE_CHECKING:
|
20 |
+
from ._typing import Dtype
|
21 |
+
from collections.abc import Sequence
|
22 |
+
|
23 |
+
import numpy as np
|
24 |
+
|
25 |
+
|
26 |
+
# Note: astype is a function, not an array method as in NumPy.
|
27 |
+
def astype(x: Array, dtype: Dtype, /, *, copy: bool = True) -> Array:
|
28 |
+
if not copy and dtype == x.dtype:
|
29 |
+
return x
|
30 |
+
return Array._new(x._array.astype(dtype=dtype, copy=copy))
|
31 |
+
|
32 |
+
|
33 |
+
def broadcast_arrays(*arrays: Array) -> List[Array]:
|
34 |
+
"""
|
35 |
+
Array API compatible wrapper for :py:func:`np.broadcast_arrays <numpy.broadcast_arrays>`.
|
36 |
+
|
37 |
+
See its docstring for more information.
|
38 |
+
"""
|
39 |
+
from ._array_object import Array
|
40 |
+
|
41 |
+
return [
|
42 |
+
Array._new(array) for array in np.broadcast_arrays(*[a._array for a in arrays])
|
43 |
+
]
|
44 |
+
|
45 |
+
|
46 |
+
def broadcast_to(x: Array, /, shape: Tuple[int, ...]) -> Array:
|
47 |
+
"""
|
48 |
+
Array API compatible wrapper for :py:func:`np.broadcast_to <numpy.broadcast_to>`.
|
49 |
+
|
50 |
+
See its docstring for more information.
|
51 |
+
"""
|
52 |
+
from ._array_object import Array
|
53 |
+
|
54 |
+
return Array._new(np.broadcast_to(x._array, shape))
|
55 |
+
|
56 |
+
|
57 |
+
def can_cast(from_: Union[Dtype, Array], to: Dtype, /) -> bool:
|
58 |
+
"""
|
59 |
+
Array API compatible wrapper for :py:func:`np.can_cast <numpy.can_cast>`.
|
60 |
+
|
61 |
+
See its docstring for more information.
|
62 |
+
"""
|
63 |
+
if isinstance(from_, Array):
|
64 |
+
from_ = from_.dtype
|
65 |
+
elif from_ not in _all_dtypes:
|
66 |
+
raise TypeError(f"{from_=}, but should be an array_api array or dtype")
|
67 |
+
if to not in _all_dtypes:
|
68 |
+
raise TypeError(f"{to=}, but should be a dtype")
|
69 |
+
# Note: We avoid np.can_cast() as it has discrepancies with the array API,
|
70 |
+
# since NumPy allows cross-kind casting (e.g., NumPy allows bool -> int8).
|
71 |
+
# See https://github.com/numpy/numpy/issues/20870
|
72 |
+
try:
|
73 |
+
# We promote `from_` and `to` together. We then check if the promoted
|
74 |
+
# dtype is `to`, which indicates if `from_` can (up)cast to `to`.
|
75 |
+
dtype = _result_type(from_, to)
|
76 |
+
return to == dtype
|
77 |
+
except TypeError:
|
78 |
+
# _result_type() raises if the dtypes don't promote together
|
79 |
+
return False
|
80 |
+
|
81 |
+
|
82 |
+
# These are internal objects for the return types of finfo and iinfo, since
|
83 |
+
# the NumPy versions contain extra data that isn't part of the spec.
|
84 |
+
@dataclass
|
85 |
+
class finfo_object:
|
86 |
+
bits: int
|
87 |
+
# Note: The types of the float data here are float, whereas in NumPy they
|
88 |
+
# are scalars of the corresponding float dtype.
|
89 |
+
eps: float
|
90 |
+
max: float
|
91 |
+
min: float
|
92 |
+
smallest_normal: float
|
93 |
+
dtype: Dtype
|
94 |
+
|
95 |
+
|
96 |
+
@dataclass
|
97 |
+
class iinfo_object:
|
98 |
+
bits: int
|
99 |
+
max: int
|
100 |
+
min: int
|
101 |
+
dtype: Dtype
|
102 |
+
|
103 |
+
|
104 |
+
def finfo(type: Union[Dtype, Array], /) -> finfo_object:
|
105 |
+
"""
|
106 |
+
Array API compatible wrapper for :py:func:`np.finfo <numpy.finfo>`.
|
107 |
+
|
108 |
+
See its docstring for more information.
|
109 |
+
"""
|
110 |
+
fi = np.finfo(type)
|
111 |
+
# Note: The types of the float data here are float, whereas in NumPy they
|
112 |
+
# are scalars of the corresponding float dtype.
|
113 |
+
return finfo_object(
|
114 |
+
fi.bits,
|
115 |
+
float(fi.eps),
|
116 |
+
float(fi.max),
|
117 |
+
float(fi.min),
|
118 |
+
float(fi.smallest_normal),
|
119 |
+
fi.dtype,
|
120 |
+
)
|
121 |
+
|
122 |
+
|
123 |
+
def iinfo(type: Union[Dtype, Array], /) -> iinfo_object:
|
124 |
+
"""
|
125 |
+
Array API compatible wrapper for :py:func:`np.iinfo <numpy.iinfo>`.
|
126 |
+
|
127 |
+
See its docstring for more information.
|
128 |
+
"""
|
129 |
+
ii = np.iinfo(type)
|
130 |
+
return iinfo_object(ii.bits, ii.max, ii.min, ii.dtype)
|
131 |
+
|
132 |
+
|
133 |
+
# Note: isdtype is a new function from the 2022.12 array API specification.
|
134 |
+
def isdtype(
|
135 |
+
dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]]
|
136 |
+
) -> bool:
|
137 |
+
"""
|
138 |
+
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
|
139 |
+
|
140 |
+
See
|
141 |
+
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
|
142 |
+
for more details
|
143 |
+
"""
|
144 |
+
if isinstance(kind, tuple):
|
145 |
+
# Disallow nested tuples
|
146 |
+
if any(isinstance(k, tuple) for k in kind):
|
147 |
+
raise TypeError("'kind' must be a dtype, str, or tuple of dtypes and strs")
|
148 |
+
return any(isdtype(dtype, k) for k in kind)
|
149 |
+
elif isinstance(kind, str):
|
150 |
+
if kind == 'bool':
|
151 |
+
return dtype in _boolean_dtypes
|
152 |
+
elif kind == 'signed integer':
|
153 |
+
return dtype in _signed_integer_dtypes
|
154 |
+
elif kind == 'unsigned integer':
|
155 |
+
return dtype in _unsigned_integer_dtypes
|
156 |
+
elif kind == 'integral':
|
157 |
+
return dtype in _integer_dtypes
|
158 |
+
elif kind == 'real floating':
|
159 |
+
return dtype in _real_floating_dtypes
|
160 |
+
elif kind == 'complex floating':
|
161 |
+
return dtype in _complex_floating_dtypes
|
162 |
+
elif kind == 'numeric':
|
163 |
+
return dtype in _numeric_dtypes
|
164 |
+
else:
|
165 |
+
raise ValueError(f"Unrecognized data type kind: {kind!r}")
|
166 |
+
elif kind in _all_dtypes:
|
167 |
+
return dtype == kind
|
168 |
+
else:
|
169 |
+
raise TypeError(f"'kind' must be a dtype, str, or tuple of dtypes and strs, not {type(kind).__name__}")
|
170 |
+
|
171 |
+
def result_type(*arrays_and_dtypes: Union[Array, Dtype]) -> Dtype:
|
172 |
+
"""
|
173 |
+
Array API compatible wrapper for :py:func:`np.result_type <numpy.result_type>`.
|
174 |
+
|
175 |
+
See its docstring for more information.
|
176 |
+
"""
|
177 |
+
# Note: we use a custom implementation that gives only the type promotions
|
178 |
+
# required by the spec rather than using np.result_type. NumPy implements
|
179 |
+
# too many extra type promotions like int64 + uint64 -> float64, and does
|
180 |
+
# value-based casting on scalar arrays.
|
181 |
+
A = []
|
182 |
+
for a in arrays_and_dtypes:
|
183 |
+
if isinstance(a, Array):
|
184 |
+
a = a.dtype
|
185 |
+
elif isinstance(a, np.ndarray) or a not in _all_dtypes:
|
186 |
+
raise TypeError("result_type() inputs must be array_api arrays or dtypes")
|
187 |
+
A.append(a)
|
188 |
+
|
189 |
+
if len(A) == 0:
|
190 |
+
raise ValueError("at least one array or dtype is required")
|
191 |
+
elif len(A) == 1:
|
192 |
+
return A[0]
|
193 |
+
else:
|
194 |
+
t = A[0]
|
195 |
+
for t2 in A[1:]:
|
196 |
+
t = _result_type(t, t2)
|
197 |
+
return t
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_dtypes.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
# Note: we use dtype objects instead of dtype classes. The spec does not
|
4 |
+
# require any behavior on dtypes other than equality.
|
5 |
+
int8 = np.dtype("int8")
|
6 |
+
int16 = np.dtype("int16")
|
7 |
+
int32 = np.dtype("int32")
|
8 |
+
int64 = np.dtype("int64")
|
9 |
+
uint8 = np.dtype("uint8")
|
10 |
+
uint16 = np.dtype("uint16")
|
11 |
+
uint32 = np.dtype("uint32")
|
12 |
+
uint64 = np.dtype("uint64")
|
13 |
+
float32 = np.dtype("float32")
|
14 |
+
float64 = np.dtype("float64")
|
15 |
+
complex64 = np.dtype("complex64")
|
16 |
+
complex128 = np.dtype("complex128")
|
17 |
+
# Note: This name is changed
|
18 |
+
bool = np.dtype("bool")
|
19 |
+
|
20 |
+
_all_dtypes = (
|
21 |
+
int8,
|
22 |
+
int16,
|
23 |
+
int32,
|
24 |
+
int64,
|
25 |
+
uint8,
|
26 |
+
uint16,
|
27 |
+
uint32,
|
28 |
+
uint64,
|
29 |
+
float32,
|
30 |
+
float64,
|
31 |
+
complex64,
|
32 |
+
complex128,
|
33 |
+
bool,
|
34 |
+
)
|
35 |
+
_boolean_dtypes = (bool,)
|
36 |
+
_real_floating_dtypes = (float32, float64)
|
37 |
+
_floating_dtypes = (float32, float64, complex64, complex128)
|
38 |
+
_complex_floating_dtypes = (complex64, complex128)
|
39 |
+
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
|
40 |
+
_signed_integer_dtypes = (int8, int16, int32, int64)
|
41 |
+
_unsigned_integer_dtypes = (uint8, uint16, uint32, uint64)
|
42 |
+
_integer_or_boolean_dtypes = (
|
43 |
+
bool,
|
44 |
+
int8,
|
45 |
+
int16,
|
46 |
+
int32,
|
47 |
+
int64,
|
48 |
+
uint8,
|
49 |
+
uint16,
|
50 |
+
uint32,
|
51 |
+
uint64,
|
52 |
+
)
|
53 |
+
_real_numeric_dtypes = (
|
54 |
+
float32,
|
55 |
+
float64,
|
56 |
+
int8,
|
57 |
+
int16,
|
58 |
+
int32,
|
59 |
+
int64,
|
60 |
+
uint8,
|
61 |
+
uint16,
|
62 |
+
uint32,
|
63 |
+
uint64,
|
64 |
+
)
|
65 |
+
_numeric_dtypes = (
|
66 |
+
float32,
|
67 |
+
float64,
|
68 |
+
complex64,
|
69 |
+
complex128,
|
70 |
+
int8,
|
71 |
+
int16,
|
72 |
+
int32,
|
73 |
+
int64,
|
74 |
+
uint8,
|
75 |
+
uint16,
|
76 |
+
uint32,
|
77 |
+
uint64,
|
78 |
+
)
|
79 |
+
|
80 |
+
_dtype_categories = {
|
81 |
+
"all": _all_dtypes,
|
82 |
+
"real numeric": _real_numeric_dtypes,
|
83 |
+
"numeric": _numeric_dtypes,
|
84 |
+
"integer": _integer_dtypes,
|
85 |
+
"integer or boolean": _integer_or_boolean_dtypes,
|
86 |
+
"boolean": _boolean_dtypes,
|
87 |
+
"real floating-point": _floating_dtypes,
|
88 |
+
"complex floating-point": _complex_floating_dtypes,
|
89 |
+
"floating-point": _floating_dtypes,
|
90 |
+
}
|
91 |
+
|
92 |
+
|
93 |
+
# Note: the spec defines a restricted type promotion table compared to NumPy.
|
94 |
+
# In particular, cross-kind promotions like integer + float or boolean +
|
95 |
+
# integer are not allowed, even for functions that accept both kinds.
|
96 |
+
# Additionally, NumPy promotes signed integer + uint64 to float64, but this
|
97 |
+
# promotion is not allowed here. To be clear, Python scalar int objects are
|
98 |
+
# allowed to promote to floating-point dtypes, but only in array operators
|
99 |
+
# (see Array._promote_scalar) method in _array_object.py.
|
100 |
+
_promotion_table = {
|
101 |
+
(int8, int8): int8,
|
102 |
+
(int8, int16): int16,
|
103 |
+
(int8, int32): int32,
|
104 |
+
(int8, int64): int64,
|
105 |
+
(int16, int8): int16,
|
106 |
+
(int16, int16): int16,
|
107 |
+
(int16, int32): int32,
|
108 |
+
(int16, int64): int64,
|
109 |
+
(int32, int8): int32,
|
110 |
+
(int32, int16): int32,
|
111 |
+
(int32, int32): int32,
|
112 |
+
(int32, int64): int64,
|
113 |
+
(int64, int8): int64,
|
114 |
+
(int64, int16): int64,
|
115 |
+
(int64, int32): int64,
|
116 |
+
(int64, int64): int64,
|
117 |
+
(uint8, uint8): uint8,
|
118 |
+
(uint8, uint16): uint16,
|
119 |
+
(uint8, uint32): uint32,
|
120 |
+
(uint8, uint64): uint64,
|
121 |
+
(uint16, uint8): uint16,
|
122 |
+
(uint16, uint16): uint16,
|
123 |
+
(uint16, uint32): uint32,
|
124 |
+
(uint16, uint64): uint64,
|
125 |
+
(uint32, uint8): uint32,
|
126 |
+
(uint32, uint16): uint32,
|
127 |
+
(uint32, uint32): uint32,
|
128 |
+
(uint32, uint64): uint64,
|
129 |
+
(uint64, uint8): uint64,
|
130 |
+
(uint64, uint16): uint64,
|
131 |
+
(uint64, uint32): uint64,
|
132 |
+
(uint64, uint64): uint64,
|
133 |
+
(int8, uint8): int16,
|
134 |
+
(int8, uint16): int32,
|
135 |
+
(int8, uint32): int64,
|
136 |
+
(int16, uint8): int16,
|
137 |
+
(int16, uint16): int32,
|
138 |
+
(int16, uint32): int64,
|
139 |
+
(int32, uint8): int32,
|
140 |
+
(int32, uint16): int32,
|
141 |
+
(int32, uint32): int64,
|
142 |
+
(int64, uint8): int64,
|
143 |
+
(int64, uint16): int64,
|
144 |
+
(int64, uint32): int64,
|
145 |
+
(uint8, int8): int16,
|
146 |
+
(uint16, int8): int32,
|
147 |
+
(uint32, int8): int64,
|
148 |
+
(uint8, int16): int16,
|
149 |
+
(uint16, int16): int32,
|
150 |
+
(uint32, int16): int64,
|
151 |
+
(uint8, int32): int32,
|
152 |
+
(uint16, int32): int32,
|
153 |
+
(uint32, int32): int64,
|
154 |
+
(uint8, int64): int64,
|
155 |
+
(uint16, int64): int64,
|
156 |
+
(uint32, int64): int64,
|
157 |
+
(float32, float32): float32,
|
158 |
+
(float32, float64): float64,
|
159 |
+
(float64, float32): float64,
|
160 |
+
(float64, float64): float64,
|
161 |
+
(complex64, complex64): complex64,
|
162 |
+
(complex64, complex128): complex128,
|
163 |
+
(complex128, complex64): complex128,
|
164 |
+
(complex128, complex128): complex128,
|
165 |
+
(float32, complex64): complex64,
|
166 |
+
(float32, complex128): complex128,
|
167 |
+
(float64, complex64): complex128,
|
168 |
+
(float64, complex128): complex128,
|
169 |
+
(complex64, float32): complex64,
|
170 |
+
(complex64, float64): complex128,
|
171 |
+
(complex128, float32): complex128,
|
172 |
+
(complex128, float64): complex128,
|
173 |
+
(bool, bool): bool,
|
174 |
+
}
|
175 |
+
|
176 |
+
|
177 |
+
def _result_type(type1, type2):
|
178 |
+
if (type1, type2) in _promotion_table:
|
179 |
+
return _promotion_table[type1, type2]
|
180 |
+
raise TypeError(f"{type1} and {type2} cannot be type promoted together")
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_manipulation_functions.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
from ._data_type_functions import result_type
|
5 |
+
|
6 |
+
from typing import List, Optional, Tuple, Union
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
# Note: the function name is different here
|
11 |
+
def concat(
|
12 |
+
arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0
|
13 |
+
) -> Array:
|
14 |
+
"""
|
15 |
+
Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`.
|
16 |
+
|
17 |
+
See its docstring for more information.
|
18 |
+
"""
|
19 |
+
# Note: Casting rules here are different from the np.concatenate default
|
20 |
+
# (no for scalars with axis=None, no cross-kind casting)
|
21 |
+
dtype = result_type(*arrays)
|
22 |
+
arrays = tuple(a._array for a in arrays)
|
23 |
+
return Array._new(np.concatenate(arrays, axis=axis, dtype=dtype))
|
24 |
+
|
25 |
+
|
26 |
+
def expand_dims(x: Array, /, *, axis: int) -> Array:
|
27 |
+
"""
|
28 |
+
Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`.
|
29 |
+
|
30 |
+
See its docstring for more information.
|
31 |
+
"""
|
32 |
+
return Array._new(np.expand_dims(x._array, axis))
|
33 |
+
|
34 |
+
|
35 |
+
def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) -> Array:
|
36 |
+
"""
|
37 |
+
Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`.
|
38 |
+
|
39 |
+
See its docstring for more information.
|
40 |
+
"""
|
41 |
+
return Array._new(np.flip(x._array, axis=axis))
|
42 |
+
|
43 |
+
|
44 |
+
# Note: The function name is different here (see also matrix_transpose).
|
45 |
+
# Unlike transpose(), the axes argument is required.
|
46 |
+
def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array:
|
47 |
+
"""
|
48 |
+
Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`.
|
49 |
+
|
50 |
+
See its docstring for more information.
|
51 |
+
"""
|
52 |
+
return Array._new(np.transpose(x._array, axes))
|
53 |
+
|
54 |
+
|
55 |
+
# Note: the optional argument is called 'shape', not 'newshape'
|
56 |
+
def reshape(x: Array,
|
57 |
+
/,
|
58 |
+
shape: Tuple[int, ...],
|
59 |
+
*,
|
60 |
+
copy: Optional[Bool] = None) -> Array:
|
61 |
+
"""
|
62 |
+
Array API compatible wrapper for :py:func:`np.reshape <numpy.reshape>`.
|
63 |
+
|
64 |
+
See its docstring for more information.
|
65 |
+
"""
|
66 |
+
|
67 |
+
data = x._array
|
68 |
+
if copy:
|
69 |
+
data = np.copy(data)
|
70 |
+
|
71 |
+
reshaped = np.reshape(data, shape)
|
72 |
+
|
73 |
+
if copy is False and not np.shares_memory(data, reshaped):
|
74 |
+
raise AttributeError("Incompatible shape for in-place modification.")
|
75 |
+
|
76 |
+
return Array._new(reshaped)
|
77 |
+
|
78 |
+
|
79 |
+
def roll(
|
80 |
+
x: Array,
|
81 |
+
/,
|
82 |
+
shift: Union[int, Tuple[int, ...]],
|
83 |
+
*,
|
84 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
85 |
+
) -> Array:
|
86 |
+
"""
|
87 |
+
Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`.
|
88 |
+
|
89 |
+
See its docstring for more information.
|
90 |
+
"""
|
91 |
+
return Array._new(np.roll(x._array, shift, axis=axis))
|
92 |
+
|
93 |
+
|
94 |
+
def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array:
|
95 |
+
"""
|
96 |
+
Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`.
|
97 |
+
|
98 |
+
See its docstring for more information.
|
99 |
+
"""
|
100 |
+
return Array._new(np.squeeze(x._array, axis=axis))
|
101 |
+
|
102 |
+
|
103 |
+
def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array:
|
104 |
+
"""
|
105 |
+
Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`.
|
106 |
+
|
107 |
+
See its docstring for more information.
|
108 |
+
"""
|
109 |
+
# Call result type here just to raise on disallowed type combinations
|
110 |
+
result_type(*arrays)
|
111 |
+
arrays = tuple(a._array for a in arrays)
|
112 |
+
return Array._new(np.stack(arrays, axis=axis))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_searching_functions.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
from ._dtypes import _result_type, _real_numeric_dtypes
|
5 |
+
|
6 |
+
from typing import Optional, Tuple
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
|
11 |
+
def argmax(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
|
12 |
+
"""
|
13 |
+
Array API compatible wrapper for :py:func:`np.argmax <numpy.argmax>`.
|
14 |
+
|
15 |
+
See its docstring for more information.
|
16 |
+
"""
|
17 |
+
if x.dtype not in _real_numeric_dtypes:
|
18 |
+
raise TypeError("Only real numeric dtypes are allowed in argmax")
|
19 |
+
return Array._new(np.asarray(np.argmax(x._array, axis=axis, keepdims=keepdims)))
|
20 |
+
|
21 |
+
|
22 |
+
def argmin(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
|
23 |
+
"""
|
24 |
+
Array API compatible wrapper for :py:func:`np.argmin <numpy.argmin>`.
|
25 |
+
|
26 |
+
See its docstring for more information.
|
27 |
+
"""
|
28 |
+
if x.dtype not in _real_numeric_dtypes:
|
29 |
+
raise TypeError("Only real numeric dtypes are allowed in argmin")
|
30 |
+
return Array._new(np.asarray(np.argmin(x._array, axis=axis, keepdims=keepdims)))
|
31 |
+
|
32 |
+
|
33 |
+
def nonzero(x: Array, /) -> Tuple[Array, ...]:
|
34 |
+
"""
|
35 |
+
Array API compatible wrapper for :py:func:`np.nonzero <numpy.nonzero>`.
|
36 |
+
|
37 |
+
See its docstring for more information.
|
38 |
+
"""
|
39 |
+
return tuple(Array._new(i) for i in np.nonzero(x._array))
|
40 |
+
|
41 |
+
|
42 |
+
def where(condition: Array, x1: Array, x2: Array, /) -> Array:
|
43 |
+
"""
|
44 |
+
Array API compatible wrapper for :py:func:`np.where <numpy.where>`.
|
45 |
+
|
46 |
+
See its docstring for more information.
|
47 |
+
"""
|
48 |
+
# Call result type here just to raise on disallowed type combinations
|
49 |
+
_result_type(x1.dtype, x2.dtype)
|
50 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
51 |
+
return Array._new(np.where(condition._array, x1._array, x2._array))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_sorting_functions.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
from ._dtypes import _real_numeric_dtypes
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
|
9 |
+
# Note: the descending keyword argument is new in this function
|
10 |
+
def argsort(
|
11 |
+
x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True
|
12 |
+
) -> Array:
|
13 |
+
"""
|
14 |
+
Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`.
|
15 |
+
|
16 |
+
See its docstring for more information.
|
17 |
+
"""
|
18 |
+
if x.dtype not in _real_numeric_dtypes:
|
19 |
+
raise TypeError("Only real numeric dtypes are allowed in argsort")
|
20 |
+
# Note: this keyword argument is different, and the default is different.
|
21 |
+
kind = "stable" if stable else "quicksort"
|
22 |
+
if not descending:
|
23 |
+
res = np.argsort(x._array, axis=axis, kind=kind)
|
24 |
+
else:
|
25 |
+
# As NumPy has no native descending sort, we imitate it here. Note that
|
26 |
+
# simply flipping the results of np.argsort(x._array, ...) would not
|
27 |
+
# respect the relative order like it would in native descending sorts.
|
28 |
+
res = np.flip(
|
29 |
+
np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind),
|
30 |
+
axis=axis,
|
31 |
+
)
|
32 |
+
# Rely on flip()/argsort() to validate axis
|
33 |
+
normalised_axis = axis if axis >= 0 else x.ndim + axis
|
34 |
+
max_i = x.shape[normalised_axis] - 1
|
35 |
+
res = max_i - res
|
36 |
+
return Array._new(res)
|
37 |
+
|
38 |
+
# Note: the descending keyword argument is new in this function
|
39 |
+
def sort(
|
40 |
+
x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True
|
41 |
+
) -> Array:
|
42 |
+
"""
|
43 |
+
Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`.
|
44 |
+
|
45 |
+
See its docstring for more information.
|
46 |
+
"""
|
47 |
+
if x.dtype not in _real_numeric_dtypes:
|
48 |
+
raise TypeError("Only real numeric dtypes are allowed in sort")
|
49 |
+
# Note: this keyword argument is different, and the default is different.
|
50 |
+
kind = "stable" if stable else "quicksort"
|
51 |
+
res = np.sort(x._array, axis=axis, kind=kind)
|
52 |
+
if descending:
|
53 |
+
res = np.flip(res, axis=axis)
|
54 |
+
return Array._new(res)
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_typing.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This file defines the types for type annotations.
|
3 |
+
|
4 |
+
These names aren't part of the module namespace, but they are used in the
|
5 |
+
annotations in the function signatures. The functions in the module are only
|
6 |
+
valid for inputs that match the given type annotations.
|
7 |
+
"""
|
8 |
+
|
9 |
+
from __future__ import annotations
|
10 |
+
|
11 |
+
__all__ = [
|
12 |
+
"Array",
|
13 |
+
"Device",
|
14 |
+
"Dtype",
|
15 |
+
"SupportsDLPack",
|
16 |
+
"SupportsBufferProtocol",
|
17 |
+
"PyCapsule",
|
18 |
+
]
|
19 |
+
|
20 |
+
import sys
|
21 |
+
|
22 |
+
from typing import (
|
23 |
+
Any,
|
24 |
+
Literal,
|
25 |
+
Sequence,
|
26 |
+
Type,
|
27 |
+
Union,
|
28 |
+
TypeVar,
|
29 |
+
Protocol,
|
30 |
+
)
|
31 |
+
|
32 |
+
from ._array_object import Array
|
33 |
+
from numpy import (
|
34 |
+
dtype,
|
35 |
+
int8,
|
36 |
+
int16,
|
37 |
+
int32,
|
38 |
+
int64,
|
39 |
+
uint8,
|
40 |
+
uint16,
|
41 |
+
uint32,
|
42 |
+
uint64,
|
43 |
+
float32,
|
44 |
+
float64,
|
45 |
+
)
|
46 |
+
|
47 |
+
_T_co = TypeVar("_T_co", covariant=True)
|
48 |
+
|
49 |
+
class NestedSequence(Protocol[_T_co]):
|
50 |
+
def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
|
51 |
+
def __len__(self, /) -> int: ...
|
52 |
+
|
53 |
+
Device = Literal["cpu"]
|
54 |
+
|
55 |
+
Dtype = dtype[Union[
|
56 |
+
int8,
|
57 |
+
int16,
|
58 |
+
int32,
|
59 |
+
int64,
|
60 |
+
uint8,
|
61 |
+
uint16,
|
62 |
+
uint32,
|
63 |
+
uint64,
|
64 |
+
float32,
|
65 |
+
float64,
|
66 |
+
]]
|
67 |
+
|
68 |
+
if sys.version_info >= (3, 12):
|
69 |
+
from collections.abc import Buffer as SupportsBufferProtocol
|
70 |
+
else:
|
71 |
+
SupportsBufferProtocol = Any
|
72 |
+
|
73 |
+
PyCapsule = Any
|
74 |
+
|
75 |
+
class SupportsDLPack(Protocol):
|
76 |
+
def __dlpack__(self, /, *, stream: None = ...) -> PyCapsule: ...
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_utility_functions.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
|
5 |
+
from typing import Optional, Tuple, Union
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
|
10 |
+
def all(
|
11 |
+
x: Array,
|
12 |
+
/,
|
13 |
+
*,
|
14 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
15 |
+
keepdims: bool = False,
|
16 |
+
) -> Array:
|
17 |
+
"""
|
18 |
+
Array API compatible wrapper for :py:func:`np.all <numpy.all>`.
|
19 |
+
|
20 |
+
See its docstring for more information.
|
21 |
+
"""
|
22 |
+
return Array._new(np.asarray(np.all(x._array, axis=axis, keepdims=keepdims)))
|
23 |
+
|
24 |
+
|
25 |
+
def any(
|
26 |
+
x: Array,
|
27 |
+
/,
|
28 |
+
*,
|
29 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
30 |
+
keepdims: bool = False,
|
31 |
+
) -> Array:
|
32 |
+
"""
|
33 |
+
Array API compatible wrapper for :py:func:`np.any <numpy.any>`.
|
34 |
+
|
35 |
+
See its docstring for more information.
|
36 |
+
"""
|
37 |
+
return Array._new(np.asarray(np.any(x._array, axis=axis, keepdims=keepdims)))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__init__.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests for the array API namespace.
|
3 |
+
|
4 |
+
Note, full compliance with the array API can be tested with the official array API test
|
5 |
+
suite https://github.com/data-apis/array-api-tests. This test suite primarily
|
6 |
+
focuses on those things that are not tested by the official test suite.
|
7 |
+
"""
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (476 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_array_object.cpython-310.pyc
ADDED
Binary file (14.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_creation_functions.cpython-310.pyc
ADDED
Binary file (8.12 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_data_type_functions.cpython-310.pyc
ADDED
Binary file (1.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_elementwise_functions.cpython-310.pyc
ADDED
Binary file (3.18 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_indexing_functions.cpython-310.pyc
ADDED
Binary file (852 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_manipulation_functions.cpython-310.pyc
ADDED
Binary file (1.77 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_set_functions.cpython-310.pyc
ADDED
Binary file (831 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_sorting_functions.cpython-310.pyc
ADDED
Binary file (848 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/__pycache__/test_validation.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_array_object.py
ADDED
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import operator
|
2 |
+
|
3 |
+
from numpy.testing import assert_raises, suppress_warnings
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from .. import ones, asarray, reshape, result_type, all, equal
|
8 |
+
from .._array_object import Array
|
9 |
+
from .._dtypes import (
|
10 |
+
_all_dtypes,
|
11 |
+
_boolean_dtypes,
|
12 |
+
_real_floating_dtypes,
|
13 |
+
_floating_dtypes,
|
14 |
+
_complex_floating_dtypes,
|
15 |
+
_integer_dtypes,
|
16 |
+
_integer_or_boolean_dtypes,
|
17 |
+
_real_numeric_dtypes,
|
18 |
+
_numeric_dtypes,
|
19 |
+
int8,
|
20 |
+
int16,
|
21 |
+
int32,
|
22 |
+
int64,
|
23 |
+
uint64,
|
24 |
+
bool as bool_,
|
25 |
+
)
|
26 |
+
|
27 |
+
|
28 |
+
def test_validate_index():
|
29 |
+
# The indexing tests in the official array API test suite test that the
|
30 |
+
# array object correctly handles the subset of indices that are required
|
31 |
+
# by the spec. But the NumPy array API implementation specifically
|
32 |
+
# disallows any index not required by the spec, via Array._validate_index.
|
33 |
+
# This test focuses on testing that non-valid indices are correctly
|
34 |
+
# rejected. See
|
35 |
+
# https://data-apis.org/array-api/latest/API_specification/indexing.html
|
36 |
+
# and the docstring of Array._validate_index for the exact indexing
|
37 |
+
# behavior that should be allowed. This does not test indices that are
|
38 |
+
# already invalid in NumPy itself because Array will generally just pass
|
39 |
+
# such indices directly to the underlying np.ndarray.
|
40 |
+
|
41 |
+
a = ones((3, 4))
|
42 |
+
|
43 |
+
# Out of bounds slices are not allowed
|
44 |
+
assert_raises(IndexError, lambda: a[:4])
|
45 |
+
assert_raises(IndexError, lambda: a[:-4])
|
46 |
+
assert_raises(IndexError, lambda: a[:3:-1])
|
47 |
+
assert_raises(IndexError, lambda: a[:-5:-1])
|
48 |
+
assert_raises(IndexError, lambda: a[4:])
|
49 |
+
assert_raises(IndexError, lambda: a[-4:])
|
50 |
+
assert_raises(IndexError, lambda: a[4::-1])
|
51 |
+
assert_raises(IndexError, lambda: a[-4::-1])
|
52 |
+
|
53 |
+
assert_raises(IndexError, lambda: a[...,:5])
|
54 |
+
assert_raises(IndexError, lambda: a[...,:-5])
|
55 |
+
assert_raises(IndexError, lambda: a[...,:5:-1])
|
56 |
+
assert_raises(IndexError, lambda: a[...,:-6:-1])
|
57 |
+
assert_raises(IndexError, lambda: a[...,5:])
|
58 |
+
assert_raises(IndexError, lambda: a[...,-5:])
|
59 |
+
assert_raises(IndexError, lambda: a[...,5::-1])
|
60 |
+
assert_raises(IndexError, lambda: a[...,-5::-1])
|
61 |
+
|
62 |
+
# Boolean indices cannot be part of a larger tuple index
|
63 |
+
assert_raises(IndexError, lambda: a[a[:,0]==1,0])
|
64 |
+
assert_raises(IndexError, lambda: a[a[:,0]==1,...])
|
65 |
+
assert_raises(IndexError, lambda: a[..., a[0]==1])
|
66 |
+
assert_raises(IndexError, lambda: a[[True, True, True]])
|
67 |
+
assert_raises(IndexError, lambda: a[(True, True, True),])
|
68 |
+
|
69 |
+
# Integer array indices are not allowed (except for 0-D)
|
70 |
+
idx = asarray([[0, 1]])
|
71 |
+
assert_raises(IndexError, lambda: a[idx])
|
72 |
+
assert_raises(IndexError, lambda: a[idx,])
|
73 |
+
assert_raises(IndexError, lambda: a[[0, 1]])
|
74 |
+
assert_raises(IndexError, lambda: a[(0, 1), (0, 1)])
|
75 |
+
assert_raises(IndexError, lambda: a[[0, 1]])
|
76 |
+
assert_raises(IndexError, lambda: a[np.array([[0, 1]])])
|
77 |
+
|
78 |
+
# Multiaxis indices must contain exactly as many indices as dimensions
|
79 |
+
assert_raises(IndexError, lambda: a[()])
|
80 |
+
assert_raises(IndexError, lambda: a[0,])
|
81 |
+
assert_raises(IndexError, lambda: a[0])
|
82 |
+
assert_raises(IndexError, lambda: a[:])
|
83 |
+
|
84 |
+
def test_operators():
|
85 |
+
# For every operator, we test that it works for the required type
|
86 |
+
# combinations and raises TypeError otherwise
|
87 |
+
binary_op_dtypes = {
|
88 |
+
"__add__": "numeric",
|
89 |
+
"__and__": "integer_or_boolean",
|
90 |
+
"__eq__": "all",
|
91 |
+
"__floordiv__": "real numeric",
|
92 |
+
"__ge__": "real numeric",
|
93 |
+
"__gt__": "real numeric",
|
94 |
+
"__le__": "real numeric",
|
95 |
+
"__lshift__": "integer",
|
96 |
+
"__lt__": "real numeric",
|
97 |
+
"__mod__": "real numeric",
|
98 |
+
"__mul__": "numeric",
|
99 |
+
"__ne__": "all",
|
100 |
+
"__or__": "integer_or_boolean",
|
101 |
+
"__pow__": "numeric",
|
102 |
+
"__rshift__": "integer",
|
103 |
+
"__sub__": "numeric",
|
104 |
+
"__truediv__": "floating",
|
105 |
+
"__xor__": "integer_or_boolean",
|
106 |
+
}
|
107 |
+
# Recompute each time because of in-place ops
|
108 |
+
def _array_vals():
|
109 |
+
for d in _integer_dtypes:
|
110 |
+
yield asarray(1, dtype=d)
|
111 |
+
for d in _boolean_dtypes:
|
112 |
+
yield asarray(False, dtype=d)
|
113 |
+
for d in _floating_dtypes:
|
114 |
+
yield asarray(1.0, dtype=d)
|
115 |
+
|
116 |
+
|
117 |
+
BIG_INT = int(1e30)
|
118 |
+
for op, dtypes in binary_op_dtypes.items():
|
119 |
+
ops = [op]
|
120 |
+
if op not in ["__eq__", "__ne__", "__le__", "__ge__", "__lt__", "__gt__"]:
|
121 |
+
rop = "__r" + op[2:]
|
122 |
+
iop = "__i" + op[2:]
|
123 |
+
ops += [rop, iop]
|
124 |
+
for s in [1, 1.0, 1j, BIG_INT, False]:
|
125 |
+
for _op in ops:
|
126 |
+
for a in _array_vals():
|
127 |
+
# Test array op scalar. From the spec, the following combinations
|
128 |
+
# are supported:
|
129 |
+
|
130 |
+
# - Python bool for a bool array dtype,
|
131 |
+
# - a Python int within the bounds of the given dtype for integer array dtypes,
|
132 |
+
# - a Python int or float for real floating-point array dtypes
|
133 |
+
# - a Python int, float, or complex for complex floating-point array dtypes
|
134 |
+
|
135 |
+
if ((dtypes == "all"
|
136 |
+
or dtypes == "numeric" and a.dtype in _numeric_dtypes
|
137 |
+
or dtypes == "real numeric" and a.dtype in _real_numeric_dtypes
|
138 |
+
or dtypes == "integer" and a.dtype in _integer_dtypes
|
139 |
+
or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes
|
140 |
+
or dtypes == "boolean" and a.dtype in _boolean_dtypes
|
141 |
+
or dtypes == "floating" and a.dtype in _floating_dtypes
|
142 |
+
)
|
143 |
+
# bool is a subtype of int, which is why we avoid
|
144 |
+
# isinstance here.
|
145 |
+
and (a.dtype in _boolean_dtypes and type(s) == bool
|
146 |
+
or a.dtype in _integer_dtypes and type(s) == int
|
147 |
+
or a.dtype in _real_floating_dtypes and type(s) in [float, int]
|
148 |
+
or a.dtype in _complex_floating_dtypes and type(s) in [complex, float, int]
|
149 |
+
)):
|
150 |
+
if a.dtype in _integer_dtypes and s == BIG_INT:
|
151 |
+
assert_raises(OverflowError, lambda: getattr(a, _op)(s))
|
152 |
+
else:
|
153 |
+
# Only test for no error
|
154 |
+
with suppress_warnings() as sup:
|
155 |
+
# ignore warnings from pow(BIG_INT)
|
156 |
+
sup.filter(RuntimeWarning,
|
157 |
+
"invalid value encountered in power")
|
158 |
+
getattr(a, _op)(s)
|
159 |
+
else:
|
160 |
+
assert_raises(TypeError, lambda: getattr(a, _op)(s))
|
161 |
+
|
162 |
+
# Test array op array.
|
163 |
+
for _op in ops:
|
164 |
+
for x in _array_vals():
|
165 |
+
for y in _array_vals():
|
166 |
+
# See the promotion table in NEP 47 or the array
|
167 |
+
# API spec page on type promotion. Mixed kind
|
168 |
+
# promotion is not defined.
|
169 |
+
if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
|
170 |
+
or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
|
171 |
+
or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
|
172 |
+
or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
|
173 |
+
or x.dtype in _boolean_dtypes and y.dtype not in _boolean_dtypes
|
174 |
+
or y.dtype in _boolean_dtypes and x.dtype not in _boolean_dtypes
|
175 |
+
or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
|
176 |
+
or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
|
177 |
+
):
|
178 |
+
assert_raises(TypeError, lambda: getattr(x, _op)(y))
|
179 |
+
# Ensure in-place operators only promote to the same dtype as the left operand.
|
180 |
+
elif (
|
181 |
+
_op.startswith("__i")
|
182 |
+
and result_type(x.dtype, y.dtype) != x.dtype
|
183 |
+
):
|
184 |
+
assert_raises(TypeError, lambda: getattr(x, _op)(y))
|
185 |
+
# Ensure only those dtypes that are required for every operator are allowed.
|
186 |
+
elif (dtypes == "all" and (x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
|
187 |
+
or x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
|
188 |
+
or (dtypes == "real numeric" and x.dtype in _real_numeric_dtypes and y.dtype in _real_numeric_dtypes)
|
189 |
+
or (dtypes == "numeric" and x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
|
190 |
+
or dtypes == "integer" and x.dtype in _integer_dtypes and y.dtype in _integer_dtypes
|
191 |
+
or dtypes == "integer_or_boolean" and (x.dtype in _integer_dtypes and y.dtype in _integer_dtypes
|
192 |
+
or x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes)
|
193 |
+
or dtypes == "boolean" and x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
|
194 |
+
or dtypes == "floating" and x.dtype in _floating_dtypes and y.dtype in _floating_dtypes
|
195 |
+
):
|
196 |
+
getattr(x, _op)(y)
|
197 |
+
else:
|
198 |
+
assert_raises(TypeError, lambda: getattr(x, _op)(y))
|
199 |
+
|
200 |
+
unary_op_dtypes = {
|
201 |
+
"__abs__": "numeric",
|
202 |
+
"__invert__": "integer_or_boolean",
|
203 |
+
"__neg__": "numeric",
|
204 |
+
"__pos__": "numeric",
|
205 |
+
}
|
206 |
+
for op, dtypes in unary_op_dtypes.items():
|
207 |
+
for a in _array_vals():
|
208 |
+
if (
|
209 |
+
dtypes == "numeric"
|
210 |
+
and a.dtype in _numeric_dtypes
|
211 |
+
or dtypes == "integer_or_boolean"
|
212 |
+
and a.dtype in _integer_or_boolean_dtypes
|
213 |
+
):
|
214 |
+
# Only test for no error
|
215 |
+
getattr(a, op)()
|
216 |
+
else:
|
217 |
+
assert_raises(TypeError, lambda: getattr(a, op)())
|
218 |
+
|
219 |
+
# Finally, matmul() must be tested separately, because it works a bit
|
220 |
+
# different from the other operations.
|
221 |
+
def _matmul_array_vals():
|
222 |
+
for a in _array_vals():
|
223 |
+
yield a
|
224 |
+
for d in _all_dtypes:
|
225 |
+
yield ones((3, 4), dtype=d)
|
226 |
+
yield ones((4, 2), dtype=d)
|
227 |
+
yield ones((4, 4), dtype=d)
|
228 |
+
|
229 |
+
# Scalars always error
|
230 |
+
for _op in ["__matmul__", "__rmatmul__", "__imatmul__"]:
|
231 |
+
for s in [1, 1.0, False]:
|
232 |
+
for a in _matmul_array_vals():
|
233 |
+
if (type(s) in [float, int] and a.dtype in _floating_dtypes
|
234 |
+
or type(s) == int and a.dtype in _integer_dtypes):
|
235 |
+
# Type promotion is valid, but @ is not allowed on 0-D
|
236 |
+
# inputs, so the error is a ValueError
|
237 |
+
assert_raises(ValueError, lambda: getattr(a, _op)(s))
|
238 |
+
else:
|
239 |
+
assert_raises(TypeError, lambda: getattr(a, _op)(s))
|
240 |
+
|
241 |
+
for x in _matmul_array_vals():
|
242 |
+
for y in _matmul_array_vals():
|
243 |
+
if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
|
244 |
+
or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
|
245 |
+
or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
|
246 |
+
or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
|
247 |
+
or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
|
248 |
+
or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
|
249 |
+
or x.dtype in _boolean_dtypes
|
250 |
+
or y.dtype in _boolean_dtypes
|
251 |
+
):
|
252 |
+
assert_raises(TypeError, lambda: x.__matmul__(y))
|
253 |
+
assert_raises(TypeError, lambda: y.__rmatmul__(x))
|
254 |
+
assert_raises(TypeError, lambda: x.__imatmul__(y))
|
255 |
+
elif x.shape == () or y.shape == () or x.shape[1] != y.shape[0]:
|
256 |
+
assert_raises(ValueError, lambda: x.__matmul__(y))
|
257 |
+
assert_raises(ValueError, lambda: y.__rmatmul__(x))
|
258 |
+
if result_type(x.dtype, y.dtype) != x.dtype:
|
259 |
+
assert_raises(TypeError, lambda: x.__imatmul__(y))
|
260 |
+
else:
|
261 |
+
assert_raises(ValueError, lambda: x.__imatmul__(y))
|
262 |
+
else:
|
263 |
+
x.__matmul__(y)
|
264 |
+
y.__rmatmul__(x)
|
265 |
+
if result_type(x.dtype, y.dtype) != x.dtype:
|
266 |
+
assert_raises(TypeError, lambda: x.__imatmul__(y))
|
267 |
+
elif y.shape[0] != y.shape[1]:
|
268 |
+
# This one fails because x @ y has a different shape from x
|
269 |
+
assert_raises(ValueError, lambda: x.__imatmul__(y))
|
270 |
+
else:
|
271 |
+
x.__imatmul__(y)
|
272 |
+
|
273 |
+
|
274 |
+
def test_python_scalar_construtors():
|
275 |
+
b = asarray(False)
|
276 |
+
i = asarray(0)
|
277 |
+
f = asarray(0.0)
|
278 |
+
c = asarray(0j)
|
279 |
+
|
280 |
+
assert bool(b) == False
|
281 |
+
assert int(i) == 0
|
282 |
+
assert float(f) == 0.0
|
283 |
+
assert operator.index(i) == 0
|
284 |
+
|
285 |
+
# bool/int/float/complex should only be allowed on 0-D arrays.
|
286 |
+
assert_raises(TypeError, lambda: bool(asarray([False])))
|
287 |
+
assert_raises(TypeError, lambda: int(asarray([0])))
|
288 |
+
assert_raises(TypeError, lambda: float(asarray([0.0])))
|
289 |
+
assert_raises(TypeError, lambda: complex(asarray([0j])))
|
290 |
+
assert_raises(TypeError, lambda: operator.index(asarray([0])))
|
291 |
+
|
292 |
+
# bool should work on all types of arrays
|
293 |
+
assert bool(b) is bool(i) is bool(f) is bool(c) is False
|
294 |
+
|
295 |
+
# int should fail on complex arrays
|
296 |
+
assert int(b) == int(i) == int(f) == 0
|
297 |
+
assert_raises(TypeError, lambda: int(c))
|
298 |
+
|
299 |
+
# float should fail on complex arrays
|
300 |
+
assert float(b) == float(i) == float(f) == 0.0
|
301 |
+
assert_raises(TypeError, lambda: float(c))
|
302 |
+
|
303 |
+
# complex should work on all types of arrays
|
304 |
+
assert complex(b) == complex(i) == complex(f) == complex(c) == 0j
|
305 |
+
|
306 |
+
# index should only work on integer arrays
|
307 |
+
assert operator.index(i) == 0
|
308 |
+
assert_raises(TypeError, lambda: operator.index(b))
|
309 |
+
assert_raises(TypeError, lambda: operator.index(f))
|
310 |
+
assert_raises(TypeError, lambda: operator.index(c))
|
311 |
+
|
312 |
+
|
313 |
+
def test_device_property():
|
314 |
+
a = ones((3, 4))
|
315 |
+
assert a.device == 'cpu'
|
316 |
+
|
317 |
+
assert all(equal(a.to_device('cpu'), a))
|
318 |
+
assert_raises(ValueError, lambda: a.to_device('gpu'))
|
319 |
+
|
320 |
+
assert all(equal(asarray(a, device='cpu'), a))
|
321 |
+
assert_raises(ValueError, lambda: asarray(a, device='gpu'))
|
322 |
+
|
323 |
+
def test_array_properties():
|
324 |
+
a = ones((1, 2, 3))
|
325 |
+
b = ones((2, 3))
|
326 |
+
assert_raises(ValueError, lambda: a.T)
|
327 |
+
|
328 |
+
assert isinstance(b.T, Array)
|
329 |
+
assert b.T.shape == (3, 2)
|
330 |
+
|
331 |
+
assert isinstance(a.mT, Array)
|
332 |
+
assert a.mT.shape == (1, 3, 2)
|
333 |
+
assert isinstance(b.mT, Array)
|
334 |
+
assert b.mT.shape == (3, 2)
|
335 |
+
|
336 |
+
def test___array__():
|
337 |
+
a = ones((2, 3), dtype=int16)
|
338 |
+
assert np.asarray(a) is a._array
|
339 |
+
b = np.asarray(a, dtype=np.float64)
|
340 |
+
assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
|
341 |
+
assert b.dtype == np.float64
|
342 |
+
|
343 |
+
def test_allow_newaxis():
|
344 |
+
a = ones(5)
|
345 |
+
indexed_a = a[None, :]
|
346 |
+
assert indexed_a.shape == (1, 5)
|
347 |
+
|
348 |
+
def test_disallow_flat_indexing_with_newaxis():
|
349 |
+
a = ones((3, 3, 3))
|
350 |
+
with pytest.raises(IndexError):
|
351 |
+
a[None, 0, 0]
|
352 |
+
|
353 |
+
def test_disallow_mask_with_newaxis():
|
354 |
+
a = ones((3, 3, 3))
|
355 |
+
with pytest.raises(IndexError):
|
356 |
+
a[None, asarray(True)]
|
357 |
+
|
358 |
+
@pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)])
|
359 |
+
@pytest.mark.parametrize("index", ["string", False, True])
|
360 |
+
def test_error_on_invalid_index(shape, index):
|
361 |
+
a = ones(shape)
|
362 |
+
with pytest.raises(IndexError):
|
363 |
+
a[index]
|
364 |
+
|
365 |
+
def test_mask_0d_array_without_errors():
|
366 |
+
a = ones(())
|
367 |
+
a[asarray(True)]
|
368 |
+
|
369 |
+
@pytest.mark.parametrize(
|
370 |
+
"i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])]
|
371 |
+
)
|
372 |
+
def test_error_on_invalid_index_with_ellipsis(i):
|
373 |
+
a = ones((3, 3, 3))
|
374 |
+
with pytest.raises(IndexError):
|
375 |
+
a[..., i]
|
376 |
+
with pytest.raises(IndexError):
|
377 |
+
a[i, ...]
|
378 |
+
|
379 |
+
def test_array_keys_use_private_array():
|
380 |
+
"""
|
381 |
+
Indexing operations convert array keys before indexing the internal array
|
382 |
+
|
383 |
+
Fails when array_api array keys are not converted into NumPy-proper arrays
|
384 |
+
in __getitem__(). This is achieved by passing array_api arrays with 0-sized
|
385 |
+
dimensions, which NumPy-proper treats erroneously - not sure why!
|
386 |
+
|
387 |
+
TODO: Find and use appropriate __setitem__() case.
|
388 |
+
"""
|
389 |
+
a = ones((0, 0), dtype=bool_)
|
390 |
+
assert a[a].shape == (0,)
|
391 |
+
|
392 |
+
a = ones((0,), dtype=bool_)
|
393 |
+
key = ones((0, 0), dtype=bool_)
|
394 |
+
with pytest.raises(IndexError):
|
395 |
+
a[key]
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_creation_functions.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.testing import assert_raises
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from .. import all
|
5 |
+
from .._creation_functions import (
|
6 |
+
asarray,
|
7 |
+
arange,
|
8 |
+
empty,
|
9 |
+
empty_like,
|
10 |
+
eye,
|
11 |
+
full,
|
12 |
+
full_like,
|
13 |
+
linspace,
|
14 |
+
meshgrid,
|
15 |
+
ones,
|
16 |
+
ones_like,
|
17 |
+
zeros,
|
18 |
+
zeros_like,
|
19 |
+
)
|
20 |
+
from .._dtypes import float32, float64
|
21 |
+
from .._array_object import Array
|
22 |
+
|
23 |
+
|
24 |
+
def test_asarray_errors():
|
25 |
+
# Test various protections against incorrect usage
|
26 |
+
assert_raises(TypeError, lambda: Array([1]))
|
27 |
+
assert_raises(TypeError, lambda: asarray(["a"]))
|
28 |
+
assert_raises(ValueError, lambda: asarray([1.0], dtype=np.float16))
|
29 |
+
assert_raises(OverflowError, lambda: asarray(2**100))
|
30 |
+
# Preferably this would be OverflowError
|
31 |
+
# assert_raises(OverflowError, lambda: asarray([2**100]))
|
32 |
+
assert_raises(TypeError, lambda: asarray([2**100]))
|
33 |
+
asarray([1], device="cpu") # Doesn't error
|
34 |
+
assert_raises(ValueError, lambda: asarray([1], device="gpu"))
|
35 |
+
|
36 |
+
assert_raises(ValueError, lambda: asarray([1], dtype=int))
|
37 |
+
assert_raises(ValueError, lambda: asarray([1], dtype="i"))
|
38 |
+
|
39 |
+
|
40 |
+
def test_asarray_copy():
|
41 |
+
a = asarray([1])
|
42 |
+
b = asarray(a, copy=True)
|
43 |
+
a[0] = 0
|
44 |
+
assert all(b[0] == 1)
|
45 |
+
assert all(a[0] == 0)
|
46 |
+
a = asarray([1])
|
47 |
+
b = asarray(a, copy=np._CopyMode.ALWAYS)
|
48 |
+
a[0] = 0
|
49 |
+
assert all(b[0] == 1)
|
50 |
+
assert all(a[0] == 0)
|
51 |
+
a = asarray([1])
|
52 |
+
b = asarray(a, copy=np._CopyMode.NEVER)
|
53 |
+
a[0] = 0
|
54 |
+
assert all(b[0] == 0)
|
55 |
+
assert_raises(NotImplementedError, lambda: asarray(a, copy=False))
|
56 |
+
assert_raises(NotImplementedError,
|
57 |
+
lambda: asarray(a, copy=np._CopyMode.IF_NEEDED))
|
58 |
+
|
59 |
+
|
60 |
+
def test_arange_errors():
|
61 |
+
arange(1, device="cpu") # Doesn't error
|
62 |
+
assert_raises(ValueError, lambda: arange(1, device="gpu"))
|
63 |
+
assert_raises(ValueError, lambda: arange(1, dtype=int))
|
64 |
+
assert_raises(ValueError, lambda: arange(1, dtype="i"))
|
65 |
+
|
66 |
+
|
67 |
+
def test_empty_errors():
|
68 |
+
empty((1,), device="cpu") # Doesn't error
|
69 |
+
assert_raises(ValueError, lambda: empty((1,), device="gpu"))
|
70 |
+
assert_raises(ValueError, lambda: empty((1,), dtype=int))
|
71 |
+
assert_raises(ValueError, lambda: empty((1,), dtype="i"))
|
72 |
+
|
73 |
+
|
74 |
+
def test_empty_like_errors():
|
75 |
+
empty_like(asarray(1), device="cpu") # Doesn't error
|
76 |
+
assert_raises(ValueError, lambda: empty_like(asarray(1), device="gpu"))
|
77 |
+
assert_raises(ValueError, lambda: empty_like(asarray(1), dtype=int))
|
78 |
+
assert_raises(ValueError, lambda: empty_like(asarray(1), dtype="i"))
|
79 |
+
|
80 |
+
|
81 |
+
def test_eye_errors():
|
82 |
+
eye(1, device="cpu") # Doesn't error
|
83 |
+
assert_raises(ValueError, lambda: eye(1, device="gpu"))
|
84 |
+
assert_raises(ValueError, lambda: eye(1, dtype=int))
|
85 |
+
assert_raises(ValueError, lambda: eye(1, dtype="i"))
|
86 |
+
|
87 |
+
|
88 |
+
def test_full_errors():
|
89 |
+
full((1,), 0, device="cpu") # Doesn't error
|
90 |
+
assert_raises(ValueError, lambda: full((1,), 0, device="gpu"))
|
91 |
+
assert_raises(ValueError, lambda: full((1,), 0, dtype=int))
|
92 |
+
assert_raises(ValueError, lambda: full((1,), 0, dtype="i"))
|
93 |
+
|
94 |
+
|
95 |
+
def test_full_like_errors():
|
96 |
+
full_like(asarray(1), 0, device="cpu") # Doesn't error
|
97 |
+
assert_raises(ValueError, lambda: full_like(asarray(1), 0, device="gpu"))
|
98 |
+
assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype=int))
|
99 |
+
assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype="i"))
|
100 |
+
|
101 |
+
|
102 |
+
def test_linspace_errors():
|
103 |
+
linspace(0, 1, 10, device="cpu") # Doesn't error
|
104 |
+
assert_raises(ValueError, lambda: linspace(0, 1, 10, device="gpu"))
|
105 |
+
assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype=float))
|
106 |
+
assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype="f"))
|
107 |
+
|
108 |
+
|
109 |
+
def test_ones_errors():
|
110 |
+
ones((1,), device="cpu") # Doesn't error
|
111 |
+
assert_raises(ValueError, lambda: ones((1,), device="gpu"))
|
112 |
+
assert_raises(ValueError, lambda: ones((1,), dtype=int))
|
113 |
+
assert_raises(ValueError, lambda: ones((1,), dtype="i"))
|
114 |
+
|
115 |
+
|
116 |
+
def test_ones_like_errors():
|
117 |
+
ones_like(asarray(1), device="cpu") # Doesn't error
|
118 |
+
assert_raises(ValueError, lambda: ones_like(asarray(1), device="gpu"))
|
119 |
+
assert_raises(ValueError, lambda: ones_like(asarray(1), dtype=int))
|
120 |
+
assert_raises(ValueError, lambda: ones_like(asarray(1), dtype="i"))
|
121 |
+
|
122 |
+
|
123 |
+
def test_zeros_errors():
|
124 |
+
zeros((1,), device="cpu") # Doesn't error
|
125 |
+
assert_raises(ValueError, lambda: zeros((1,), device="gpu"))
|
126 |
+
assert_raises(ValueError, lambda: zeros((1,), dtype=int))
|
127 |
+
assert_raises(ValueError, lambda: zeros((1,), dtype="i"))
|
128 |
+
|
129 |
+
|
130 |
+
def test_zeros_like_errors():
|
131 |
+
zeros_like(asarray(1), device="cpu") # Doesn't error
|
132 |
+
assert_raises(ValueError, lambda: zeros_like(asarray(1), device="gpu"))
|
133 |
+
assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype=int))
|
134 |
+
assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype="i"))
|
135 |
+
|
136 |
+
def test_meshgrid_dtype_errors():
|
137 |
+
# Doesn't raise
|
138 |
+
meshgrid()
|
139 |
+
meshgrid(asarray([1.], dtype=float32))
|
140 |
+
meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float32))
|
141 |
+
|
142 |
+
assert_raises(ValueError, lambda: meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float64)))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_data_type_functions.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from numpy.testing import assert_raises
|
4 |
+
from numpy import array_api as xp
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
@pytest.mark.parametrize(
|
8 |
+
"from_, to, expected",
|
9 |
+
[
|
10 |
+
(xp.int8, xp.int16, True),
|
11 |
+
(xp.int16, xp.int8, False),
|
12 |
+
(xp.bool, xp.int8, False),
|
13 |
+
(xp.asarray(0, dtype=xp.uint8), xp.int8, False),
|
14 |
+
],
|
15 |
+
)
|
16 |
+
def test_can_cast(from_, to, expected):
|
17 |
+
"""
|
18 |
+
can_cast() returns correct result
|
19 |
+
"""
|
20 |
+
assert xp.can_cast(from_, to) == expected
|
21 |
+
|
22 |
+
def test_isdtype_strictness():
|
23 |
+
assert_raises(TypeError, lambda: xp.isdtype(xp.float64, 64))
|
24 |
+
assert_raises(ValueError, lambda: xp.isdtype(xp.float64, 'f8'))
|
25 |
+
|
26 |
+
assert_raises(TypeError, lambda: xp.isdtype(xp.float64, (('integral',),)))
|
27 |
+
assert_raises(TypeError, lambda: xp.isdtype(xp.float64, np.object_))
|
28 |
+
|
29 |
+
# TODO: These will require https://github.com/numpy/numpy/issues/23883
|
30 |
+
# assert_raises(TypeError, lambda: xp.isdtype(xp.float64, None))
|
31 |
+
# assert_raises(TypeError, lambda: xp.isdtype(xp.float64, np.float64))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_elementwise_functions.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from inspect import getfullargspec
|
2 |
+
|
3 |
+
from numpy.testing import assert_raises
|
4 |
+
|
5 |
+
from .. import asarray, _elementwise_functions
|
6 |
+
from .._elementwise_functions import bitwise_left_shift, bitwise_right_shift
|
7 |
+
from .._dtypes import (
|
8 |
+
_dtype_categories,
|
9 |
+
_boolean_dtypes,
|
10 |
+
_floating_dtypes,
|
11 |
+
_integer_dtypes,
|
12 |
+
)
|
13 |
+
|
14 |
+
|
15 |
+
def nargs(func):
|
16 |
+
return len(getfullargspec(func).args)
|
17 |
+
|
18 |
+
|
19 |
+
def test_function_types():
|
20 |
+
# Test that every function accepts only the required input types. We only
|
21 |
+
# test the negative cases here (error). The positive cases are tested in
|
22 |
+
# the array API test suite.
|
23 |
+
|
24 |
+
elementwise_function_input_types = {
|
25 |
+
"abs": "numeric",
|
26 |
+
"acos": "floating-point",
|
27 |
+
"acosh": "floating-point",
|
28 |
+
"add": "numeric",
|
29 |
+
"asin": "floating-point",
|
30 |
+
"asinh": "floating-point",
|
31 |
+
"atan": "floating-point",
|
32 |
+
"atan2": "real floating-point",
|
33 |
+
"atanh": "floating-point",
|
34 |
+
"bitwise_and": "integer or boolean",
|
35 |
+
"bitwise_invert": "integer or boolean",
|
36 |
+
"bitwise_left_shift": "integer",
|
37 |
+
"bitwise_or": "integer or boolean",
|
38 |
+
"bitwise_right_shift": "integer",
|
39 |
+
"bitwise_xor": "integer or boolean",
|
40 |
+
"ceil": "real numeric",
|
41 |
+
"conj": "complex floating-point",
|
42 |
+
"cos": "floating-point",
|
43 |
+
"cosh": "floating-point",
|
44 |
+
"divide": "floating-point",
|
45 |
+
"equal": "all",
|
46 |
+
"exp": "floating-point",
|
47 |
+
"expm1": "floating-point",
|
48 |
+
"floor": "real numeric",
|
49 |
+
"floor_divide": "real numeric",
|
50 |
+
"greater": "real numeric",
|
51 |
+
"greater_equal": "real numeric",
|
52 |
+
"imag": "complex floating-point",
|
53 |
+
"isfinite": "numeric",
|
54 |
+
"isinf": "numeric",
|
55 |
+
"isnan": "numeric",
|
56 |
+
"less": "real numeric",
|
57 |
+
"less_equal": "real numeric",
|
58 |
+
"log": "floating-point",
|
59 |
+
"logaddexp": "real floating-point",
|
60 |
+
"log10": "floating-point",
|
61 |
+
"log1p": "floating-point",
|
62 |
+
"log2": "floating-point",
|
63 |
+
"logical_and": "boolean",
|
64 |
+
"logical_not": "boolean",
|
65 |
+
"logical_or": "boolean",
|
66 |
+
"logical_xor": "boolean",
|
67 |
+
"multiply": "numeric",
|
68 |
+
"negative": "numeric",
|
69 |
+
"not_equal": "all",
|
70 |
+
"positive": "numeric",
|
71 |
+
"pow": "numeric",
|
72 |
+
"real": "complex floating-point",
|
73 |
+
"remainder": "real numeric",
|
74 |
+
"round": "numeric",
|
75 |
+
"sign": "numeric",
|
76 |
+
"sin": "floating-point",
|
77 |
+
"sinh": "floating-point",
|
78 |
+
"sqrt": "floating-point",
|
79 |
+
"square": "numeric",
|
80 |
+
"subtract": "numeric",
|
81 |
+
"tan": "floating-point",
|
82 |
+
"tanh": "floating-point",
|
83 |
+
"trunc": "real numeric",
|
84 |
+
}
|
85 |
+
|
86 |
+
def _array_vals():
|
87 |
+
for d in _integer_dtypes:
|
88 |
+
yield asarray(1, dtype=d)
|
89 |
+
for d in _boolean_dtypes:
|
90 |
+
yield asarray(False, dtype=d)
|
91 |
+
for d in _floating_dtypes:
|
92 |
+
yield asarray(1.0, dtype=d)
|
93 |
+
|
94 |
+
for x in _array_vals():
|
95 |
+
for func_name, types in elementwise_function_input_types.items():
|
96 |
+
dtypes = _dtype_categories[types]
|
97 |
+
func = getattr(_elementwise_functions, func_name)
|
98 |
+
if nargs(func) == 2:
|
99 |
+
for y in _array_vals():
|
100 |
+
if x.dtype not in dtypes or y.dtype not in dtypes:
|
101 |
+
assert_raises(TypeError, lambda: func(x, y))
|
102 |
+
else:
|
103 |
+
if x.dtype not in dtypes:
|
104 |
+
assert_raises(TypeError, lambda: func(x))
|
105 |
+
|
106 |
+
|
107 |
+
def test_bitwise_shift_error():
|
108 |
+
# bitwise shift functions should raise when the second argument is negative
|
109 |
+
assert_raises(
|
110 |
+
ValueError, lambda: bitwise_left_shift(asarray([1, 1]), asarray([1, -1]))
|
111 |
+
)
|
112 |
+
assert_raises(
|
113 |
+
ValueError, lambda: bitwise_right_shift(asarray([1, 1]), asarray([1, -1]))
|
114 |
+
)
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_indexing_functions.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from numpy import array_api as xp
|
4 |
+
|
5 |
+
|
6 |
+
@pytest.mark.parametrize(
|
7 |
+
"x, indices, axis, expected",
|
8 |
+
[
|
9 |
+
([2, 3], [1, 1, 0], 0, [3, 3, 2]),
|
10 |
+
([2, 3], [1, 1, 0], -1, [3, 3, 2]),
|
11 |
+
([[2, 3]], [1], -1, [[3]]),
|
12 |
+
([[2, 3]], [0, 0], 0, [[2, 3], [2, 3]]),
|
13 |
+
],
|
14 |
+
)
|
15 |
+
def test_take_function(x, indices, axis, expected):
|
16 |
+
"""
|
17 |
+
Indices respect relative order of a descending stable-sort
|
18 |
+
|
19 |
+
See https://github.com/numpy/numpy/issues/20778
|
20 |
+
"""
|
21 |
+
x = xp.asarray(x)
|
22 |
+
indices = xp.asarray(indices)
|
23 |
+
out = xp.take(x, indices, axis=axis)
|
24 |
+
assert xp.all(out == xp.asarray(expected))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/tests/test_manipulation_functions.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.testing import assert_raises
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from .. import all
|
5 |
+
from .._creation_functions import asarray
|
6 |
+
from .._dtypes import float64, int8
|
7 |
+
from .._manipulation_functions import (
|
8 |
+
concat,
|
9 |
+
reshape,
|
10 |
+
stack
|
11 |
+
)
|
12 |
+
|
13 |
+
|
14 |
+
def test_concat_errors():
|
15 |
+
assert_raises(TypeError, lambda: concat((1, 1), axis=None))
|
16 |
+
assert_raises(TypeError, lambda: concat([asarray([1], dtype=int8),
|
17 |
+
asarray([1], dtype=float64)]))
|
18 |
+
|
19 |
+
|
20 |
+
def test_stack_errors():
|
21 |
+
assert_raises(TypeError, lambda: stack([asarray([1, 1], dtype=int8),
|
22 |
+
asarray([2, 2], dtype=float64)]))
|
23 |
+
|
24 |
+
|
25 |
+
def test_reshape_copy():
|
26 |
+
a = asarray(np.ones((2, 3)))
|
27 |
+
b = reshape(a, (3, 2), copy=True)
|
28 |
+
assert not np.shares_memory(a._array, b._array)
|
29 |
+
|
30 |
+
a = asarray(np.ones((2, 3)))
|
31 |
+
b = reshape(a, (3, 2), copy=False)
|
32 |
+
assert np.shares_memory(a._array, b._array)
|
33 |
+
|
34 |
+
a = asarray(np.ones((2, 3)).T)
|
35 |
+
b = reshape(a, (3, 2), copy=True)
|
36 |
+
assert_raises(AttributeError, lambda: reshape(a, (2, 3), copy=False))
|
37 |
+
|