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/array_api/__init__.py +387 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_constants.py +7 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_creation_functions.py +351 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_elementwise_functions.py +765 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_indexing_functions.py +20 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_set_functions.py +106 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/_statistical_functions.py +122 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/linalg.py +466 -0
- env-llmeval/lib/python3.10/site-packages/numpy/array_api/setup.py +12 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__main__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__version__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_isocbind.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_src_pyf.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/auxfuncs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/capi_maps.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cb_rules.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cfuncs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/common_rules.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/diagnose.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f2py2e.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f90mod_rules.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/func2subr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/rules.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/setup.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/symbolic.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/use_rules.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py +9 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_distutils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_meson.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py +46 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py +75 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py +205 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template +54 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.c +1423 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h +173 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_assumed_shape.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_block_docstring.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_callback.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_character.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_common.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_crackfortran.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_data.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_docs.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/numpy/array_api/__init__.py
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A NumPy sub-namespace that conforms to the Python array API standard.
|
3 |
+
|
4 |
+
This submodule accompanies NEP 47, which proposes its inclusion in NumPy. It
|
5 |
+
is still considered experimental, and will issue a warning when imported.
|
6 |
+
|
7 |
+
This is a proof-of-concept namespace that wraps the corresponding NumPy
|
8 |
+
functions to give a conforming implementation of the Python array API standard
|
9 |
+
(https://data-apis.github.io/array-api/latest/). The standard is currently in
|
10 |
+
an RFC phase and comments on it are both welcome and encouraged. Comments
|
11 |
+
should be made either at https://github.com/data-apis/array-api or at
|
12 |
+
https://github.com/data-apis/consortium-feedback/discussions.
|
13 |
+
|
14 |
+
NumPy already follows the proposed spec for the most part, so this module
|
15 |
+
serves mostly as a thin wrapper around it. However, NumPy also implements a
|
16 |
+
lot of behavior that is not included in the spec, so this serves as a
|
17 |
+
restricted subset of the API. Only those functions that are part of the spec
|
18 |
+
are included in this namespace, and all functions are given with the exact
|
19 |
+
signature given in the spec, including the use of position-only arguments, and
|
20 |
+
omitting any extra keyword arguments implemented by NumPy but not part of the
|
21 |
+
spec. The behavior of some functions is also modified from the NumPy behavior
|
22 |
+
to conform to the standard. Note that the underlying array object itself is
|
23 |
+
wrapped in a wrapper Array() class, but is otherwise unchanged. This submodule
|
24 |
+
is implemented in pure Python with no C extensions.
|
25 |
+
|
26 |
+
The array API spec is designed as a "minimal API subset" and explicitly allows
|
27 |
+
libraries to include behaviors not specified by it. But users of this module
|
28 |
+
that intend to write portable code should be aware that only those behaviors
|
29 |
+
that are listed in the spec are guaranteed to be implemented across libraries.
|
30 |
+
Consequently, the NumPy implementation was chosen to be both conforming and
|
31 |
+
minimal, so that users can use this implementation of the array API namespace
|
32 |
+
and be sure that behaviors that it defines will be available in conforming
|
33 |
+
namespaces from other libraries.
|
34 |
+
|
35 |
+
A few notes about the current state of this submodule:
|
36 |
+
|
37 |
+
- There is a test suite that tests modules against the array API standard at
|
38 |
+
https://github.com/data-apis/array-api-tests. The test suite is still a work
|
39 |
+
in progress, but the existing tests pass on this module, with a few
|
40 |
+
exceptions:
|
41 |
+
|
42 |
+
- DLPack support (see https://github.com/data-apis/array-api/pull/106) is
|
43 |
+
not included here, as it requires a full implementation in NumPy proper
|
44 |
+
first.
|
45 |
+
|
46 |
+
The test suite is not yet complete, and even the tests that exist are not
|
47 |
+
guaranteed to give a comprehensive coverage of the spec. Therefore, when
|
48 |
+
reviewing and using this submodule, you should refer to the standard
|
49 |
+
documents themselves. There are some tests in numpy.array_api.tests, but
|
50 |
+
they primarily focus on things that are not tested by the official array API
|
51 |
+
test suite.
|
52 |
+
|
53 |
+
- There is a custom array object, numpy.array_api.Array, which is returned by
|
54 |
+
all functions in this module. All functions in the array API namespace
|
55 |
+
implicitly assume that they will only receive this object as input. The only
|
56 |
+
way to create instances of this object is to use one of the array creation
|
57 |
+
functions. It does not have a public constructor on the object itself. The
|
58 |
+
object is a small wrapper class around numpy.ndarray. The main purpose of it
|
59 |
+
is to restrict the namespace of the array object to only those dtypes and
|
60 |
+
only those methods that are required by the spec, as well as to limit/change
|
61 |
+
certain behavior that differs in the spec. In particular:
|
62 |
+
|
63 |
+
- The array API namespace does not have scalar objects, only 0-D arrays.
|
64 |
+
Operations on Array that would create a scalar in NumPy create a 0-D
|
65 |
+
array.
|
66 |
+
|
67 |
+
- Indexing: Only a subset of indices supported by NumPy are required by the
|
68 |
+
spec. The Array object restricts indexing to only allow those types of
|
69 |
+
indices that are required by the spec. See the docstring of the
|
70 |
+
numpy.array_api.Array._validate_indices helper function for more
|
71 |
+
information.
|
72 |
+
|
73 |
+
- Type promotion: Some type promotion rules are different in the spec. In
|
74 |
+
particular, the spec does not have any value-based casting. The spec also
|
75 |
+
does not require cross-kind casting, like integer -> floating-point. Only
|
76 |
+
those promotions that are explicitly required by the array API
|
77 |
+
specification are allowed in this module. See NEP 47 for more info.
|
78 |
+
|
79 |
+
- Functions do not automatically call asarray() on their input, and will not
|
80 |
+
work if the input type is not Array. The exception is array creation
|
81 |
+
functions, and Python operators on the Array object, which accept Python
|
82 |
+
scalars of the same type as the array dtype.
|
83 |
+
|
84 |
+
- All functions include type annotations, corresponding to those given in the
|
85 |
+
spec (see _typing.py for definitions of some custom types). These do not
|
86 |
+
currently fully pass mypy due to some limitations in mypy.
|
87 |
+
|
88 |
+
- Dtype objects are just the NumPy dtype objects, e.g., float64 =
|
89 |
+
np.dtype('float64'). The spec does not require any behavior on these dtype
|
90 |
+
objects other than that they be accessible by name and be comparable by
|
91 |
+
equality, but it was considered too much extra complexity to create custom
|
92 |
+
objects to represent dtypes.
|
93 |
+
|
94 |
+
- All places where the implementations in this submodule are known to deviate
|
95 |
+
from their corresponding functions in NumPy are marked with "# Note:"
|
96 |
+
comments.
|
97 |
+
|
98 |
+
Still TODO in this module are:
|
99 |
+
|
100 |
+
- DLPack support for numpy.ndarray is still in progress. See
|
101 |
+
https://github.com/numpy/numpy/pull/19083.
|
102 |
+
|
103 |
+
- The copy=False keyword argument to asarray() is not yet implemented. This
|
104 |
+
requires support in numpy.asarray() first.
|
105 |
+
|
106 |
+
- Some functions are not yet fully tested in the array API test suite, and may
|
107 |
+
require updates that are not yet known until the tests are written.
|
108 |
+
|
109 |
+
- The spec is still in an RFC phase and may still have minor updates, which
|
110 |
+
will need to be reflected here.
|
111 |
+
|
112 |
+
- Complex number support in array API spec is planned but not yet finalized,
|
113 |
+
as are the fft extension and certain linear algebra functions such as eig
|
114 |
+
that require complex dtypes.
|
115 |
+
|
116 |
+
"""
|
117 |
+
|
118 |
+
import warnings
|
119 |
+
|
120 |
+
warnings.warn(
|
121 |
+
"The numpy.array_api submodule is still experimental. See NEP 47.", stacklevel=2
|
122 |
+
)
|
123 |
+
|
124 |
+
__array_api_version__ = "2022.12"
|
125 |
+
|
126 |
+
__all__ = ["__array_api_version__"]
|
127 |
+
|
128 |
+
from ._constants import e, inf, nan, pi, newaxis
|
129 |
+
|
130 |
+
__all__ += ["e", "inf", "nan", "pi", "newaxis"]
|
131 |
+
|
132 |
+
from ._creation_functions import (
|
133 |
+
asarray,
|
134 |
+
arange,
|
135 |
+
empty,
|
136 |
+
empty_like,
|
137 |
+
eye,
|
138 |
+
from_dlpack,
|
139 |
+
full,
|
140 |
+
full_like,
|
141 |
+
linspace,
|
142 |
+
meshgrid,
|
143 |
+
ones,
|
144 |
+
ones_like,
|
145 |
+
tril,
|
146 |
+
triu,
|
147 |
+
zeros,
|
148 |
+
zeros_like,
|
149 |
+
)
|
150 |
+
|
151 |
+
__all__ += [
|
152 |
+
"asarray",
|
153 |
+
"arange",
|
154 |
+
"empty",
|
155 |
+
"empty_like",
|
156 |
+
"eye",
|
157 |
+
"from_dlpack",
|
158 |
+
"full",
|
159 |
+
"full_like",
|
160 |
+
"linspace",
|
161 |
+
"meshgrid",
|
162 |
+
"ones",
|
163 |
+
"ones_like",
|
164 |
+
"tril",
|
165 |
+
"triu",
|
166 |
+
"zeros",
|
167 |
+
"zeros_like",
|
168 |
+
]
|
169 |
+
|
170 |
+
from ._data_type_functions import (
|
171 |
+
astype,
|
172 |
+
broadcast_arrays,
|
173 |
+
broadcast_to,
|
174 |
+
can_cast,
|
175 |
+
finfo,
|
176 |
+
isdtype,
|
177 |
+
iinfo,
|
178 |
+
result_type,
|
179 |
+
)
|
180 |
+
|
181 |
+
__all__ += [
|
182 |
+
"astype",
|
183 |
+
"broadcast_arrays",
|
184 |
+
"broadcast_to",
|
185 |
+
"can_cast",
|
186 |
+
"finfo",
|
187 |
+
"iinfo",
|
188 |
+
"result_type",
|
189 |
+
]
|
190 |
+
|
191 |
+
from ._dtypes import (
|
192 |
+
int8,
|
193 |
+
int16,
|
194 |
+
int32,
|
195 |
+
int64,
|
196 |
+
uint8,
|
197 |
+
uint16,
|
198 |
+
uint32,
|
199 |
+
uint64,
|
200 |
+
float32,
|
201 |
+
float64,
|
202 |
+
complex64,
|
203 |
+
complex128,
|
204 |
+
bool,
|
205 |
+
)
|
206 |
+
|
207 |
+
__all__ += [
|
208 |
+
"int8",
|
209 |
+
"int16",
|
210 |
+
"int32",
|
211 |
+
"int64",
|
212 |
+
"uint8",
|
213 |
+
"uint16",
|
214 |
+
"uint32",
|
215 |
+
"uint64",
|
216 |
+
"float32",
|
217 |
+
"float64",
|
218 |
+
"bool",
|
219 |
+
]
|
220 |
+
|
221 |
+
from ._elementwise_functions import (
|
222 |
+
abs,
|
223 |
+
acos,
|
224 |
+
acosh,
|
225 |
+
add,
|
226 |
+
asin,
|
227 |
+
asinh,
|
228 |
+
atan,
|
229 |
+
atan2,
|
230 |
+
atanh,
|
231 |
+
bitwise_and,
|
232 |
+
bitwise_left_shift,
|
233 |
+
bitwise_invert,
|
234 |
+
bitwise_or,
|
235 |
+
bitwise_right_shift,
|
236 |
+
bitwise_xor,
|
237 |
+
ceil,
|
238 |
+
conj,
|
239 |
+
cos,
|
240 |
+
cosh,
|
241 |
+
divide,
|
242 |
+
equal,
|
243 |
+
exp,
|
244 |
+
expm1,
|
245 |
+
floor,
|
246 |
+
floor_divide,
|
247 |
+
greater,
|
248 |
+
greater_equal,
|
249 |
+
imag,
|
250 |
+
isfinite,
|
251 |
+
isinf,
|
252 |
+
isnan,
|
253 |
+
less,
|
254 |
+
less_equal,
|
255 |
+
log,
|
256 |
+
log1p,
|
257 |
+
log2,
|
258 |
+
log10,
|
259 |
+
logaddexp,
|
260 |
+
logical_and,
|
261 |
+
logical_not,
|
262 |
+
logical_or,
|
263 |
+
logical_xor,
|
264 |
+
multiply,
|
265 |
+
negative,
|
266 |
+
not_equal,
|
267 |
+
positive,
|
268 |
+
pow,
|
269 |
+
real,
|
270 |
+
remainder,
|
271 |
+
round,
|
272 |
+
sign,
|
273 |
+
sin,
|
274 |
+
sinh,
|
275 |
+
square,
|
276 |
+
sqrt,
|
277 |
+
subtract,
|
278 |
+
tan,
|
279 |
+
tanh,
|
280 |
+
trunc,
|
281 |
+
)
|
282 |
+
|
283 |
+
__all__ += [
|
284 |
+
"abs",
|
285 |
+
"acos",
|
286 |
+
"acosh",
|
287 |
+
"add",
|
288 |
+
"asin",
|
289 |
+
"asinh",
|
290 |
+
"atan",
|
291 |
+
"atan2",
|
292 |
+
"atanh",
|
293 |
+
"bitwise_and",
|
294 |
+
"bitwise_left_shift",
|
295 |
+
"bitwise_invert",
|
296 |
+
"bitwise_or",
|
297 |
+
"bitwise_right_shift",
|
298 |
+
"bitwise_xor",
|
299 |
+
"ceil",
|
300 |
+
"cos",
|
301 |
+
"cosh",
|
302 |
+
"divide",
|
303 |
+
"equal",
|
304 |
+
"exp",
|
305 |
+
"expm1",
|
306 |
+
"floor",
|
307 |
+
"floor_divide",
|
308 |
+
"greater",
|
309 |
+
"greater_equal",
|
310 |
+
"isfinite",
|
311 |
+
"isinf",
|
312 |
+
"isnan",
|
313 |
+
"less",
|
314 |
+
"less_equal",
|
315 |
+
"log",
|
316 |
+
"log1p",
|
317 |
+
"log2",
|
318 |
+
"log10",
|
319 |
+
"logaddexp",
|
320 |
+
"logical_and",
|
321 |
+
"logical_not",
|
322 |
+
"logical_or",
|
323 |
+
"logical_xor",
|
324 |
+
"multiply",
|
325 |
+
"negative",
|
326 |
+
"not_equal",
|
327 |
+
"positive",
|
328 |
+
"pow",
|
329 |
+
"remainder",
|
330 |
+
"round",
|
331 |
+
"sign",
|
332 |
+
"sin",
|
333 |
+
"sinh",
|
334 |
+
"square",
|
335 |
+
"sqrt",
|
336 |
+
"subtract",
|
337 |
+
"tan",
|
338 |
+
"tanh",
|
339 |
+
"trunc",
|
340 |
+
]
|
341 |
+
|
342 |
+
from ._indexing_functions import take
|
343 |
+
|
344 |
+
__all__ += ["take"]
|
345 |
+
|
346 |
+
# linalg is an extension in the array API spec, which is a sub-namespace. Only
|
347 |
+
# a subset of functions in it are imported into the top-level namespace.
|
348 |
+
from . import linalg
|
349 |
+
|
350 |
+
__all__ += ["linalg"]
|
351 |
+
|
352 |
+
from .linalg import matmul, tensordot, matrix_transpose, vecdot
|
353 |
+
|
354 |
+
__all__ += ["matmul", "tensordot", "matrix_transpose", "vecdot"]
|
355 |
+
|
356 |
+
from ._manipulation_functions import (
|
357 |
+
concat,
|
358 |
+
expand_dims,
|
359 |
+
flip,
|
360 |
+
permute_dims,
|
361 |
+
reshape,
|
362 |
+
roll,
|
363 |
+
squeeze,
|
364 |
+
stack,
|
365 |
+
)
|
366 |
+
|
367 |
+
__all__ += ["concat", "expand_dims", "flip", "permute_dims", "reshape", "roll", "squeeze", "stack"]
|
368 |
+
|
369 |
+
from ._searching_functions import argmax, argmin, nonzero, where
|
370 |
+
|
371 |
+
__all__ += ["argmax", "argmin", "nonzero", "where"]
|
372 |
+
|
373 |
+
from ._set_functions import unique_all, unique_counts, unique_inverse, unique_values
|
374 |
+
|
375 |
+
__all__ += ["unique_all", "unique_counts", "unique_inverse", "unique_values"]
|
376 |
+
|
377 |
+
from ._sorting_functions import argsort, sort
|
378 |
+
|
379 |
+
__all__ += ["argsort", "sort"]
|
380 |
+
|
381 |
+
from ._statistical_functions import max, mean, min, prod, std, sum, var
|
382 |
+
|
383 |
+
__all__ += ["max", "mean", "min", "prod", "std", "sum", "var"]
|
384 |
+
|
385 |
+
from ._utility_functions import all, any
|
386 |
+
|
387 |
+
__all__ += ["all", "any"]
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_constants.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
e = np.e
|
4 |
+
inf = np.inf
|
5 |
+
nan = np.nan
|
6 |
+
pi = np.pi
|
7 |
+
newaxis = np.newaxis
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_creation_functions.py
ADDED
@@ -0,0 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
|
4 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
|
5 |
+
|
6 |
+
if TYPE_CHECKING:
|
7 |
+
from ._typing import (
|
8 |
+
Array,
|
9 |
+
Device,
|
10 |
+
Dtype,
|
11 |
+
NestedSequence,
|
12 |
+
SupportsBufferProtocol,
|
13 |
+
)
|
14 |
+
from collections.abc import Sequence
|
15 |
+
from ._dtypes import _all_dtypes
|
16 |
+
|
17 |
+
import numpy as np
|
18 |
+
|
19 |
+
|
20 |
+
def _check_valid_dtype(dtype):
|
21 |
+
# Note: Only spelling dtypes as the dtype objects is supported.
|
22 |
+
|
23 |
+
# We use this instead of "dtype in _all_dtypes" because the dtype objects
|
24 |
+
# define equality with the sorts of things we want to disallow.
|
25 |
+
for d in (None,) + _all_dtypes:
|
26 |
+
if dtype is d:
|
27 |
+
return
|
28 |
+
raise ValueError("dtype must be one of the supported dtypes")
|
29 |
+
|
30 |
+
|
31 |
+
def asarray(
|
32 |
+
obj: Union[
|
33 |
+
Array,
|
34 |
+
bool,
|
35 |
+
int,
|
36 |
+
float,
|
37 |
+
NestedSequence[bool | int | float],
|
38 |
+
SupportsBufferProtocol,
|
39 |
+
],
|
40 |
+
/,
|
41 |
+
*,
|
42 |
+
dtype: Optional[Dtype] = None,
|
43 |
+
device: Optional[Device] = None,
|
44 |
+
copy: Optional[Union[bool, np._CopyMode]] = None,
|
45 |
+
) -> Array:
|
46 |
+
"""
|
47 |
+
Array API compatible wrapper for :py:func:`np.asarray <numpy.asarray>`.
|
48 |
+
|
49 |
+
See its docstring for more information.
|
50 |
+
"""
|
51 |
+
# _array_object imports in this file are inside the functions to avoid
|
52 |
+
# circular imports
|
53 |
+
from ._array_object import Array
|
54 |
+
|
55 |
+
_check_valid_dtype(dtype)
|
56 |
+
if device not in ["cpu", None]:
|
57 |
+
raise ValueError(f"Unsupported device {device!r}")
|
58 |
+
if copy in (False, np._CopyMode.IF_NEEDED):
|
59 |
+
# Note: copy=False is not yet implemented in np.asarray
|
60 |
+
raise NotImplementedError("copy=False is not yet implemented")
|
61 |
+
if isinstance(obj, Array):
|
62 |
+
if dtype is not None and obj.dtype != dtype:
|
63 |
+
copy = True
|
64 |
+
if copy in (True, np._CopyMode.ALWAYS):
|
65 |
+
return Array._new(np.array(obj._array, copy=True, dtype=dtype))
|
66 |
+
return obj
|
67 |
+
if dtype is None and isinstance(obj, int) and (obj > 2 ** 64 or obj < -(2 ** 63)):
|
68 |
+
# Give a better error message in this case. NumPy would convert this
|
69 |
+
# to an object array. TODO: This won't handle large integers in lists.
|
70 |
+
raise OverflowError("Integer out of bounds for array dtypes")
|
71 |
+
res = np.asarray(obj, dtype=dtype)
|
72 |
+
return Array._new(res)
|
73 |
+
|
74 |
+
|
75 |
+
def arange(
|
76 |
+
start: Union[int, float],
|
77 |
+
/,
|
78 |
+
stop: Optional[Union[int, float]] = None,
|
79 |
+
step: Union[int, float] = 1,
|
80 |
+
*,
|
81 |
+
dtype: Optional[Dtype] = None,
|
82 |
+
device: Optional[Device] = None,
|
83 |
+
) -> Array:
|
84 |
+
"""
|
85 |
+
Array API compatible wrapper for :py:func:`np.arange <numpy.arange>`.
|
86 |
+
|
87 |
+
See its docstring for more information.
|
88 |
+
"""
|
89 |
+
from ._array_object import Array
|
90 |
+
|
91 |
+
_check_valid_dtype(dtype)
|
92 |
+
if device not in ["cpu", None]:
|
93 |
+
raise ValueError(f"Unsupported device {device!r}")
|
94 |
+
return Array._new(np.arange(start, stop=stop, step=step, dtype=dtype))
|
95 |
+
|
96 |
+
|
97 |
+
def empty(
|
98 |
+
shape: Union[int, Tuple[int, ...]],
|
99 |
+
*,
|
100 |
+
dtype: Optional[Dtype] = None,
|
101 |
+
device: Optional[Device] = None,
|
102 |
+
) -> Array:
|
103 |
+
"""
|
104 |
+
Array API compatible wrapper for :py:func:`np.empty <numpy.empty>`.
|
105 |
+
|
106 |
+
See its docstring for more information.
|
107 |
+
"""
|
108 |
+
from ._array_object import Array
|
109 |
+
|
110 |
+
_check_valid_dtype(dtype)
|
111 |
+
if device not in ["cpu", None]:
|
112 |
+
raise ValueError(f"Unsupported device {device!r}")
|
113 |
+
return Array._new(np.empty(shape, dtype=dtype))
|
114 |
+
|
115 |
+
|
116 |
+
def empty_like(
|
117 |
+
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
|
118 |
+
) -> Array:
|
119 |
+
"""
|
120 |
+
Array API compatible wrapper for :py:func:`np.empty_like <numpy.empty_like>`.
|
121 |
+
|
122 |
+
See its docstring for more information.
|
123 |
+
"""
|
124 |
+
from ._array_object import Array
|
125 |
+
|
126 |
+
_check_valid_dtype(dtype)
|
127 |
+
if device not in ["cpu", None]:
|
128 |
+
raise ValueError(f"Unsupported device {device!r}")
|
129 |
+
return Array._new(np.empty_like(x._array, dtype=dtype))
|
130 |
+
|
131 |
+
|
132 |
+
def eye(
|
133 |
+
n_rows: int,
|
134 |
+
n_cols: Optional[int] = None,
|
135 |
+
/,
|
136 |
+
*,
|
137 |
+
k: int = 0,
|
138 |
+
dtype: Optional[Dtype] = None,
|
139 |
+
device: Optional[Device] = None,
|
140 |
+
) -> Array:
|
141 |
+
"""
|
142 |
+
Array API compatible wrapper for :py:func:`np.eye <numpy.eye>`.
|
143 |
+
|
144 |
+
See its docstring for more information.
|
145 |
+
"""
|
146 |
+
from ._array_object import Array
|
147 |
+
|
148 |
+
_check_valid_dtype(dtype)
|
149 |
+
if device not in ["cpu", None]:
|
150 |
+
raise ValueError(f"Unsupported device {device!r}")
|
151 |
+
return Array._new(np.eye(n_rows, M=n_cols, k=k, dtype=dtype))
|
152 |
+
|
153 |
+
|
154 |
+
def from_dlpack(x: object, /) -> Array:
|
155 |
+
from ._array_object import Array
|
156 |
+
|
157 |
+
return Array._new(np.from_dlpack(x))
|
158 |
+
|
159 |
+
|
160 |
+
def full(
|
161 |
+
shape: Union[int, Tuple[int, ...]],
|
162 |
+
fill_value: Union[int, float],
|
163 |
+
*,
|
164 |
+
dtype: Optional[Dtype] = None,
|
165 |
+
device: Optional[Device] = None,
|
166 |
+
) -> Array:
|
167 |
+
"""
|
168 |
+
Array API compatible wrapper for :py:func:`np.full <numpy.full>`.
|
169 |
+
|
170 |
+
See its docstring for more information.
|
171 |
+
"""
|
172 |
+
from ._array_object import Array
|
173 |
+
|
174 |
+
_check_valid_dtype(dtype)
|
175 |
+
if device not in ["cpu", None]:
|
176 |
+
raise ValueError(f"Unsupported device {device!r}")
|
177 |
+
if isinstance(fill_value, Array) and fill_value.ndim == 0:
|
178 |
+
fill_value = fill_value._array
|
179 |
+
res = np.full(shape, fill_value, dtype=dtype)
|
180 |
+
if res.dtype not in _all_dtypes:
|
181 |
+
# This will happen if the fill value is not something that NumPy
|
182 |
+
# coerces to one of the acceptable dtypes.
|
183 |
+
raise TypeError("Invalid input to full")
|
184 |
+
return Array._new(res)
|
185 |
+
|
186 |
+
|
187 |
+
def full_like(
|
188 |
+
x: Array,
|
189 |
+
/,
|
190 |
+
fill_value: Union[int, float],
|
191 |
+
*,
|
192 |
+
dtype: Optional[Dtype] = None,
|
193 |
+
device: Optional[Device] = None,
|
194 |
+
) -> Array:
|
195 |
+
"""
|
196 |
+
Array API compatible wrapper for :py:func:`np.full_like <numpy.full_like>`.
|
197 |
+
|
198 |
+
See its docstring for more information.
|
199 |
+
"""
|
200 |
+
from ._array_object import Array
|
201 |
+
|
202 |
+
_check_valid_dtype(dtype)
|
203 |
+
if device not in ["cpu", None]:
|
204 |
+
raise ValueError(f"Unsupported device {device!r}")
|
205 |
+
res = np.full_like(x._array, fill_value, dtype=dtype)
|
206 |
+
if res.dtype not in _all_dtypes:
|
207 |
+
# This will happen if the fill value is not something that NumPy
|
208 |
+
# coerces to one of the acceptable dtypes.
|
209 |
+
raise TypeError("Invalid input to full_like")
|
210 |
+
return Array._new(res)
|
211 |
+
|
212 |
+
|
213 |
+
def linspace(
|
214 |
+
start: Union[int, float],
|
215 |
+
stop: Union[int, float],
|
216 |
+
/,
|
217 |
+
num: int,
|
218 |
+
*,
|
219 |
+
dtype: Optional[Dtype] = None,
|
220 |
+
device: Optional[Device] = None,
|
221 |
+
endpoint: bool = True,
|
222 |
+
) -> Array:
|
223 |
+
"""
|
224 |
+
Array API compatible wrapper for :py:func:`np.linspace <numpy.linspace>`.
|
225 |
+
|
226 |
+
See its docstring for more information.
|
227 |
+
"""
|
228 |
+
from ._array_object import Array
|
229 |
+
|
230 |
+
_check_valid_dtype(dtype)
|
231 |
+
if device not in ["cpu", None]:
|
232 |
+
raise ValueError(f"Unsupported device {device!r}")
|
233 |
+
return Array._new(np.linspace(start, stop, num, dtype=dtype, endpoint=endpoint))
|
234 |
+
|
235 |
+
|
236 |
+
def meshgrid(*arrays: Array, indexing: str = "xy") -> List[Array]:
|
237 |
+
"""
|
238 |
+
Array API compatible wrapper for :py:func:`np.meshgrid <numpy.meshgrid>`.
|
239 |
+
|
240 |
+
See its docstring for more information.
|
241 |
+
"""
|
242 |
+
from ._array_object import Array
|
243 |
+
|
244 |
+
# Note: unlike np.meshgrid, only inputs with all the same dtype are
|
245 |
+
# allowed
|
246 |
+
|
247 |
+
if len({a.dtype for a in arrays}) > 1:
|
248 |
+
raise ValueError("meshgrid inputs must all have the same dtype")
|
249 |
+
|
250 |
+
return [
|
251 |
+
Array._new(array)
|
252 |
+
for array in np.meshgrid(*[a._array for a in arrays], indexing=indexing)
|
253 |
+
]
|
254 |
+
|
255 |
+
|
256 |
+
def ones(
|
257 |
+
shape: Union[int, Tuple[int, ...]],
|
258 |
+
*,
|
259 |
+
dtype: Optional[Dtype] = None,
|
260 |
+
device: Optional[Device] = None,
|
261 |
+
) -> Array:
|
262 |
+
"""
|
263 |
+
Array API compatible wrapper for :py:func:`np.ones <numpy.ones>`.
|
264 |
+
|
265 |
+
See its docstring for more information.
|
266 |
+
"""
|
267 |
+
from ._array_object import Array
|
268 |
+
|
269 |
+
_check_valid_dtype(dtype)
|
270 |
+
if device not in ["cpu", None]:
|
271 |
+
raise ValueError(f"Unsupported device {device!r}")
|
272 |
+
return Array._new(np.ones(shape, dtype=dtype))
|
273 |
+
|
274 |
+
|
275 |
+
def ones_like(
|
276 |
+
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
|
277 |
+
) -> Array:
|
278 |
+
"""
|
279 |
+
Array API compatible wrapper for :py:func:`np.ones_like <numpy.ones_like>`.
|
280 |
+
|
281 |
+
See its docstring for more information.
|
282 |
+
"""
|
283 |
+
from ._array_object import Array
|
284 |
+
|
285 |
+
_check_valid_dtype(dtype)
|
286 |
+
if device not in ["cpu", None]:
|
287 |
+
raise ValueError(f"Unsupported device {device!r}")
|
288 |
+
return Array._new(np.ones_like(x._array, dtype=dtype))
|
289 |
+
|
290 |
+
|
291 |
+
def tril(x: Array, /, *, k: int = 0) -> Array:
|
292 |
+
"""
|
293 |
+
Array API compatible wrapper for :py:func:`np.tril <numpy.tril>`.
|
294 |
+
|
295 |
+
See its docstring for more information.
|
296 |
+
"""
|
297 |
+
from ._array_object import Array
|
298 |
+
|
299 |
+
if x.ndim < 2:
|
300 |
+
# Note: Unlike np.tril, x must be at least 2-D
|
301 |
+
raise ValueError("x must be at least 2-dimensional for tril")
|
302 |
+
return Array._new(np.tril(x._array, k=k))
|
303 |
+
|
304 |
+
|
305 |
+
def triu(x: Array, /, *, k: int = 0) -> Array:
|
306 |
+
"""
|
307 |
+
Array API compatible wrapper for :py:func:`np.triu <numpy.triu>`.
|
308 |
+
|
309 |
+
See its docstring for more information.
|
310 |
+
"""
|
311 |
+
from ._array_object import Array
|
312 |
+
|
313 |
+
if x.ndim < 2:
|
314 |
+
# Note: Unlike np.triu, x must be at least 2-D
|
315 |
+
raise ValueError("x must be at least 2-dimensional for triu")
|
316 |
+
return Array._new(np.triu(x._array, k=k))
|
317 |
+
|
318 |
+
|
319 |
+
def zeros(
|
320 |
+
shape: Union[int, Tuple[int, ...]],
|
321 |
+
*,
|
322 |
+
dtype: Optional[Dtype] = None,
|
323 |
+
device: Optional[Device] = None,
|
324 |
+
) -> Array:
|
325 |
+
"""
|
326 |
+
Array API compatible wrapper for :py:func:`np.zeros <numpy.zeros>`.
|
327 |
+
|
328 |
+
See its docstring for more information.
|
329 |
+
"""
|
330 |
+
from ._array_object import Array
|
331 |
+
|
332 |
+
_check_valid_dtype(dtype)
|
333 |
+
if device not in ["cpu", None]:
|
334 |
+
raise ValueError(f"Unsupported device {device!r}")
|
335 |
+
return Array._new(np.zeros(shape, dtype=dtype))
|
336 |
+
|
337 |
+
|
338 |
+
def zeros_like(
|
339 |
+
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
|
340 |
+
) -> Array:
|
341 |
+
"""
|
342 |
+
Array API compatible wrapper for :py:func:`np.zeros_like <numpy.zeros_like>`.
|
343 |
+
|
344 |
+
See its docstring for more information.
|
345 |
+
"""
|
346 |
+
from ._array_object import Array
|
347 |
+
|
348 |
+
_check_valid_dtype(dtype)
|
349 |
+
if device not in ["cpu", None]:
|
350 |
+
raise ValueError(f"Unsupported device {device!r}")
|
351 |
+
return Array._new(np.zeros_like(x._array, dtype=dtype))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_elementwise_functions.py
ADDED
@@ -0,0 +1,765 @@
|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__future__ import annotations
|
2 |
+
|
3 |
+
from ._dtypes import (
|
4 |
+
_boolean_dtypes,
|
5 |
+
_floating_dtypes,
|
6 |
+
_real_floating_dtypes,
|
7 |
+
_complex_floating_dtypes,
|
8 |
+
_integer_dtypes,
|
9 |
+
_integer_or_boolean_dtypes,
|
10 |
+
_real_numeric_dtypes,
|
11 |
+
_numeric_dtypes,
|
12 |
+
_result_type,
|
13 |
+
)
|
14 |
+
from ._array_object import Array
|
15 |
+
|
16 |
+
import numpy as np
|
17 |
+
|
18 |
+
|
19 |
+
def abs(x: Array, /) -> Array:
|
20 |
+
"""
|
21 |
+
Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`.
|
22 |
+
|
23 |
+
See its docstring for more information.
|
24 |
+
"""
|
25 |
+
if x.dtype not in _numeric_dtypes:
|
26 |
+
raise TypeError("Only numeric dtypes are allowed in abs")
|
27 |
+
return Array._new(np.abs(x._array))
|
28 |
+
|
29 |
+
|
30 |
+
# Note: the function name is different here
|
31 |
+
def acos(x: Array, /) -> Array:
|
32 |
+
"""
|
33 |
+
Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`.
|
34 |
+
|
35 |
+
See its docstring for more information.
|
36 |
+
"""
|
37 |
+
if x.dtype not in _floating_dtypes:
|
38 |
+
raise TypeError("Only floating-point dtypes are allowed in acos")
|
39 |
+
return Array._new(np.arccos(x._array))
|
40 |
+
|
41 |
+
|
42 |
+
# Note: the function name is different here
|
43 |
+
def acosh(x: Array, /) -> Array:
|
44 |
+
"""
|
45 |
+
Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`.
|
46 |
+
|
47 |
+
See its docstring for more information.
|
48 |
+
"""
|
49 |
+
if x.dtype not in _floating_dtypes:
|
50 |
+
raise TypeError("Only floating-point dtypes are allowed in acosh")
|
51 |
+
return Array._new(np.arccosh(x._array))
|
52 |
+
|
53 |
+
|
54 |
+
def add(x1: Array, x2: Array, /) -> Array:
|
55 |
+
"""
|
56 |
+
Array API compatible wrapper for :py:func:`np.add <numpy.add>`.
|
57 |
+
|
58 |
+
See its docstring for more information.
|
59 |
+
"""
|
60 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
61 |
+
raise TypeError("Only numeric dtypes are allowed in add")
|
62 |
+
# Call result type here just to raise on disallowed type combinations
|
63 |
+
_result_type(x1.dtype, x2.dtype)
|
64 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
65 |
+
return Array._new(np.add(x1._array, x2._array))
|
66 |
+
|
67 |
+
|
68 |
+
# Note: the function name is different here
|
69 |
+
def asin(x: Array, /) -> Array:
|
70 |
+
"""
|
71 |
+
Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`.
|
72 |
+
|
73 |
+
See its docstring for more information.
|
74 |
+
"""
|
75 |
+
if x.dtype not in _floating_dtypes:
|
76 |
+
raise TypeError("Only floating-point dtypes are allowed in asin")
|
77 |
+
return Array._new(np.arcsin(x._array))
|
78 |
+
|
79 |
+
|
80 |
+
# Note: the function name is different here
|
81 |
+
def asinh(x: Array, /) -> Array:
|
82 |
+
"""
|
83 |
+
Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`.
|
84 |
+
|
85 |
+
See its docstring for more information.
|
86 |
+
"""
|
87 |
+
if x.dtype not in _floating_dtypes:
|
88 |
+
raise TypeError("Only floating-point dtypes are allowed in asinh")
|
89 |
+
return Array._new(np.arcsinh(x._array))
|
90 |
+
|
91 |
+
|
92 |
+
# Note: the function name is different here
|
93 |
+
def atan(x: Array, /) -> Array:
|
94 |
+
"""
|
95 |
+
Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`.
|
96 |
+
|
97 |
+
See its docstring for more information.
|
98 |
+
"""
|
99 |
+
if x.dtype not in _floating_dtypes:
|
100 |
+
raise TypeError("Only floating-point dtypes are allowed in atan")
|
101 |
+
return Array._new(np.arctan(x._array))
|
102 |
+
|
103 |
+
|
104 |
+
# Note: the function name is different here
|
105 |
+
def atan2(x1: Array, x2: Array, /) -> Array:
|
106 |
+
"""
|
107 |
+
Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`.
|
108 |
+
|
109 |
+
See its docstring for more information.
|
110 |
+
"""
|
111 |
+
if x1.dtype not in _real_floating_dtypes or x2.dtype not in _real_floating_dtypes:
|
112 |
+
raise TypeError("Only real floating-point dtypes are allowed in atan2")
|
113 |
+
# Call result type here just to raise on disallowed type combinations
|
114 |
+
_result_type(x1.dtype, x2.dtype)
|
115 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
116 |
+
return Array._new(np.arctan2(x1._array, x2._array))
|
117 |
+
|
118 |
+
|
119 |
+
# Note: the function name is different here
|
120 |
+
def atanh(x: Array, /) -> Array:
|
121 |
+
"""
|
122 |
+
Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`.
|
123 |
+
|
124 |
+
See its docstring for more information.
|
125 |
+
"""
|
126 |
+
if x.dtype not in _floating_dtypes:
|
127 |
+
raise TypeError("Only floating-point dtypes are allowed in atanh")
|
128 |
+
return Array._new(np.arctanh(x._array))
|
129 |
+
|
130 |
+
|
131 |
+
def bitwise_and(x1: Array, x2: Array, /) -> Array:
|
132 |
+
"""
|
133 |
+
Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`.
|
134 |
+
|
135 |
+
See its docstring for more information.
|
136 |
+
"""
|
137 |
+
if (
|
138 |
+
x1.dtype not in _integer_or_boolean_dtypes
|
139 |
+
or x2.dtype not in _integer_or_boolean_dtypes
|
140 |
+
):
|
141 |
+
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_and")
|
142 |
+
# Call result type here just to raise on disallowed type combinations
|
143 |
+
_result_type(x1.dtype, x2.dtype)
|
144 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
145 |
+
return Array._new(np.bitwise_and(x1._array, x2._array))
|
146 |
+
|
147 |
+
|
148 |
+
# Note: the function name is different here
|
149 |
+
def bitwise_left_shift(x1: Array, x2: Array, /) -> Array:
|
150 |
+
"""
|
151 |
+
Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`.
|
152 |
+
|
153 |
+
See its docstring for more information.
|
154 |
+
"""
|
155 |
+
if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes:
|
156 |
+
raise TypeError("Only integer dtypes are allowed in bitwise_left_shift")
|
157 |
+
# Call result type here just to raise on disallowed type combinations
|
158 |
+
_result_type(x1.dtype, x2.dtype)
|
159 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
160 |
+
# Note: bitwise_left_shift is only defined for x2 nonnegative.
|
161 |
+
if np.any(x2._array < 0):
|
162 |
+
raise ValueError("bitwise_left_shift(x1, x2) is only defined for x2 >= 0")
|
163 |
+
return Array._new(np.left_shift(x1._array, x2._array))
|
164 |
+
|
165 |
+
|
166 |
+
# Note: the function name is different here
|
167 |
+
def bitwise_invert(x: Array, /) -> Array:
|
168 |
+
"""
|
169 |
+
Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`.
|
170 |
+
|
171 |
+
See its docstring for more information.
|
172 |
+
"""
|
173 |
+
if x.dtype not in _integer_or_boolean_dtypes:
|
174 |
+
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_invert")
|
175 |
+
return Array._new(np.invert(x._array))
|
176 |
+
|
177 |
+
|
178 |
+
def bitwise_or(x1: Array, x2: Array, /) -> Array:
|
179 |
+
"""
|
180 |
+
Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`.
|
181 |
+
|
182 |
+
See its docstring for more information.
|
183 |
+
"""
|
184 |
+
if (
|
185 |
+
x1.dtype not in _integer_or_boolean_dtypes
|
186 |
+
or x2.dtype not in _integer_or_boolean_dtypes
|
187 |
+
):
|
188 |
+
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_or")
|
189 |
+
# Call result type here just to raise on disallowed type combinations
|
190 |
+
_result_type(x1.dtype, x2.dtype)
|
191 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
192 |
+
return Array._new(np.bitwise_or(x1._array, x2._array))
|
193 |
+
|
194 |
+
|
195 |
+
# Note: the function name is different here
|
196 |
+
def bitwise_right_shift(x1: Array, x2: Array, /) -> Array:
|
197 |
+
"""
|
198 |
+
Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`.
|
199 |
+
|
200 |
+
See its docstring for more information.
|
201 |
+
"""
|
202 |
+
if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes:
|
203 |
+
raise TypeError("Only integer dtypes are allowed in bitwise_right_shift")
|
204 |
+
# Call result type here just to raise on disallowed type combinations
|
205 |
+
_result_type(x1.dtype, x2.dtype)
|
206 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
207 |
+
# Note: bitwise_right_shift is only defined for x2 nonnegative.
|
208 |
+
if np.any(x2._array < 0):
|
209 |
+
raise ValueError("bitwise_right_shift(x1, x2) is only defined for x2 >= 0")
|
210 |
+
return Array._new(np.right_shift(x1._array, x2._array))
|
211 |
+
|
212 |
+
|
213 |
+
def bitwise_xor(x1: Array, x2: Array, /) -> Array:
|
214 |
+
"""
|
215 |
+
Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`.
|
216 |
+
|
217 |
+
See its docstring for more information.
|
218 |
+
"""
|
219 |
+
if (
|
220 |
+
x1.dtype not in _integer_or_boolean_dtypes
|
221 |
+
or x2.dtype not in _integer_or_boolean_dtypes
|
222 |
+
):
|
223 |
+
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_xor")
|
224 |
+
# Call result type here just to raise on disallowed type combinations
|
225 |
+
_result_type(x1.dtype, x2.dtype)
|
226 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
227 |
+
return Array._new(np.bitwise_xor(x1._array, x2._array))
|
228 |
+
|
229 |
+
|
230 |
+
def ceil(x: Array, /) -> Array:
|
231 |
+
"""
|
232 |
+
Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`.
|
233 |
+
|
234 |
+
See its docstring for more information.
|
235 |
+
"""
|
236 |
+
if x.dtype not in _real_numeric_dtypes:
|
237 |
+
raise TypeError("Only real numeric dtypes are allowed in ceil")
|
238 |
+
if x.dtype in _integer_dtypes:
|
239 |
+
# Note: The return dtype of ceil is the same as the input
|
240 |
+
return x
|
241 |
+
return Array._new(np.ceil(x._array))
|
242 |
+
|
243 |
+
|
244 |
+
def conj(x: Array, /) -> Array:
|
245 |
+
"""
|
246 |
+
Array API compatible wrapper for :py:func:`np.conj <numpy.conj>`.
|
247 |
+
|
248 |
+
See its docstring for more information.
|
249 |
+
"""
|
250 |
+
if x.dtype not in _complex_floating_dtypes:
|
251 |
+
raise TypeError("Only complex floating-point dtypes are allowed in conj")
|
252 |
+
return Array._new(np.conj(x))
|
253 |
+
|
254 |
+
|
255 |
+
def cos(x: Array, /) -> Array:
|
256 |
+
"""
|
257 |
+
Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`.
|
258 |
+
|
259 |
+
See its docstring for more information.
|
260 |
+
"""
|
261 |
+
if x.dtype not in _floating_dtypes:
|
262 |
+
raise TypeError("Only floating-point dtypes are allowed in cos")
|
263 |
+
return Array._new(np.cos(x._array))
|
264 |
+
|
265 |
+
|
266 |
+
def cosh(x: Array, /) -> Array:
|
267 |
+
"""
|
268 |
+
Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`.
|
269 |
+
|
270 |
+
See its docstring for more information.
|
271 |
+
"""
|
272 |
+
if x.dtype not in _floating_dtypes:
|
273 |
+
raise TypeError("Only floating-point dtypes are allowed in cosh")
|
274 |
+
return Array._new(np.cosh(x._array))
|
275 |
+
|
276 |
+
|
277 |
+
def divide(x1: Array, x2: Array, /) -> Array:
|
278 |
+
"""
|
279 |
+
Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`.
|
280 |
+
|
281 |
+
See its docstring for more information.
|
282 |
+
"""
|
283 |
+
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
|
284 |
+
raise TypeError("Only floating-point dtypes are allowed in divide")
|
285 |
+
# Call result type here just to raise on disallowed type combinations
|
286 |
+
_result_type(x1.dtype, x2.dtype)
|
287 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
288 |
+
return Array._new(np.divide(x1._array, x2._array))
|
289 |
+
|
290 |
+
|
291 |
+
def equal(x1: Array, x2: Array, /) -> Array:
|
292 |
+
"""
|
293 |
+
Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`.
|
294 |
+
|
295 |
+
See its docstring for more information.
|
296 |
+
"""
|
297 |
+
# Call result type here just to raise on disallowed type combinations
|
298 |
+
_result_type(x1.dtype, x2.dtype)
|
299 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
300 |
+
return Array._new(np.equal(x1._array, x2._array))
|
301 |
+
|
302 |
+
|
303 |
+
def exp(x: Array, /) -> Array:
|
304 |
+
"""
|
305 |
+
Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`.
|
306 |
+
|
307 |
+
See its docstring for more information.
|
308 |
+
"""
|
309 |
+
if x.dtype not in _floating_dtypes:
|
310 |
+
raise TypeError("Only floating-point dtypes are allowed in exp")
|
311 |
+
return Array._new(np.exp(x._array))
|
312 |
+
|
313 |
+
|
314 |
+
def expm1(x: Array, /) -> Array:
|
315 |
+
"""
|
316 |
+
Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`.
|
317 |
+
|
318 |
+
See its docstring for more information.
|
319 |
+
"""
|
320 |
+
if x.dtype not in _floating_dtypes:
|
321 |
+
raise TypeError("Only floating-point dtypes are allowed in expm1")
|
322 |
+
return Array._new(np.expm1(x._array))
|
323 |
+
|
324 |
+
|
325 |
+
def floor(x: Array, /) -> Array:
|
326 |
+
"""
|
327 |
+
Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`.
|
328 |
+
|
329 |
+
See its docstring for more information.
|
330 |
+
"""
|
331 |
+
if x.dtype not in _real_numeric_dtypes:
|
332 |
+
raise TypeError("Only real numeric dtypes are allowed in floor")
|
333 |
+
if x.dtype in _integer_dtypes:
|
334 |
+
# Note: The return dtype of floor is the same as the input
|
335 |
+
return x
|
336 |
+
return Array._new(np.floor(x._array))
|
337 |
+
|
338 |
+
|
339 |
+
def floor_divide(x1: Array, x2: Array, /) -> Array:
|
340 |
+
"""
|
341 |
+
Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`.
|
342 |
+
|
343 |
+
See its docstring for more information.
|
344 |
+
"""
|
345 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
346 |
+
raise TypeError("Only real numeric dtypes are allowed in floor_divide")
|
347 |
+
# Call result type here just to raise on disallowed type combinations
|
348 |
+
_result_type(x1.dtype, x2.dtype)
|
349 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
350 |
+
return Array._new(np.floor_divide(x1._array, x2._array))
|
351 |
+
|
352 |
+
|
353 |
+
def greater(x1: Array, x2: Array, /) -> Array:
|
354 |
+
"""
|
355 |
+
Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`.
|
356 |
+
|
357 |
+
See its docstring for more information.
|
358 |
+
"""
|
359 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
360 |
+
raise TypeError("Only real numeric dtypes are allowed in greater")
|
361 |
+
# Call result type here just to raise on disallowed type combinations
|
362 |
+
_result_type(x1.dtype, x2.dtype)
|
363 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
364 |
+
return Array._new(np.greater(x1._array, x2._array))
|
365 |
+
|
366 |
+
|
367 |
+
def greater_equal(x1: Array, x2: Array, /) -> Array:
|
368 |
+
"""
|
369 |
+
Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`.
|
370 |
+
|
371 |
+
See its docstring for more information.
|
372 |
+
"""
|
373 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
374 |
+
raise TypeError("Only real numeric dtypes are allowed in greater_equal")
|
375 |
+
# Call result type here just to raise on disallowed type combinations
|
376 |
+
_result_type(x1.dtype, x2.dtype)
|
377 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
378 |
+
return Array._new(np.greater_equal(x1._array, x2._array))
|
379 |
+
|
380 |
+
|
381 |
+
def imag(x: Array, /) -> Array:
|
382 |
+
"""
|
383 |
+
Array API compatible wrapper for :py:func:`np.imag <numpy.imag>`.
|
384 |
+
|
385 |
+
See its docstring for more information.
|
386 |
+
"""
|
387 |
+
if x.dtype not in _complex_floating_dtypes:
|
388 |
+
raise TypeError("Only complex floating-point dtypes are allowed in imag")
|
389 |
+
return Array._new(np.imag(x))
|
390 |
+
|
391 |
+
|
392 |
+
def isfinite(x: Array, /) -> Array:
|
393 |
+
"""
|
394 |
+
Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`.
|
395 |
+
|
396 |
+
See its docstring for more information.
|
397 |
+
"""
|
398 |
+
if x.dtype not in _numeric_dtypes:
|
399 |
+
raise TypeError("Only numeric dtypes are allowed in isfinite")
|
400 |
+
return Array._new(np.isfinite(x._array))
|
401 |
+
|
402 |
+
|
403 |
+
def isinf(x: Array, /) -> Array:
|
404 |
+
"""
|
405 |
+
Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`.
|
406 |
+
|
407 |
+
See its docstring for more information.
|
408 |
+
"""
|
409 |
+
if x.dtype not in _numeric_dtypes:
|
410 |
+
raise TypeError("Only numeric dtypes are allowed in isinf")
|
411 |
+
return Array._new(np.isinf(x._array))
|
412 |
+
|
413 |
+
|
414 |
+
def isnan(x: Array, /) -> Array:
|
415 |
+
"""
|
416 |
+
Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`.
|
417 |
+
|
418 |
+
See its docstring for more information.
|
419 |
+
"""
|
420 |
+
if x.dtype not in _numeric_dtypes:
|
421 |
+
raise TypeError("Only numeric dtypes are allowed in isnan")
|
422 |
+
return Array._new(np.isnan(x._array))
|
423 |
+
|
424 |
+
|
425 |
+
def less(x1: Array, x2: Array, /) -> Array:
|
426 |
+
"""
|
427 |
+
Array API compatible wrapper for :py:func:`np.less <numpy.less>`.
|
428 |
+
|
429 |
+
See its docstring for more information.
|
430 |
+
"""
|
431 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
432 |
+
raise TypeError("Only real numeric dtypes are allowed in less")
|
433 |
+
# Call result type here just to raise on disallowed type combinations
|
434 |
+
_result_type(x1.dtype, x2.dtype)
|
435 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
436 |
+
return Array._new(np.less(x1._array, x2._array))
|
437 |
+
|
438 |
+
|
439 |
+
def less_equal(x1: Array, x2: Array, /) -> Array:
|
440 |
+
"""
|
441 |
+
Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`.
|
442 |
+
|
443 |
+
See its docstring for more information.
|
444 |
+
"""
|
445 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
446 |
+
raise TypeError("Only real numeric dtypes are allowed in less_equal")
|
447 |
+
# Call result type here just to raise on disallowed type combinations
|
448 |
+
_result_type(x1.dtype, x2.dtype)
|
449 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
450 |
+
return Array._new(np.less_equal(x1._array, x2._array))
|
451 |
+
|
452 |
+
|
453 |
+
def log(x: Array, /) -> Array:
|
454 |
+
"""
|
455 |
+
Array API compatible wrapper for :py:func:`np.log <numpy.log>`.
|
456 |
+
|
457 |
+
See its docstring for more information.
|
458 |
+
"""
|
459 |
+
if x.dtype not in _floating_dtypes:
|
460 |
+
raise TypeError("Only floating-point dtypes are allowed in log")
|
461 |
+
return Array._new(np.log(x._array))
|
462 |
+
|
463 |
+
|
464 |
+
def log1p(x: Array, /) -> Array:
|
465 |
+
"""
|
466 |
+
Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`.
|
467 |
+
|
468 |
+
See its docstring for more information.
|
469 |
+
"""
|
470 |
+
if x.dtype not in _floating_dtypes:
|
471 |
+
raise TypeError("Only floating-point dtypes are allowed in log1p")
|
472 |
+
return Array._new(np.log1p(x._array))
|
473 |
+
|
474 |
+
|
475 |
+
def log2(x: Array, /) -> Array:
|
476 |
+
"""
|
477 |
+
Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`.
|
478 |
+
|
479 |
+
See its docstring for more information.
|
480 |
+
"""
|
481 |
+
if x.dtype not in _floating_dtypes:
|
482 |
+
raise TypeError("Only floating-point dtypes are allowed in log2")
|
483 |
+
return Array._new(np.log2(x._array))
|
484 |
+
|
485 |
+
|
486 |
+
def log10(x: Array, /) -> Array:
|
487 |
+
"""
|
488 |
+
Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`.
|
489 |
+
|
490 |
+
See its docstring for more information.
|
491 |
+
"""
|
492 |
+
if x.dtype not in _floating_dtypes:
|
493 |
+
raise TypeError("Only floating-point dtypes are allowed in log10")
|
494 |
+
return Array._new(np.log10(x._array))
|
495 |
+
|
496 |
+
|
497 |
+
def logaddexp(x1: Array, x2: Array) -> Array:
|
498 |
+
"""
|
499 |
+
Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`.
|
500 |
+
|
501 |
+
See its docstring for more information.
|
502 |
+
"""
|
503 |
+
if x1.dtype not in _real_floating_dtypes or x2.dtype not in _real_floating_dtypes:
|
504 |
+
raise TypeError("Only real floating-point dtypes are allowed in logaddexp")
|
505 |
+
# Call result type here just to raise on disallowed type combinations
|
506 |
+
_result_type(x1.dtype, x2.dtype)
|
507 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
508 |
+
return Array._new(np.logaddexp(x1._array, x2._array))
|
509 |
+
|
510 |
+
|
511 |
+
def logical_and(x1: Array, x2: Array, /) -> Array:
|
512 |
+
"""
|
513 |
+
Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`.
|
514 |
+
|
515 |
+
See its docstring for more information.
|
516 |
+
"""
|
517 |
+
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
|
518 |
+
raise TypeError("Only boolean dtypes are allowed in logical_and")
|
519 |
+
# Call result type here just to raise on disallowed type combinations
|
520 |
+
_result_type(x1.dtype, x2.dtype)
|
521 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
522 |
+
return Array._new(np.logical_and(x1._array, x2._array))
|
523 |
+
|
524 |
+
|
525 |
+
def logical_not(x: Array, /) -> Array:
|
526 |
+
"""
|
527 |
+
Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`.
|
528 |
+
|
529 |
+
See its docstring for more information.
|
530 |
+
"""
|
531 |
+
if x.dtype not in _boolean_dtypes:
|
532 |
+
raise TypeError("Only boolean dtypes are allowed in logical_not")
|
533 |
+
return Array._new(np.logical_not(x._array))
|
534 |
+
|
535 |
+
|
536 |
+
def logical_or(x1: Array, x2: Array, /) -> Array:
|
537 |
+
"""
|
538 |
+
Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`.
|
539 |
+
|
540 |
+
See its docstring for more information.
|
541 |
+
"""
|
542 |
+
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
|
543 |
+
raise TypeError("Only boolean dtypes are allowed in logical_or")
|
544 |
+
# Call result type here just to raise on disallowed type combinations
|
545 |
+
_result_type(x1.dtype, x2.dtype)
|
546 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
547 |
+
return Array._new(np.logical_or(x1._array, x2._array))
|
548 |
+
|
549 |
+
|
550 |
+
def logical_xor(x1: Array, x2: Array, /) -> Array:
|
551 |
+
"""
|
552 |
+
Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`.
|
553 |
+
|
554 |
+
See its docstring for more information.
|
555 |
+
"""
|
556 |
+
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
|
557 |
+
raise TypeError("Only boolean dtypes are allowed in logical_xor")
|
558 |
+
# Call result type here just to raise on disallowed type combinations
|
559 |
+
_result_type(x1.dtype, x2.dtype)
|
560 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
561 |
+
return Array._new(np.logical_xor(x1._array, x2._array))
|
562 |
+
|
563 |
+
|
564 |
+
def multiply(x1: Array, x2: Array, /) -> Array:
|
565 |
+
"""
|
566 |
+
Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`.
|
567 |
+
|
568 |
+
See its docstring for more information.
|
569 |
+
"""
|
570 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
571 |
+
raise TypeError("Only numeric dtypes are allowed in multiply")
|
572 |
+
# Call result type here just to raise on disallowed type combinations
|
573 |
+
_result_type(x1.dtype, x2.dtype)
|
574 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
575 |
+
return Array._new(np.multiply(x1._array, x2._array))
|
576 |
+
|
577 |
+
|
578 |
+
def negative(x: Array, /) -> Array:
|
579 |
+
"""
|
580 |
+
Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`.
|
581 |
+
|
582 |
+
See its docstring for more information.
|
583 |
+
"""
|
584 |
+
if x.dtype not in _numeric_dtypes:
|
585 |
+
raise TypeError("Only numeric dtypes are allowed in negative")
|
586 |
+
return Array._new(np.negative(x._array))
|
587 |
+
|
588 |
+
|
589 |
+
def not_equal(x1: Array, x2: Array, /) -> Array:
|
590 |
+
"""
|
591 |
+
Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`.
|
592 |
+
|
593 |
+
See its docstring for more information.
|
594 |
+
"""
|
595 |
+
# Call result type here just to raise on disallowed type combinations
|
596 |
+
_result_type(x1.dtype, x2.dtype)
|
597 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
598 |
+
return Array._new(np.not_equal(x1._array, x2._array))
|
599 |
+
|
600 |
+
|
601 |
+
def positive(x: Array, /) -> Array:
|
602 |
+
"""
|
603 |
+
Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`.
|
604 |
+
|
605 |
+
See its docstring for more information.
|
606 |
+
"""
|
607 |
+
if x.dtype not in _numeric_dtypes:
|
608 |
+
raise TypeError("Only numeric dtypes are allowed in positive")
|
609 |
+
return Array._new(np.positive(x._array))
|
610 |
+
|
611 |
+
|
612 |
+
# Note: the function name is different here
|
613 |
+
def pow(x1: Array, x2: Array, /) -> Array:
|
614 |
+
"""
|
615 |
+
Array API compatible wrapper for :py:func:`np.power <numpy.power>`.
|
616 |
+
|
617 |
+
See its docstring for more information.
|
618 |
+
"""
|
619 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
620 |
+
raise TypeError("Only numeric dtypes are allowed in pow")
|
621 |
+
# Call result type here just to raise on disallowed type combinations
|
622 |
+
_result_type(x1.dtype, x2.dtype)
|
623 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
624 |
+
return Array._new(np.power(x1._array, x2._array))
|
625 |
+
|
626 |
+
|
627 |
+
def real(x: Array, /) -> Array:
|
628 |
+
"""
|
629 |
+
Array API compatible wrapper for :py:func:`np.real <numpy.real>`.
|
630 |
+
|
631 |
+
See its docstring for more information.
|
632 |
+
"""
|
633 |
+
if x.dtype not in _complex_floating_dtypes:
|
634 |
+
raise TypeError("Only complex floating-point dtypes are allowed in real")
|
635 |
+
return Array._new(np.real(x))
|
636 |
+
|
637 |
+
|
638 |
+
def remainder(x1: Array, x2: Array, /) -> Array:
|
639 |
+
"""
|
640 |
+
Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`.
|
641 |
+
|
642 |
+
See its docstring for more information.
|
643 |
+
"""
|
644 |
+
if x1.dtype not in _real_numeric_dtypes or x2.dtype not in _real_numeric_dtypes:
|
645 |
+
raise TypeError("Only real numeric dtypes are allowed in remainder")
|
646 |
+
# Call result type here just to raise on disallowed type combinations
|
647 |
+
_result_type(x1.dtype, x2.dtype)
|
648 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
649 |
+
return Array._new(np.remainder(x1._array, x2._array))
|
650 |
+
|
651 |
+
|
652 |
+
def round(x: Array, /) -> Array:
|
653 |
+
"""
|
654 |
+
Array API compatible wrapper for :py:func:`np.round <numpy.round>`.
|
655 |
+
|
656 |
+
See its docstring for more information.
|
657 |
+
"""
|
658 |
+
if x.dtype not in _numeric_dtypes:
|
659 |
+
raise TypeError("Only numeric dtypes are allowed in round")
|
660 |
+
return Array._new(np.round(x._array))
|
661 |
+
|
662 |
+
|
663 |
+
def sign(x: Array, /) -> Array:
|
664 |
+
"""
|
665 |
+
Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`.
|
666 |
+
|
667 |
+
See its docstring for more information.
|
668 |
+
"""
|
669 |
+
if x.dtype not in _numeric_dtypes:
|
670 |
+
raise TypeError("Only numeric dtypes are allowed in sign")
|
671 |
+
return Array._new(np.sign(x._array))
|
672 |
+
|
673 |
+
|
674 |
+
def sin(x: Array, /) -> Array:
|
675 |
+
"""
|
676 |
+
Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`.
|
677 |
+
|
678 |
+
See its docstring for more information.
|
679 |
+
"""
|
680 |
+
if x.dtype not in _floating_dtypes:
|
681 |
+
raise TypeError("Only floating-point dtypes are allowed in sin")
|
682 |
+
return Array._new(np.sin(x._array))
|
683 |
+
|
684 |
+
|
685 |
+
def sinh(x: Array, /) -> Array:
|
686 |
+
"""
|
687 |
+
Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`.
|
688 |
+
|
689 |
+
See its docstring for more information.
|
690 |
+
"""
|
691 |
+
if x.dtype not in _floating_dtypes:
|
692 |
+
raise TypeError("Only floating-point dtypes are allowed in sinh")
|
693 |
+
return Array._new(np.sinh(x._array))
|
694 |
+
|
695 |
+
|
696 |
+
def square(x: Array, /) -> Array:
|
697 |
+
"""
|
698 |
+
Array API compatible wrapper for :py:func:`np.square <numpy.square>`.
|
699 |
+
|
700 |
+
See its docstring for more information.
|
701 |
+
"""
|
702 |
+
if x.dtype not in _numeric_dtypes:
|
703 |
+
raise TypeError("Only numeric dtypes are allowed in square")
|
704 |
+
return Array._new(np.square(x._array))
|
705 |
+
|
706 |
+
|
707 |
+
def sqrt(x: Array, /) -> Array:
|
708 |
+
"""
|
709 |
+
Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`.
|
710 |
+
|
711 |
+
See its docstring for more information.
|
712 |
+
"""
|
713 |
+
if x.dtype not in _floating_dtypes:
|
714 |
+
raise TypeError("Only floating-point dtypes are allowed in sqrt")
|
715 |
+
return Array._new(np.sqrt(x._array))
|
716 |
+
|
717 |
+
|
718 |
+
def subtract(x1: Array, x2: Array, /) -> Array:
|
719 |
+
"""
|
720 |
+
Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`.
|
721 |
+
|
722 |
+
See its docstring for more information.
|
723 |
+
"""
|
724 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
725 |
+
raise TypeError("Only numeric dtypes are allowed in subtract")
|
726 |
+
# Call result type here just to raise on disallowed type combinations
|
727 |
+
_result_type(x1.dtype, x2.dtype)
|
728 |
+
x1, x2 = Array._normalize_two_args(x1, x2)
|
729 |
+
return Array._new(np.subtract(x1._array, x2._array))
|
730 |
+
|
731 |
+
|
732 |
+
def tan(x: Array, /) -> Array:
|
733 |
+
"""
|
734 |
+
Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`.
|
735 |
+
|
736 |
+
See its docstring for more information.
|
737 |
+
"""
|
738 |
+
if x.dtype not in _floating_dtypes:
|
739 |
+
raise TypeError("Only floating-point dtypes are allowed in tan")
|
740 |
+
return Array._new(np.tan(x._array))
|
741 |
+
|
742 |
+
|
743 |
+
def tanh(x: Array, /) -> Array:
|
744 |
+
"""
|
745 |
+
Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`.
|
746 |
+
|
747 |
+
See its docstring for more information.
|
748 |
+
"""
|
749 |
+
if x.dtype not in _floating_dtypes:
|
750 |
+
raise TypeError("Only floating-point dtypes are allowed in tanh")
|
751 |
+
return Array._new(np.tanh(x._array))
|
752 |
+
|
753 |
+
|
754 |
+
def trunc(x: Array, /) -> Array:
|
755 |
+
"""
|
756 |
+
Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`.
|
757 |
+
|
758 |
+
See its docstring for more information.
|
759 |
+
"""
|
760 |
+
if x.dtype not in _real_numeric_dtypes:
|
761 |
+
raise TypeError("Only real numeric dtypes are allowed in trunc")
|
762 |
+
if x.dtype in _integer_dtypes:
|
763 |
+
# Note: The return dtype of trunc is the same as the input
|
764 |
+
return x
|
765 |
+
return Array._new(np.trunc(x._array))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_indexing_functions.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
from ._dtypes import _integer_dtypes
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
def take(x: Array, indices: Array, /, *, axis: Optional[int] = None) -> Array:
|
9 |
+
"""
|
10 |
+
Array API compatible wrapper for :py:func:`np.take <numpy.take>`.
|
11 |
+
|
12 |
+
See its docstring for more information.
|
13 |
+
"""
|
14 |
+
if axis is None and x.ndim != 1:
|
15 |
+
raise ValueError("axis must be specified when ndim > 1")
|
16 |
+
if indices.dtype not in _integer_dtypes:
|
17 |
+
raise TypeError("Only integer dtypes are allowed in indexing")
|
18 |
+
if indices.ndim != 1:
|
19 |
+
raise ValueError("Only 1-dim indices array is supported")
|
20 |
+
return Array._new(np.take(x._array, indices._array, axis=axis))
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_set_functions.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._array_object import Array
|
4 |
+
|
5 |
+
from typing import NamedTuple
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
# Note: np.unique() is split into four functions in the array API:
|
10 |
+
# unique_all, unique_counts, unique_inverse, and unique_values (this is done
|
11 |
+
# to remove polymorphic return types).
|
12 |
+
|
13 |
+
# Note: The various unique() functions are supposed to return multiple NaNs.
|
14 |
+
# This does not match the NumPy behavior, however, this is currently left as a
|
15 |
+
# TODO in this implementation as this behavior may be reverted in np.unique().
|
16 |
+
# See https://github.com/numpy/numpy/issues/20326.
|
17 |
+
|
18 |
+
# Note: The functions here return a namedtuple (np.unique() returns a normal
|
19 |
+
# tuple).
|
20 |
+
|
21 |
+
class UniqueAllResult(NamedTuple):
|
22 |
+
values: Array
|
23 |
+
indices: Array
|
24 |
+
inverse_indices: Array
|
25 |
+
counts: Array
|
26 |
+
|
27 |
+
|
28 |
+
class UniqueCountsResult(NamedTuple):
|
29 |
+
values: Array
|
30 |
+
counts: Array
|
31 |
+
|
32 |
+
|
33 |
+
class UniqueInverseResult(NamedTuple):
|
34 |
+
values: Array
|
35 |
+
inverse_indices: Array
|
36 |
+
|
37 |
+
|
38 |
+
def unique_all(x: Array, /) -> UniqueAllResult:
|
39 |
+
"""
|
40 |
+
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
|
41 |
+
|
42 |
+
See its docstring for more information.
|
43 |
+
"""
|
44 |
+
values, indices, inverse_indices, counts = np.unique(
|
45 |
+
x._array,
|
46 |
+
return_counts=True,
|
47 |
+
return_index=True,
|
48 |
+
return_inverse=True,
|
49 |
+
equal_nan=False,
|
50 |
+
)
|
51 |
+
# np.unique() flattens inverse indices, but they need to share x's shape
|
52 |
+
# See https://github.com/numpy/numpy/issues/20638
|
53 |
+
inverse_indices = inverse_indices.reshape(x.shape)
|
54 |
+
return UniqueAllResult(
|
55 |
+
Array._new(values),
|
56 |
+
Array._new(indices),
|
57 |
+
Array._new(inverse_indices),
|
58 |
+
Array._new(counts),
|
59 |
+
)
|
60 |
+
|
61 |
+
|
62 |
+
def unique_counts(x: Array, /) -> UniqueCountsResult:
|
63 |
+
res = np.unique(
|
64 |
+
x._array,
|
65 |
+
return_counts=True,
|
66 |
+
return_index=False,
|
67 |
+
return_inverse=False,
|
68 |
+
equal_nan=False,
|
69 |
+
)
|
70 |
+
|
71 |
+
return UniqueCountsResult(*[Array._new(i) for i in res])
|
72 |
+
|
73 |
+
|
74 |
+
def unique_inverse(x: Array, /) -> UniqueInverseResult:
|
75 |
+
"""
|
76 |
+
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
|
77 |
+
|
78 |
+
See its docstring for more information.
|
79 |
+
"""
|
80 |
+
values, inverse_indices = np.unique(
|
81 |
+
x._array,
|
82 |
+
return_counts=False,
|
83 |
+
return_index=False,
|
84 |
+
return_inverse=True,
|
85 |
+
equal_nan=False,
|
86 |
+
)
|
87 |
+
# np.unique() flattens inverse indices, but they need to share x's shape
|
88 |
+
# See https://github.com/numpy/numpy/issues/20638
|
89 |
+
inverse_indices = inverse_indices.reshape(x.shape)
|
90 |
+
return UniqueInverseResult(Array._new(values), Array._new(inverse_indices))
|
91 |
+
|
92 |
+
|
93 |
+
def unique_values(x: Array, /) -> Array:
|
94 |
+
"""
|
95 |
+
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
|
96 |
+
|
97 |
+
See its docstring for more information.
|
98 |
+
"""
|
99 |
+
res = np.unique(
|
100 |
+
x._array,
|
101 |
+
return_counts=False,
|
102 |
+
return_index=False,
|
103 |
+
return_inverse=False,
|
104 |
+
equal_nan=False,
|
105 |
+
)
|
106 |
+
return Array._new(res)
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/_statistical_functions.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from ._dtypes import (
|
4 |
+
_real_floating_dtypes,
|
5 |
+
_real_numeric_dtypes,
|
6 |
+
_numeric_dtypes,
|
7 |
+
)
|
8 |
+
from ._array_object import Array
|
9 |
+
from ._dtypes import float32, float64, complex64, complex128
|
10 |
+
|
11 |
+
from typing import TYPE_CHECKING, Optional, Tuple, Union
|
12 |
+
|
13 |
+
if TYPE_CHECKING:
|
14 |
+
from ._typing import Dtype
|
15 |
+
|
16 |
+
import numpy as np
|
17 |
+
|
18 |
+
|
19 |
+
def max(
|
20 |
+
x: Array,
|
21 |
+
/,
|
22 |
+
*,
|
23 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
24 |
+
keepdims: bool = False,
|
25 |
+
) -> Array:
|
26 |
+
if x.dtype not in _real_numeric_dtypes:
|
27 |
+
raise TypeError("Only real numeric dtypes are allowed in max")
|
28 |
+
return Array._new(np.max(x._array, axis=axis, keepdims=keepdims))
|
29 |
+
|
30 |
+
|
31 |
+
def mean(
|
32 |
+
x: Array,
|
33 |
+
/,
|
34 |
+
*,
|
35 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
36 |
+
keepdims: bool = False,
|
37 |
+
) -> Array:
|
38 |
+
if x.dtype not in _real_floating_dtypes:
|
39 |
+
raise TypeError("Only real floating-point dtypes are allowed in mean")
|
40 |
+
return Array._new(np.mean(x._array, axis=axis, keepdims=keepdims))
|
41 |
+
|
42 |
+
|
43 |
+
def min(
|
44 |
+
x: Array,
|
45 |
+
/,
|
46 |
+
*,
|
47 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
48 |
+
keepdims: bool = False,
|
49 |
+
) -> Array:
|
50 |
+
if x.dtype not in _real_numeric_dtypes:
|
51 |
+
raise TypeError("Only real numeric dtypes are allowed in min")
|
52 |
+
return Array._new(np.min(x._array, axis=axis, keepdims=keepdims))
|
53 |
+
|
54 |
+
|
55 |
+
def prod(
|
56 |
+
x: Array,
|
57 |
+
/,
|
58 |
+
*,
|
59 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
60 |
+
dtype: Optional[Dtype] = None,
|
61 |
+
keepdims: bool = False,
|
62 |
+
) -> Array:
|
63 |
+
if x.dtype not in _numeric_dtypes:
|
64 |
+
raise TypeError("Only numeric dtypes are allowed in prod")
|
65 |
+
# Note: sum() and prod() always upcast for dtype=None. `np.prod` does that
|
66 |
+
# for integers, but not for float32 or complex64, so we need to
|
67 |
+
# special-case it here
|
68 |
+
if dtype is None:
|
69 |
+
if x.dtype == float32:
|
70 |
+
dtype = float64
|
71 |
+
elif x.dtype == complex64:
|
72 |
+
dtype = complex128
|
73 |
+
return Array._new(np.prod(x._array, dtype=dtype, axis=axis, keepdims=keepdims))
|
74 |
+
|
75 |
+
|
76 |
+
def std(
|
77 |
+
x: Array,
|
78 |
+
/,
|
79 |
+
*,
|
80 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
81 |
+
correction: Union[int, float] = 0.0,
|
82 |
+
keepdims: bool = False,
|
83 |
+
) -> Array:
|
84 |
+
# Note: the keyword argument correction is different here
|
85 |
+
if x.dtype not in _real_floating_dtypes:
|
86 |
+
raise TypeError("Only real floating-point dtypes are allowed in std")
|
87 |
+
return Array._new(np.std(x._array, axis=axis, ddof=correction, keepdims=keepdims))
|
88 |
+
|
89 |
+
|
90 |
+
def sum(
|
91 |
+
x: Array,
|
92 |
+
/,
|
93 |
+
*,
|
94 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
95 |
+
dtype: Optional[Dtype] = None,
|
96 |
+
keepdims: bool = False,
|
97 |
+
) -> Array:
|
98 |
+
if x.dtype not in _numeric_dtypes:
|
99 |
+
raise TypeError("Only numeric dtypes are allowed in sum")
|
100 |
+
# Note: sum() and prod() always upcast for dtype=None. `np.sum` does that
|
101 |
+
# for integers, but not for float32 or complex64, so we need to
|
102 |
+
# special-case it here
|
103 |
+
if dtype is None:
|
104 |
+
if x.dtype == float32:
|
105 |
+
dtype = float64
|
106 |
+
elif x.dtype == complex64:
|
107 |
+
dtype = complex128
|
108 |
+
return Array._new(np.sum(x._array, axis=axis, dtype=dtype, keepdims=keepdims))
|
109 |
+
|
110 |
+
|
111 |
+
def var(
|
112 |
+
x: Array,
|
113 |
+
/,
|
114 |
+
*,
|
115 |
+
axis: Optional[Union[int, Tuple[int, ...]]] = None,
|
116 |
+
correction: Union[int, float] = 0.0,
|
117 |
+
keepdims: bool = False,
|
118 |
+
) -> Array:
|
119 |
+
# Note: the keyword argument correction is different here
|
120 |
+
if x.dtype not in _real_floating_dtypes:
|
121 |
+
raise TypeError("Only real floating-point dtypes are allowed in var")
|
122 |
+
return Array._new(np.var(x._array, axis=axis, ddof=correction, keepdims=keepdims))
|
env-llmeval/lib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|
+
)
|
11 |
+
from ._manipulation_functions import reshape
|
12 |
+
from ._elementwise_functions import conj
|
13 |
+
from ._array_object import Array
|
14 |
+
|
15 |
+
from ..core.numeric import normalize_axis_tuple
|
16 |
+
|
17 |
+
from typing import TYPE_CHECKING
|
18 |
+
if TYPE_CHECKING:
|
19 |
+
from ._typing import Literal, Optional, Sequence, Tuple, Union, Dtype
|
20 |
+
|
21 |
+
from typing import NamedTuple
|
22 |
+
|
23 |
+
import numpy.linalg
|
24 |
+
import numpy as np
|
25 |
+
|
26 |
+
class EighResult(NamedTuple):
|
27 |
+
eigenvalues: Array
|
28 |
+
eigenvectors: Array
|
29 |
+
|
30 |
+
class QRResult(NamedTuple):
|
31 |
+
Q: Array
|
32 |
+
R: Array
|
33 |
+
|
34 |
+
class SlogdetResult(NamedTuple):
|
35 |
+
sign: Array
|
36 |
+
logabsdet: Array
|
37 |
+
|
38 |
+
class SVDResult(NamedTuple):
|
39 |
+
U: Array
|
40 |
+
S: Array
|
41 |
+
Vh: Array
|
42 |
+
|
43 |
+
# Note: the inclusion of the upper keyword is different from
|
44 |
+
# np.linalg.cholesky, which does not have it.
|
45 |
+
def cholesky(x: Array, /, *, upper: bool = False) -> Array:
|
46 |
+
"""
|
47 |
+
Array API compatible wrapper for :py:func:`np.linalg.cholesky <numpy.linalg.cholesky>`.
|
48 |
+
|
49 |
+
See its docstring for more information.
|
50 |
+
"""
|
51 |
+
# Note: the restriction to floating-point dtypes only is different from
|
52 |
+
# np.linalg.cholesky.
|
53 |
+
if x.dtype not in _floating_dtypes:
|
54 |
+
raise TypeError('Only floating-point dtypes are allowed in cholesky')
|
55 |
+
L = np.linalg.cholesky(x._array)
|
56 |
+
if upper:
|
57 |
+
U = Array._new(L).mT
|
58 |
+
if U.dtype in [complex64, complex128]:
|
59 |
+
U = conj(U)
|
60 |
+
return U
|
61 |
+
return Array._new(L)
|
62 |
+
|
63 |
+
# Note: cross is the numpy top-level namespace, not np.linalg
|
64 |
+
def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
|
65 |
+
"""
|
66 |
+
Array API compatible wrapper for :py:func:`np.cross <numpy.cross>`.
|
67 |
+
|
68 |
+
See its docstring for more information.
|
69 |
+
"""
|
70 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
71 |
+
raise TypeError('Only numeric dtypes are allowed in cross')
|
72 |
+
# Note: this is different from np.cross(), which broadcasts
|
73 |
+
if x1.shape != x2.shape:
|
74 |
+
raise ValueError('x1 and x2 must have the same shape')
|
75 |
+
if x1.ndim == 0:
|
76 |
+
raise ValueError('cross() requires arrays of dimension at least 1')
|
77 |
+
# Note: this is different from np.cross(), which allows dimension 2
|
78 |
+
if x1.shape[axis] != 3:
|
79 |
+
raise ValueError('cross() dimension must equal 3')
|
80 |
+
return Array._new(np.cross(x1._array, x2._array, axis=axis))
|
81 |
+
|
82 |
+
def det(x: Array, /) -> Array:
|
83 |
+
"""
|
84 |
+
Array API compatible wrapper for :py:func:`np.linalg.det <numpy.linalg.det>`.
|
85 |
+
|
86 |
+
See its docstring for more information.
|
87 |
+
"""
|
88 |
+
# Note: the restriction to floating-point dtypes only is different from
|
89 |
+
# np.linalg.det.
|
90 |
+
if x.dtype not in _floating_dtypes:
|
91 |
+
raise TypeError('Only floating-point dtypes are allowed in det')
|
92 |
+
return Array._new(np.linalg.det(x._array))
|
93 |
+
|
94 |
+
# Note: diagonal is the numpy top-level namespace, not np.linalg
|
95 |
+
def diagonal(x: Array, /, *, offset: int = 0) -> Array:
|
96 |
+
"""
|
97 |
+
Array API compatible wrapper for :py:func:`np.diagonal <numpy.diagonal>`.
|
98 |
+
|
99 |
+
See its docstring for more information.
|
100 |
+
"""
|
101 |
+
# Note: diagonal always operates on the last two axes, whereas np.diagonal
|
102 |
+
# operates on the first two axes by default
|
103 |
+
return Array._new(np.diagonal(x._array, offset=offset, axis1=-2, axis2=-1))
|
104 |
+
|
105 |
+
|
106 |
+
def eigh(x: Array, /) -> EighResult:
|
107 |
+
"""
|
108 |
+
Array API compatible wrapper for :py:func:`np.linalg.eigh <numpy.linalg.eigh>`.
|
109 |
+
|
110 |
+
See its docstring for more information.
|
111 |
+
"""
|
112 |
+
# Note: the restriction to floating-point dtypes only is different from
|
113 |
+
# np.linalg.eigh.
|
114 |
+
if x.dtype not in _floating_dtypes:
|
115 |
+
raise TypeError('Only floating-point dtypes are allowed in eigh')
|
116 |
+
|
117 |
+
# Note: the return type here is a namedtuple, which is different from
|
118 |
+
# np.eigh, which only returns a tuple.
|
119 |
+
return EighResult(*map(Array._new, np.linalg.eigh(x._array)))
|
120 |
+
|
121 |
+
|
122 |
+
def eigvalsh(x: Array, /) -> Array:
|
123 |
+
"""
|
124 |
+
Array API compatible wrapper for :py:func:`np.linalg.eigvalsh <numpy.linalg.eigvalsh>`.
|
125 |
+
|
126 |
+
See its docstring for more information.
|
127 |
+
"""
|
128 |
+
# Note: the restriction to floating-point dtypes only is different from
|
129 |
+
# np.linalg.eigvalsh.
|
130 |
+
if x.dtype not in _floating_dtypes:
|
131 |
+
raise TypeError('Only floating-point dtypes are allowed in eigvalsh')
|
132 |
+
|
133 |
+
return Array._new(np.linalg.eigvalsh(x._array))
|
134 |
+
|
135 |
+
def inv(x: Array, /) -> Array:
|
136 |
+
"""
|
137 |
+
Array API compatible wrapper for :py:func:`np.linalg.inv <numpy.linalg.inv>`.
|
138 |
+
|
139 |
+
See its docstring for more information.
|
140 |
+
"""
|
141 |
+
# Note: the restriction to floating-point dtypes only is different from
|
142 |
+
# np.linalg.inv.
|
143 |
+
if x.dtype not in _floating_dtypes:
|
144 |
+
raise TypeError('Only floating-point dtypes are allowed in inv')
|
145 |
+
|
146 |
+
return Array._new(np.linalg.inv(x._array))
|
147 |
+
|
148 |
+
|
149 |
+
# Note: matmul is the numpy top-level namespace but not in np.linalg
|
150 |
+
def matmul(x1: Array, x2: Array, /) -> Array:
|
151 |
+
"""
|
152 |
+
Array API compatible wrapper for :py:func:`np.matmul <numpy.matmul>`.
|
153 |
+
|
154 |
+
See its docstring for more information.
|
155 |
+
"""
|
156 |
+
# Note: the restriction to numeric dtypes only is different from
|
157 |
+
# np.matmul.
|
158 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
159 |
+
raise TypeError('Only numeric dtypes are allowed in matmul')
|
160 |
+
|
161 |
+
return Array._new(np.matmul(x1._array, x2._array))
|
162 |
+
|
163 |
+
|
164 |
+
# Note: the name here is different from norm(). The array API norm is split
|
165 |
+
# into matrix_norm and vector_norm().
|
166 |
+
|
167 |
+
# The type for ord should be Optional[Union[int, float, Literal[np.inf,
|
168 |
+
# -np.inf, 'fro', 'nuc']]], but Literal does not support floating-point
|
169 |
+
# literals.
|
170 |
+
def matrix_norm(x: Array, /, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> Array:
|
171 |
+
"""
|
172 |
+
Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
|
173 |
+
|
174 |
+
See its docstring for more information.
|
175 |
+
"""
|
176 |
+
# Note: the restriction to floating-point dtypes only is different from
|
177 |
+
# np.linalg.norm.
|
178 |
+
if x.dtype not in _floating_dtypes:
|
179 |
+
raise TypeError('Only floating-point dtypes are allowed in matrix_norm')
|
180 |
+
|
181 |
+
return Array._new(np.linalg.norm(x._array, axis=(-2, -1), keepdims=keepdims, ord=ord))
|
182 |
+
|
183 |
+
|
184 |
+
def matrix_power(x: Array, n: int, /) -> Array:
|
185 |
+
"""
|
186 |
+
Array API compatible wrapper for :py:func:`np.matrix_power <numpy.matrix_power>`.
|
187 |
+
|
188 |
+
See its docstring for more information.
|
189 |
+
"""
|
190 |
+
# Note: the restriction to floating-point dtypes only is different from
|
191 |
+
# np.linalg.matrix_power.
|
192 |
+
if x.dtype not in _floating_dtypes:
|
193 |
+
raise TypeError('Only floating-point dtypes are allowed for the first argument of matrix_power')
|
194 |
+
|
195 |
+
# np.matrix_power already checks if n is an integer
|
196 |
+
return Array._new(np.linalg.matrix_power(x._array, n))
|
197 |
+
|
198 |
+
# Note: the keyword argument name rtol is different from np.linalg.matrix_rank
|
199 |
+
def matrix_rank(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
|
200 |
+
"""
|
201 |
+
Array API compatible wrapper for :py:func:`np.matrix_rank <numpy.matrix_rank>`.
|
202 |
+
|
203 |
+
See its docstring for more information.
|
204 |
+
"""
|
205 |
+
# Note: this is different from np.linalg.matrix_rank, which supports 1
|
206 |
+
# dimensional arrays.
|
207 |
+
if x.ndim < 2:
|
208 |
+
raise np.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
|
209 |
+
S = np.linalg.svd(x._array, compute_uv=False)
|
210 |
+
if rtol is None:
|
211 |
+
tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * np.finfo(S.dtype).eps
|
212 |
+
else:
|
213 |
+
if isinstance(rtol, Array):
|
214 |
+
rtol = rtol._array
|
215 |
+
# Note: this is different from np.linalg.matrix_rank, which does not multiply
|
216 |
+
# the tolerance by the largest singular value.
|
217 |
+
tol = S.max(axis=-1, keepdims=True)*np.asarray(rtol)[..., np.newaxis]
|
218 |
+
return Array._new(np.count_nonzero(S > tol, axis=-1))
|
219 |
+
|
220 |
+
|
221 |
+
# Note: this function is new in the array API spec. Unlike transpose, it only
|
222 |
+
# transposes the last two axes.
|
223 |
+
def matrix_transpose(x: Array, /) -> Array:
|
224 |
+
if x.ndim < 2:
|
225 |
+
raise ValueError("x must be at least 2-dimensional for matrix_transpose")
|
226 |
+
return Array._new(np.swapaxes(x._array, -1, -2))
|
227 |
+
|
228 |
+
# Note: outer is the numpy top-level namespace, not np.linalg
|
229 |
+
def outer(x1: Array, x2: Array, /) -> Array:
|
230 |
+
"""
|
231 |
+
Array API compatible wrapper for :py:func:`np.outer <numpy.outer>`.
|
232 |
+
|
233 |
+
See its docstring for more information.
|
234 |
+
"""
|
235 |
+
# Note: the restriction to numeric dtypes only is different from
|
236 |
+
# np.outer.
|
237 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
238 |
+
raise TypeError('Only numeric dtypes are allowed in outer')
|
239 |
+
|
240 |
+
# Note: the restriction to only 1-dim arrays is different from np.outer
|
241 |
+
if x1.ndim != 1 or x2.ndim != 1:
|
242 |
+
raise ValueError('The input arrays to outer must be 1-dimensional')
|
243 |
+
|
244 |
+
return Array._new(np.outer(x1._array, x2._array))
|
245 |
+
|
246 |
+
# Note: the keyword argument name rtol is different from np.linalg.pinv
|
247 |
+
def pinv(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
|
248 |
+
"""
|
249 |
+
Array API compatible wrapper for :py:func:`np.linalg.pinv <numpy.linalg.pinv>`.
|
250 |
+
|
251 |
+
See its docstring for more information.
|
252 |
+
"""
|
253 |
+
# Note: the restriction to floating-point dtypes only is different from
|
254 |
+
# np.linalg.pinv.
|
255 |
+
if x.dtype not in _floating_dtypes:
|
256 |
+
raise TypeError('Only floating-point dtypes are allowed in pinv')
|
257 |
+
|
258 |
+
# Note: this is different from np.linalg.pinv, which does not multiply the
|
259 |
+
# default tolerance by max(M, N).
|
260 |
+
if rtol is None:
|
261 |
+
rtol = max(x.shape[-2:]) * np.finfo(x.dtype).eps
|
262 |
+
return Array._new(np.linalg.pinv(x._array, rcond=rtol))
|
263 |
+
|
264 |
+
def qr(x: Array, /, *, mode: Literal['reduced', 'complete'] = 'reduced') -> QRResult:
|
265 |
+
"""
|
266 |
+
Array API compatible wrapper for :py:func:`np.linalg.qr <numpy.linalg.qr>`.
|
267 |
+
|
268 |
+
See its docstring for more information.
|
269 |
+
"""
|
270 |
+
# Note: the restriction to floating-point dtypes only is different from
|
271 |
+
# np.linalg.qr.
|
272 |
+
if x.dtype not in _floating_dtypes:
|
273 |
+
raise TypeError('Only floating-point dtypes are allowed in qr')
|
274 |
+
|
275 |
+
# Note: the return type here is a namedtuple, which is different from
|
276 |
+
# np.linalg.qr, which only returns a tuple.
|
277 |
+
return QRResult(*map(Array._new, np.linalg.qr(x._array, mode=mode)))
|
278 |
+
|
279 |
+
def slogdet(x: Array, /) -> SlogdetResult:
|
280 |
+
"""
|
281 |
+
Array API compatible wrapper for :py:func:`np.linalg.slogdet <numpy.linalg.slogdet>`.
|
282 |
+
|
283 |
+
See its docstring for more information.
|
284 |
+
"""
|
285 |
+
# Note: the restriction to floating-point dtypes only is different from
|
286 |
+
# np.linalg.slogdet.
|
287 |
+
if x.dtype not in _floating_dtypes:
|
288 |
+
raise TypeError('Only floating-point dtypes are allowed in slogdet')
|
289 |
+
|
290 |
+
# Note: the return type here is a namedtuple, which is different from
|
291 |
+
# np.linalg.slogdet, which only returns a tuple.
|
292 |
+
return SlogdetResult(*map(Array._new, np.linalg.slogdet(x._array)))
|
293 |
+
|
294 |
+
# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
|
295 |
+
# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
|
296 |
+
# of matrices. The np.linalg.solve behavior of allowing stacks of both
|
297 |
+
# matrices and vectors is ambiguous c.f.
|
298 |
+
# https://github.com/numpy/numpy/issues/15349 and
|
299 |
+
# https://github.com/data-apis/array-api/issues/285.
|
300 |
+
|
301 |
+
# To workaround this, the below is the code from np.linalg.solve except
|
302 |
+
# only calling solve1 in the exactly 1D case.
|
303 |
+
def _solve(a, b):
|
304 |
+
from ..linalg.linalg import (_makearray, _assert_stacked_2d,
|
305 |
+
_assert_stacked_square, _commonType,
|
306 |
+
isComplexType, get_linalg_error_extobj,
|
307 |
+
_raise_linalgerror_singular)
|
308 |
+
from ..linalg import _umath_linalg
|
309 |
+
|
310 |
+
a, _ = _makearray(a)
|
311 |
+
_assert_stacked_2d(a)
|
312 |
+
_assert_stacked_square(a)
|
313 |
+
b, wrap = _makearray(b)
|
314 |
+
t, result_t = _commonType(a, b)
|
315 |
+
|
316 |
+
# This part is different from np.linalg.solve
|
317 |
+
if b.ndim == 1:
|
318 |
+
gufunc = _umath_linalg.solve1
|
319 |
+
else:
|
320 |
+
gufunc = _umath_linalg.solve
|
321 |
+
|
322 |
+
# This does nothing currently but is left in because it will be relevant
|
323 |
+
# when complex dtype support is added to the spec in 2022.
|
324 |
+
signature = 'DD->D' if isComplexType(t) else 'dd->d'
|
325 |
+
with np.errstate(call=_raise_linalgerror_singular, invalid='call',
|
326 |
+
over='ignore', divide='ignore', under='ignore'):
|
327 |
+
r = gufunc(a, b, signature=signature)
|
328 |
+
|
329 |
+
return wrap(r.astype(result_t, copy=False))
|
330 |
+
|
331 |
+
def solve(x1: Array, x2: Array, /) -> Array:
|
332 |
+
"""
|
333 |
+
Array API compatible wrapper for :py:func:`np.linalg.solve <numpy.linalg.solve>`.
|
334 |
+
|
335 |
+
See its docstring for more information.
|
336 |
+
"""
|
337 |
+
# Note: the restriction to floating-point dtypes only is different from
|
338 |
+
# np.linalg.solve.
|
339 |
+
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
|
340 |
+
raise TypeError('Only floating-point dtypes are allowed in solve')
|
341 |
+
|
342 |
+
return Array._new(_solve(x1._array, x2._array))
|
343 |
+
|
344 |
+
def svd(x: Array, /, *, full_matrices: bool = True) -> SVDResult:
|
345 |
+
"""
|
346 |
+
Array API compatible wrapper for :py:func:`np.linalg.svd <numpy.linalg.svd>`.
|
347 |
+
|
348 |
+
See its docstring for more information.
|
349 |
+
"""
|
350 |
+
# Note: the restriction to floating-point dtypes only is different from
|
351 |
+
# np.linalg.svd.
|
352 |
+
if x.dtype not in _floating_dtypes:
|
353 |
+
raise TypeError('Only floating-point dtypes are allowed in svd')
|
354 |
+
|
355 |
+
# Note: the return type here is a namedtuple, which is different from
|
356 |
+
# np.svd, which only returns a tuple.
|
357 |
+
return SVDResult(*map(Array._new, np.linalg.svd(x._array, full_matrices=full_matrices)))
|
358 |
+
|
359 |
+
# Note: svdvals is not in NumPy (but it is in SciPy). It is equivalent to
|
360 |
+
# np.linalg.svd(compute_uv=False).
|
361 |
+
def svdvals(x: Array, /) -> Union[Array, Tuple[Array, ...]]:
|
362 |
+
if x.dtype not in _floating_dtypes:
|
363 |
+
raise TypeError('Only floating-point dtypes are allowed in svdvals')
|
364 |
+
return Array._new(np.linalg.svd(x._array, compute_uv=False))
|
365 |
+
|
366 |
+
# Note: tensordot is the numpy top-level namespace but not in np.linalg
|
367 |
+
|
368 |
+
# Note: axes must be a tuple, unlike np.tensordot where it can be an array or array-like.
|
369 |
+
def tensordot(x1: Array, x2: Array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2) -> Array:
|
370 |
+
# Note: the restriction to numeric dtypes only is different from
|
371 |
+
# np.tensordot.
|
372 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
373 |
+
raise TypeError('Only numeric dtypes are allowed in tensordot')
|
374 |
+
|
375 |
+
return Array._new(np.tensordot(x1._array, x2._array, axes=axes))
|
376 |
+
|
377 |
+
# Note: trace is the numpy top-level namespace, not np.linalg
|
378 |
+
def trace(x: Array, /, *, offset: int = 0, dtype: Optional[Dtype] = None) -> Array:
|
379 |
+
"""
|
380 |
+
Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`.
|
381 |
+
|
382 |
+
See its docstring for more information.
|
383 |
+
"""
|
384 |
+
if x.dtype not in _numeric_dtypes:
|
385 |
+
raise TypeError('Only numeric dtypes are allowed in trace')
|
386 |
+
|
387 |
+
# Note: trace() works the same as sum() and prod() (see
|
388 |
+
# _statistical_functions.py)
|
389 |
+
if dtype is None:
|
390 |
+
if x.dtype == float32:
|
391 |
+
dtype = float64
|
392 |
+
elif x.dtype == complex64:
|
393 |
+
dtype = complex128
|
394 |
+
# Note: trace always operates on the last two axes, whereas np.trace
|
395 |
+
# operates on the first two axes by default
|
396 |
+
return Array._new(np.asarray(np.trace(x._array, offset=offset, axis1=-2, axis2=-1, dtype=dtype)))
|
397 |
+
|
398 |
+
# Note: vecdot is not in NumPy
|
399 |
+
def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
|
400 |
+
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
|
401 |
+
raise TypeError('Only numeric dtypes are allowed in vecdot')
|
402 |
+
ndim = max(x1.ndim, x2.ndim)
|
403 |
+
x1_shape = (1,)*(ndim - x1.ndim) + tuple(x1.shape)
|
404 |
+
x2_shape = (1,)*(ndim - x2.ndim) + tuple(x2.shape)
|
405 |
+
if x1_shape[axis] != x2_shape[axis]:
|
406 |
+
raise ValueError("x1 and x2 must have the same size along the given axis")
|
407 |
+
|
408 |
+
x1_, x2_ = np.broadcast_arrays(x1._array, x2._array)
|
409 |
+
x1_ = np.moveaxis(x1_, axis, -1)
|
410 |
+
x2_ = np.moveaxis(x2_, axis, -1)
|
411 |
+
|
412 |
+
res = x1_[..., None, :] @ x2_[..., None]
|
413 |
+
return Array._new(res[..., 0, 0])
|
414 |
+
|
415 |
+
|
416 |
+
# Note: the name here is different from norm(). The array API norm is split
|
417 |
+
# into matrix_norm and vector_norm().
|
418 |
+
|
419 |
+
# The type for ord should be Optional[Union[int, float, Literal[np.inf,
|
420 |
+
# -np.inf]]] but Literal does not support floating-point literals.
|
421 |
+
def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
|
422 |
+
"""
|
423 |
+
Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
|
424 |
+
|
425 |
+
See its docstring for more information.
|
426 |
+
"""
|
427 |
+
# Note: the restriction to floating-point dtypes only is different from
|
428 |
+
# np.linalg.norm.
|
429 |
+
if x.dtype not in _floating_dtypes:
|
430 |
+
raise TypeError('Only floating-point dtypes are allowed in norm')
|
431 |
+
|
432 |
+
# np.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
|
433 |
+
# when axis=None and the input is 2-D, so to force a vector norm, we make
|
434 |
+
# it so the input is 1-D (for axis=None), or reshape so that norm is done
|
435 |
+
# on a single dimension.
|
436 |
+
a = x._array
|
437 |
+
if axis is None:
|
438 |
+
# Note: np.linalg.norm() doesn't handle 0-D arrays
|
439 |
+
a = a.ravel()
|
440 |
+
_axis = 0
|
441 |
+
elif isinstance(axis, tuple):
|
442 |
+
# Note: The axis argument supports any number of axes, whereas
|
443 |
+
# np.linalg.norm() only supports a single axis for vector norm.
|
444 |
+
normalized_axis = normalize_axis_tuple(axis, x.ndim)
|
445 |
+
rest = tuple(i for i in range(a.ndim) if i not in normalized_axis)
|
446 |
+
newshape = axis + rest
|
447 |
+
a = np.transpose(a, newshape).reshape(
|
448 |
+
(np.prod([a.shape[i] for i in axis], dtype=int), *[a.shape[i] for i in rest]))
|
449 |
+
_axis = 0
|
450 |
+
else:
|
451 |
+
_axis = axis
|
452 |
+
|
453 |
+
res = Array._new(np.linalg.norm(a, axis=_axis, ord=ord))
|
454 |
+
|
455 |
+
if keepdims:
|
456 |
+
# We can't reuse np.linalg.norm(keepdims) because of the reshape hacks
|
457 |
+
# above to avoid matrix norm logic.
|
458 |
+
shape = list(x.shape)
|
459 |
+
_axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
|
460 |
+
for i in _axis:
|
461 |
+
shape[i] = 1
|
462 |
+
res = reshape(res, tuple(shape))
|
463 |
+
|
464 |
+
return res
|
465 |
+
|
466 |
+
__all__ = ['cholesky', 'cross', 'det', 'diagonal', 'eigh', 'eigvalsh', 'inv', 'matmul', 'matrix_norm', 'matrix_power', 'matrix_rank', 'matrix_transpose', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'svdvals', 'tensordot', 'trace', 'vecdot', 'vector_norm']
|
env-llmeval/lib/python3.10/site-packages/numpy/array_api/setup.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def configuration(parent_package="", top_path=None):
|
2 |
+
from numpy.distutils.misc_util import Configuration
|
3 |
+
|
4 |
+
config = Configuration("array_api", parent_package, top_path)
|
5 |
+
config.add_subpackage("tests")
|
6 |
+
return config
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
from numpy.distutils.core import setup
|
11 |
+
|
12 |
+
setup(configuration=configuration)
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (5.36 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__main__.cpython-310.pyc
ADDED
Binary file (229 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/__version__.cpython-310.pyc
ADDED
Binary file (223 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_isocbind.cpython-310.pyc
ADDED
Binary file (1.58 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/_src_pyf.cpython-310.pyc
ADDED
Binary file (5.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/auxfuncs.cpython-310.pyc
ADDED
Binary file (25.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/capi_maps.cpython-310.pyc
ADDED
Binary file (18.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cb_rules.cpython-310.pyc
ADDED
Binary file (18.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/cfuncs.cpython-310.pyc
ADDED
Binary file (45.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/common_rules.cpython-310.pyc
ADDED
Binary file (4.85 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-310.pyc
ADDED
Binary file (87.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/diagnose.cpython-310.pyc
ADDED
Binary file (3.83 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f2py2e.cpython-310.pyc
ADDED
Binary file (22.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/f90mod_rules.cpython-310.pyc
ADDED
Binary file (7.22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/func2subr.cpython-310.pyc
ADDED
Binary file (7.07 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/rules.cpython-310.pyc
ADDED
Binary file (38.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/setup.cpython-310.pyc
ADDED
Binary file (2.34 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/symbolic.cpython-310.pyc
ADDED
Binary file (38.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/__pycache__/use_rules.cpython-310.pyc
ADDED
Binary file (3.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def f2py_build_generator(name):
|
2 |
+
if name == "meson":
|
3 |
+
from ._meson import MesonBackend
|
4 |
+
return MesonBackend
|
5 |
+
elif name == "distutils":
|
6 |
+
from ._distutils import DistutilsBackend
|
7 |
+
return DistutilsBackend
|
8 |
+
else:
|
9 |
+
raise ValueError(f"Unknown backend: {name}")
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (495 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_distutils.cpython-310.pyc
ADDED
Binary file (2.24 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/__pycache__/_meson.cpython-310.pyc
ADDED
Binary file (7.44 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_backend.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from abc import ABC, abstractmethod
|
4 |
+
|
5 |
+
|
6 |
+
class Backend(ABC):
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
modulename,
|
10 |
+
sources,
|
11 |
+
extra_objects,
|
12 |
+
build_dir,
|
13 |
+
include_dirs,
|
14 |
+
library_dirs,
|
15 |
+
libraries,
|
16 |
+
define_macros,
|
17 |
+
undef_macros,
|
18 |
+
f2py_flags,
|
19 |
+
sysinfo_flags,
|
20 |
+
fc_flags,
|
21 |
+
flib_flags,
|
22 |
+
setup_flags,
|
23 |
+
remove_build_dir,
|
24 |
+
extra_dat,
|
25 |
+
):
|
26 |
+
self.modulename = modulename
|
27 |
+
self.sources = sources
|
28 |
+
self.extra_objects = extra_objects
|
29 |
+
self.build_dir = build_dir
|
30 |
+
self.include_dirs = include_dirs
|
31 |
+
self.library_dirs = library_dirs
|
32 |
+
self.libraries = libraries
|
33 |
+
self.define_macros = define_macros
|
34 |
+
self.undef_macros = undef_macros
|
35 |
+
self.f2py_flags = f2py_flags
|
36 |
+
self.sysinfo_flags = sysinfo_flags
|
37 |
+
self.fc_flags = fc_flags
|
38 |
+
self.flib_flags = flib_flags
|
39 |
+
self.setup_flags = setup_flags
|
40 |
+
self.remove_build_dir = remove_build_dir
|
41 |
+
self.extra_dat = extra_dat
|
42 |
+
|
43 |
+
@abstractmethod
|
44 |
+
def compile(self) -> None:
|
45 |
+
"""Compile the wrapper."""
|
46 |
+
pass
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_distutils.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ._backend import Backend
|
2 |
+
|
3 |
+
from numpy.distutils.core import setup, Extension
|
4 |
+
from numpy.distutils.system_info import get_info
|
5 |
+
from numpy.distutils.misc_util import dict_append
|
6 |
+
from numpy.exceptions import VisibleDeprecationWarning
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import shutil
|
10 |
+
import warnings
|
11 |
+
|
12 |
+
|
13 |
+
class DistutilsBackend(Backend):
|
14 |
+
def __init__(sef, *args, **kwargs):
|
15 |
+
warnings.warn(
|
16 |
+
"distutils has been deprecated since NumPy 1.26.x"
|
17 |
+
"Use the Meson backend instead, or generate wrappers"
|
18 |
+
"without -c and use a custom build script",
|
19 |
+
VisibleDeprecationWarning,
|
20 |
+
stacklevel=2,
|
21 |
+
)
|
22 |
+
super().__init__(*args, **kwargs)
|
23 |
+
|
24 |
+
def compile(self):
|
25 |
+
num_info = {}
|
26 |
+
if num_info:
|
27 |
+
self.include_dirs.extend(num_info.get("include_dirs", []))
|
28 |
+
ext_args = {
|
29 |
+
"name": self.modulename,
|
30 |
+
"sources": self.sources,
|
31 |
+
"include_dirs": self.include_dirs,
|
32 |
+
"library_dirs": self.library_dirs,
|
33 |
+
"libraries": self.libraries,
|
34 |
+
"define_macros": self.define_macros,
|
35 |
+
"undef_macros": self.undef_macros,
|
36 |
+
"extra_objects": self.extra_objects,
|
37 |
+
"f2py_options": self.f2py_flags,
|
38 |
+
}
|
39 |
+
|
40 |
+
if self.sysinfo_flags:
|
41 |
+
for n in self.sysinfo_flags:
|
42 |
+
i = get_info(n)
|
43 |
+
if not i:
|
44 |
+
print(
|
45 |
+
f"No {repr(n)} resources found"
|
46 |
+
"in system (try `f2py --help-link`)"
|
47 |
+
)
|
48 |
+
dict_append(ext_args, **i)
|
49 |
+
|
50 |
+
ext = Extension(**ext_args)
|
51 |
+
|
52 |
+
sys.argv = [sys.argv[0]] + self.setup_flags
|
53 |
+
sys.argv.extend(
|
54 |
+
[
|
55 |
+
"build",
|
56 |
+
"--build-temp",
|
57 |
+
self.build_dir,
|
58 |
+
"--build-base",
|
59 |
+
self.build_dir,
|
60 |
+
"--build-platlib",
|
61 |
+
".",
|
62 |
+
"--disable-optimization",
|
63 |
+
]
|
64 |
+
)
|
65 |
+
|
66 |
+
if self.fc_flags:
|
67 |
+
sys.argv.extend(["config_fc"] + self.fc_flags)
|
68 |
+
if self.flib_flags:
|
69 |
+
sys.argv.extend(["build_ext"] + self.flib_flags)
|
70 |
+
|
71 |
+
setup(ext_modules=[ext])
|
72 |
+
|
73 |
+
if self.remove_build_dir and os.path.exists(self.build_dir):
|
74 |
+
print(f"Removing build directory {self.build_dir}")
|
75 |
+
shutil.rmtree(self.build_dir)
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/_meson.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import os
|
4 |
+
import errno
|
5 |
+
import shutil
|
6 |
+
import subprocess
|
7 |
+
import sys
|
8 |
+
from pathlib import Path
|
9 |
+
|
10 |
+
from ._backend import Backend
|
11 |
+
from string import Template
|
12 |
+
from itertools import chain
|
13 |
+
|
14 |
+
import warnings
|
15 |
+
|
16 |
+
|
17 |
+
class MesonTemplate:
|
18 |
+
"""Template meson build file generation class."""
|
19 |
+
|
20 |
+
def __init__(
|
21 |
+
self,
|
22 |
+
modulename: str,
|
23 |
+
sources: list[Path],
|
24 |
+
deps: list[str],
|
25 |
+
libraries: list[str],
|
26 |
+
library_dirs: list[Path],
|
27 |
+
include_dirs: list[Path],
|
28 |
+
object_files: list[Path],
|
29 |
+
linker_args: list[str],
|
30 |
+
c_args: list[str],
|
31 |
+
build_type: str,
|
32 |
+
python_exe: str,
|
33 |
+
):
|
34 |
+
self.modulename = modulename
|
35 |
+
self.build_template_path = (
|
36 |
+
Path(__file__).parent.absolute() / "meson.build.template"
|
37 |
+
)
|
38 |
+
self.sources = sources
|
39 |
+
self.deps = deps
|
40 |
+
self.libraries = libraries
|
41 |
+
self.library_dirs = library_dirs
|
42 |
+
if include_dirs is not None:
|
43 |
+
self.include_dirs = include_dirs
|
44 |
+
else:
|
45 |
+
self.include_dirs = []
|
46 |
+
self.substitutions = {}
|
47 |
+
self.objects = object_files
|
48 |
+
self.pipeline = [
|
49 |
+
self.initialize_template,
|
50 |
+
self.sources_substitution,
|
51 |
+
self.deps_substitution,
|
52 |
+
self.include_substitution,
|
53 |
+
self.libraries_substitution,
|
54 |
+
]
|
55 |
+
self.build_type = build_type
|
56 |
+
self.python_exe = python_exe
|
57 |
+
|
58 |
+
def meson_build_template(self) -> str:
|
59 |
+
if not self.build_template_path.is_file():
|
60 |
+
raise FileNotFoundError(
|
61 |
+
errno.ENOENT,
|
62 |
+
"Meson build template"
|
63 |
+
f" {self.build_template_path.absolute()}"
|
64 |
+
" does not exist.",
|
65 |
+
)
|
66 |
+
return self.build_template_path.read_text()
|
67 |
+
|
68 |
+
def initialize_template(self) -> None:
|
69 |
+
self.substitutions["modulename"] = self.modulename
|
70 |
+
self.substitutions["buildtype"] = self.build_type
|
71 |
+
self.substitutions["python"] = self.python_exe
|
72 |
+
|
73 |
+
def sources_substitution(self) -> None:
|
74 |
+
indent = " " * 21
|
75 |
+
self.substitutions["source_list"] = f",\n{indent}".join(
|
76 |
+
[f"{indent}'{source}'" for source in self.sources]
|
77 |
+
)
|
78 |
+
|
79 |
+
def deps_substitution(self) -> None:
|
80 |
+
indent = " " * 21
|
81 |
+
self.substitutions["dep_list"] = f",\n{indent}".join(
|
82 |
+
[f"{indent}dependency('{dep}')" for dep in self.deps]
|
83 |
+
)
|
84 |
+
|
85 |
+
def libraries_substitution(self) -> None:
|
86 |
+
self.substitutions["lib_dir_declarations"] = "\n".join(
|
87 |
+
[
|
88 |
+
f"lib_dir_{i} = declare_dependency(link_args : ['-L{lib_dir}'])"
|
89 |
+
for i, lib_dir in enumerate(self.library_dirs)
|
90 |
+
]
|
91 |
+
)
|
92 |
+
|
93 |
+
self.substitutions["lib_declarations"] = "\n".join(
|
94 |
+
[
|
95 |
+
f"{lib} = declare_dependency(link_args : ['-l{lib}'])"
|
96 |
+
for lib in self.libraries
|
97 |
+
]
|
98 |
+
)
|
99 |
+
|
100 |
+
indent = " " * 21
|
101 |
+
self.substitutions["lib_list"] = f"\n{indent}".join(
|
102 |
+
[f"{indent}{lib}," for lib in self.libraries]
|
103 |
+
)
|
104 |
+
self.substitutions["lib_dir_list"] = f"\n{indent}".join(
|
105 |
+
[f"{indent}lib_dir_{i}," for i in range(len(self.library_dirs))]
|
106 |
+
)
|
107 |
+
|
108 |
+
def include_substitution(self) -> None:
|
109 |
+
indent = " " * 21
|
110 |
+
self.substitutions["inc_list"] = f",\n{indent}".join(
|
111 |
+
[f"{indent}'{inc}'" for inc in self.include_dirs]
|
112 |
+
)
|
113 |
+
|
114 |
+
def generate_meson_build(self):
|
115 |
+
for node in self.pipeline:
|
116 |
+
node()
|
117 |
+
template = Template(self.meson_build_template())
|
118 |
+
return template.substitute(self.substitutions)
|
119 |
+
|
120 |
+
|
121 |
+
class MesonBackend(Backend):
|
122 |
+
def __init__(self, *args, **kwargs):
|
123 |
+
super().__init__(*args, **kwargs)
|
124 |
+
self.dependencies = self.extra_dat.get("dependencies", [])
|
125 |
+
self.meson_build_dir = "bbdir"
|
126 |
+
self.build_type = (
|
127 |
+
"debug" if any("debug" in flag for flag in self.fc_flags) else "release"
|
128 |
+
)
|
129 |
+
|
130 |
+
def _move_exec_to_root(self, build_dir: Path):
|
131 |
+
walk_dir = Path(build_dir) / self.meson_build_dir
|
132 |
+
path_objects = chain(
|
133 |
+
walk_dir.glob(f"{self.modulename}*.so"),
|
134 |
+
walk_dir.glob(f"{self.modulename}*.pyd"),
|
135 |
+
)
|
136 |
+
# Same behavior as distutils
|
137 |
+
# https://github.com/numpy/numpy/issues/24874#issuecomment-1835632293
|
138 |
+
for path_object in path_objects:
|
139 |
+
dest_path = Path.cwd() / path_object.name
|
140 |
+
if dest_path.exists():
|
141 |
+
dest_path.unlink()
|
142 |
+
shutil.copy2(path_object, dest_path)
|
143 |
+
os.remove(path_object)
|
144 |
+
|
145 |
+
def write_meson_build(self, build_dir: Path) -> None:
|
146 |
+
"""Writes the meson build file at specified location"""
|
147 |
+
meson_template = MesonTemplate(
|
148 |
+
self.modulename,
|
149 |
+
self.sources,
|
150 |
+
self.dependencies,
|
151 |
+
self.libraries,
|
152 |
+
self.library_dirs,
|
153 |
+
self.include_dirs,
|
154 |
+
self.extra_objects,
|
155 |
+
self.flib_flags,
|
156 |
+
self.fc_flags,
|
157 |
+
self.build_type,
|
158 |
+
sys.executable,
|
159 |
+
)
|
160 |
+
src = meson_template.generate_meson_build()
|
161 |
+
Path(build_dir).mkdir(parents=True, exist_ok=True)
|
162 |
+
meson_build_file = Path(build_dir) / "meson.build"
|
163 |
+
meson_build_file.write_text(src)
|
164 |
+
return meson_build_file
|
165 |
+
|
166 |
+
def _run_subprocess_command(self, command, cwd):
|
167 |
+
subprocess.run(command, cwd=cwd, check=True)
|
168 |
+
|
169 |
+
def run_meson(self, build_dir: Path):
|
170 |
+
setup_command = ["meson", "setup", self.meson_build_dir]
|
171 |
+
self._run_subprocess_command(setup_command, build_dir)
|
172 |
+
compile_command = ["meson", "compile", "-C", self.meson_build_dir]
|
173 |
+
self._run_subprocess_command(compile_command, build_dir)
|
174 |
+
|
175 |
+
def compile(self) -> None:
|
176 |
+
self.sources = _prepare_sources(self.modulename, self.sources, self.build_dir)
|
177 |
+
self.write_meson_build(self.build_dir)
|
178 |
+
self.run_meson(self.build_dir)
|
179 |
+
self._move_exec_to_root(self.build_dir)
|
180 |
+
|
181 |
+
|
182 |
+
def _prepare_sources(mname, sources, bdir):
|
183 |
+
extended_sources = sources.copy()
|
184 |
+
Path(bdir).mkdir(parents=True, exist_ok=True)
|
185 |
+
# Copy sources
|
186 |
+
for source in sources:
|
187 |
+
if Path(source).exists() and Path(source).is_file():
|
188 |
+
shutil.copy(source, bdir)
|
189 |
+
generated_sources = [
|
190 |
+
Path(f"{mname}module.c"),
|
191 |
+
Path(f"{mname}-f2pywrappers2.f90"),
|
192 |
+
Path(f"{mname}-f2pywrappers.f"),
|
193 |
+
]
|
194 |
+
bdir = Path(bdir)
|
195 |
+
for generated_source in generated_sources:
|
196 |
+
if generated_source.exists():
|
197 |
+
shutil.copy(generated_source, bdir / generated_source.name)
|
198 |
+
extended_sources.append(generated_source.name)
|
199 |
+
generated_source.unlink()
|
200 |
+
extended_sources = [
|
201 |
+
Path(source).name
|
202 |
+
for source in extended_sources
|
203 |
+
if not Path(source).suffix == ".pyf"
|
204 |
+
]
|
205 |
+
return extended_sources
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/_backends/meson.build.template
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
project('${modulename}',
|
2 |
+
['c', 'fortran'],
|
3 |
+
version : '0.1',
|
4 |
+
meson_version: '>= 1.1.0',
|
5 |
+
default_options : [
|
6 |
+
'warning_level=1',
|
7 |
+
'buildtype=${buildtype}'
|
8 |
+
])
|
9 |
+
fc = meson.get_compiler('fortran')
|
10 |
+
|
11 |
+
py = import('python').find_installation('${python}', pure: false)
|
12 |
+
py_dep = py.dependency()
|
13 |
+
|
14 |
+
incdir_numpy = run_command(py,
|
15 |
+
['-c', 'import os; os.chdir(".."); import numpy; print(numpy.get_include())'],
|
16 |
+
check : true
|
17 |
+
).stdout().strip()
|
18 |
+
|
19 |
+
incdir_f2py = run_command(py,
|
20 |
+
['-c', 'import os; os.chdir(".."); import numpy.f2py; print(numpy.f2py.get_include())'],
|
21 |
+
check : true
|
22 |
+
).stdout().strip()
|
23 |
+
|
24 |
+
inc_np = include_directories(incdir_numpy)
|
25 |
+
np_dep = declare_dependency(include_directories: inc_np)
|
26 |
+
|
27 |
+
incdir_f2py = incdir_numpy / '..' / '..' / 'f2py' / 'src'
|
28 |
+
inc_f2py = include_directories(incdir_f2py)
|
29 |
+
fortranobject_c = incdir_f2py / 'fortranobject.c'
|
30 |
+
|
31 |
+
inc_np = include_directories(incdir_numpy, incdir_f2py)
|
32 |
+
# gh-25000
|
33 |
+
quadmath_dep = fc.find_library('quadmath', required: false)
|
34 |
+
|
35 |
+
${lib_declarations}
|
36 |
+
${lib_dir_declarations}
|
37 |
+
|
38 |
+
py.extension_module('${modulename}',
|
39 |
+
[
|
40 |
+
${source_list},
|
41 |
+
fortranobject_c
|
42 |
+
],
|
43 |
+
include_directories: [
|
44 |
+
inc_np,
|
45 |
+
${inc_list}
|
46 |
+
],
|
47 |
+
dependencies : [
|
48 |
+
py_dep,
|
49 |
+
quadmath_dep,
|
50 |
+
${dep_list}
|
51 |
+
${lib_list}
|
52 |
+
${lib_dir_list}
|
53 |
+
],
|
54 |
+
install : true)
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.c
ADDED
@@ -0,0 +1,1423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#define FORTRANOBJECT_C
|
2 |
+
#include "fortranobject.h"
|
3 |
+
|
4 |
+
#ifdef __cplusplus
|
5 |
+
extern "C" {
|
6 |
+
#endif
|
7 |
+
|
8 |
+
#include <stdarg.h>
|
9 |
+
#include <stdlib.h>
|
10 |
+
#include <string.h>
|
11 |
+
|
12 |
+
/*
|
13 |
+
This file implements: FortranObject, array_from_pyobj, copy_ND_array
|
14 |
+
|
15 |
+
Author: Pearu Peterson <[email protected]>
|
16 |
+
$Revision: 1.52 $
|
17 |
+
$Date: 2005/07/11 07:44:20 $
|
18 |
+
*/
|
19 |
+
|
20 |
+
int
|
21 |
+
F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj)
|
22 |
+
{
|
23 |
+
if (obj == NULL) {
|
24 |
+
fprintf(stderr, "Error loading %s\n", name);
|
25 |
+
if (PyErr_Occurred()) {
|
26 |
+
PyErr_Print();
|
27 |
+
PyErr_Clear();
|
28 |
+
}
|
29 |
+
return -1;
|
30 |
+
}
|
31 |
+
return PyDict_SetItemString(dict, name, obj);
|
32 |
+
}
|
33 |
+
|
34 |
+
/*
|
35 |
+
* Python-only fallback for thread-local callback pointers
|
36 |
+
*/
|
37 |
+
void *
|
38 |
+
F2PySwapThreadLocalCallbackPtr(char *key, void *ptr)
|
39 |
+
{
|
40 |
+
PyObject *local_dict, *value;
|
41 |
+
void *prev;
|
42 |
+
|
43 |
+
local_dict = PyThreadState_GetDict();
|
44 |
+
if (local_dict == NULL) {
|
45 |
+
Py_FatalError(
|
46 |
+
"F2PySwapThreadLocalCallbackPtr: PyThreadState_GetDict "
|
47 |
+
"failed");
|
48 |
+
}
|
49 |
+
|
50 |
+
value = PyDict_GetItemString(local_dict, key);
|
51 |
+
if (value != NULL) {
|
52 |
+
prev = PyLong_AsVoidPtr(value);
|
53 |
+
if (PyErr_Occurred()) {
|
54 |
+
Py_FatalError(
|
55 |
+
"F2PySwapThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
|
56 |
+
}
|
57 |
+
}
|
58 |
+
else {
|
59 |
+
prev = NULL;
|
60 |
+
}
|
61 |
+
|
62 |
+
value = PyLong_FromVoidPtr((void *)ptr);
|
63 |
+
if (value == NULL) {
|
64 |
+
Py_FatalError(
|
65 |
+
"F2PySwapThreadLocalCallbackPtr: PyLong_FromVoidPtr failed");
|
66 |
+
}
|
67 |
+
|
68 |
+
if (PyDict_SetItemString(local_dict, key, value) != 0) {
|
69 |
+
Py_FatalError(
|
70 |
+
"F2PySwapThreadLocalCallbackPtr: PyDict_SetItemString failed");
|
71 |
+
}
|
72 |
+
|
73 |
+
Py_DECREF(value);
|
74 |
+
|
75 |
+
return prev;
|
76 |
+
}
|
77 |
+
|
78 |
+
void *
|
79 |
+
F2PyGetThreadLocalCallbackPtr(char *key)
|
80 |
+
{
|
81 |
+
PyObject *local_dict, *value;
|
82 |
+
void *prev;
|
83 |
+
|
84 |
+
local_dict = PyThreadState_GetDict();
|
85 |
+
if (local_dict == NULL) {
|
86 |
+
Py_FatalError(
|
87 |
+
"F2PyGetThreadLocalCallbackPtr: PyThreadState_GetDict failed");
|
88 |
+
}
|
89 |
+
|
90 |
+
value = PyDict_GetItemString(local_dict, key);
|
91 |
+
if (value != NULL) {
|
92 |
+
prev = PyLong_AsVoidPtr(value);
|
93 |
+
if (PyErr_Occurred()) {
|
94 |
+
Py_FatalError(
|
95 |
+
"F2PyGetThreadLocalCallbackPtr: PyLong_AsVoidPtr failed");
|
96 |
+
}
|
97 |
+
}
|
98 |
+
else {
|
99 |
+
prev = NULL;
|
100 |
+
}
|
101 |
+
|
102 |
+
return prev;
|
103 |
+
}
|
104 |
+
|
105 |
+
static PyArray_Descr *
|
106 |
+
get_descr_from_type_and_elsize(const int type_num, const int elsize) {
|
107 |
+
PyArray_Descr * descr = PyArray_DescrFromType(type_num);
|
108 |
+
if (type_num == NPY_STRING) {
|
109 |
+
// PyArray_DescrFromType returns descr with elsize = 0.
|
110 |
+
PyArray_DESCR_REPLACE(descr);
|
111 |
+
if (descr == NULL) {
|
112 |
+
return NULL;
|
113 |
+
}
|
114 |
+
descr->elsize = elsize;
|
115 |
+
}
|
116 |
+
return descr;
|
117 |
+
}
|
118 |
+
|
119 |
+
/************************* FortranObject *******************************/
|
120 |
+
|
121 |
+
typedef PyObject *(*fortranfunc)(PyObject *, PyObject *, PyObject *, void *);
|
122 |
+
|
123 |
+
PyObject *
|
124 |
+
PyFortranObject_New(FortranDataDef *defs, f2py_void_func init)
|
125 |
+
{
|
126 |
+
int i;
|
127 |
+
PyFortranObject *fp = NULL;
|
128 |
+
PyObject *v = NULL;
|
129 |
+
if (init != NULL) { /* Initialize F90 module objects */
|
130 |
+
(*(init))();
|
131 |
+
}
|
132 |
+
fp = PyObject_New(PyFortranObject, &PyFortran_Type);
|
133 |
+
if (fp == NULL) {
|
134 |
+
return NULL;
|
135 |
+
}
|
136 |
+
if ((fp->dict = PyDict_New()) == NULL) {
|
137 |
+
Py_DECREF(fp);
|
138 |
+
return NULL;
|
139 |
+
}
|
140 |
+
fp->len = 0;
|
141 |
+
while (defs[fp->len].name != NULL) {
|
142 |
+
fp->len++;
|
143 |
+
}
|
144 |
+
if (fp->len == 0) {
|
145 |
+
goto fail;
|
146 |
+
}
|
147 |
+
fp->defs = defs;
|
148 |
+
for (i = 0; i < fp->len; i++) {
|
149 |
+
if (fp->defs[i].rank == -1) { /* Is Fortran routine */
|
150 |
+
v = PyFortranObject_NewAsAttr(&(fp->defs[i]));
|
151 |
+
if (v == NULL) {
|
152 |
+
goto fail;
|
153 |
+
}
|
154 |
+
PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
|
155 |
+
Py_XDECREF(v);
|
156 |
+
}
|
157 |
+
else if ((fp->defs[i].data) !=
|
158 |
+
NULL) { /* Is Fortran variable or array (not allocatable) */
|
159 |
+
PyArray_Descr *
|
160 |
+
descr = get_descr_from_type_and_elsize(fp->defs[i].type,
|
161 |
+
fp->defs[i].elsize);
|
162 |
+
if (descr == NULL) {
|
163 |
+
goto fail;
|
164 |
+
}
|
165 |
+
v = PyArray_NewFromDescr(&PyArray_Type, descr, fp->defs[i].rank,
|
166 |
+
fp->defs[i].dims.d, NULL, fp->defs[i].data,
|
167 |
+
NPY_ARRAY_FARRAY, NULL);
|
168 |
+
if (v == NULL) {
|
169 |
+
Py_DECREF(descr);
|
170 |
+
goto fail;
|
171 |
+
}
|
172 |
+
PyDict_SetItemString(fp->dict, fp->defs[i].name, v);
|
173 |
+
Py_XDECREF(v);
|
174 |
+
}
|
175 |
+
}
|
176 |
+
return (PyObject *)fp;
|
177 |
+
fail:
|
178 |
+
Py_XDECREF(fp);
|
179 |
+
return NULL;
|
180 |
+
}
|
181 |
+
|
182 |
+
PyObject *
|
183 |
+
PyFortranObject_NewAsAttr(FortranDataDef *defs)
|
184 |
+
{ /* used for calling F90 module routines */
|
185 |
+
PyFortranObject *fp = NULL;
|
186 |
+
fp = PyObject_New(PyFortranObject, &PyFortran_Type);
|
187 |
+
if (fp == NULL)
|
188 |
+
return NULL;
|
189 |
+
if ((fp->dict = PyDict_New()) == NULL) {
|
190 |
+
PyObject_Del(fp);
|
191 |
+
return NULL;
|
192 |
+
}
|
193 |
+
fp->len = 1;
|
194 |
+
fp->defs = defs;
|
195 |
+
if (defs->rank == -1) {
|
196 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("function %s", defs->name));
|
197 |
+
} else if (defs->rank == 0) {
|
198 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("scalar %s", defs->name));
|
199 |
+
} else {
|
200 |
+
PyDict_SetItemString(fp->dict, "__name__", PyUnicode_FromFormat("array %s", defs->name));
|
201 |
+
}
|
202 |
+
return (PyObject *)fp;
|
203 |
+
}
|
204 |
+
|
205 |
+
/* Fortran methods */
|
206 |
+
|
207 |
+
static void
|
208 |
+
fortran_dealloc(PyFortranObject *fp)
|
209 |
+
{
|
210 |
+
Py_XDECREF(fp->dict);
|
211 |
+
PyObject_Del(fp);
|
212 |
+
}
|
213 |
+
|
214 |
+
/* Returns number of bytes consumed from buf, or -1 on error. */
|
215 |
+
static Py_ssize_t
|
216 |
+
format_def(char *buf, Py_ssize_t size, FortranDataDef def)
|
217 |
+
{
|
218 |
+
char *p = buf;
|
219 |
+
int i;
|
220 |
+
npy_intp n;
|
221 |
+
|
222 |
+
n = PyOS_snprintf(p, size, "array(%" NPY_INTP_FMT, def.dims.d[0]);
|
223 |
+
if (n < 0 || n >= size) {
|
224 |
+
return -1;
|
225 |
+
}
|
226 |
+
p += n;
|
227 |
+
size -= n;
|
228 |
+
|
229 |
+
for (i = 1; i < def.rank; i++) {
|
230 |
+
n = PyOS_snprintf(p, size, ",%" NPY_INTP_FMT, def.dims.d[i]);
|
231 |
+
if (n < 0 || n >= size) {
|
232 |
+
return -1;
|
233 |
+
}
|
234 |
+
p += n;
|
235 |
+
size -= n;
|
236 |
+
}
|
237 |
+
|
238 |
+
if (size <= 0) {
|
239 |
+
return -1;
|
240 |
+
}
|
241 |
+
|
242 |
+
*p++ = ')';
|
243 |
+
size--;
|
244 |
+
|
245 |
+
if (def.data == NULL) {
|
246 |
+
static const char notalloc[] = ", not allocated";
|
247 |
+
if ((size_t)size < sizeof(notalloc)) {
|
248 |
+
return -1;
|
249 |
+
}
|
250 |
+
memcpy(p, notalloc, sizeof(notalloc));
|
251 |
+
p += sizeof(notalloc);
|
252 |
+
size -= sizeof(notalloc);
|
253 |
+
}
|
254 |
+
|
255 |
+
return p - buf;
|
256 |
+
}
|
257 |
+
|
258 |
+
static PyObject *
|
259 |
+
fortran_doc(FortranDataDef def)
|
260 |
+
{
|
261 |
+
char *buf, *p;
|
262 |
+
PyObject *s = NULL;
|
263 |
+
Py_ssize_t n, origsize, size = 100;
|
264 |
+
|
265 |
+
if (def.doc != NULL) {
|
266 |
+
size += strlen(def.doc);
|
267 |
+
}
|
268 |
+
origsize = size;
|
269 |
+
buf = p = (char *)PyMem_Malloc(size);
|
270 |
+
if (buf == NULL) {
|
271 |
+
return PyErr_NoMemory();
|
272 |
+
}
|
273 |
+
|
274 |
+
if (def.rank == -1) {
|
275 |
+
if (def.doc) {
|
276 |
+
n = strlen(def.doc);
|
277 |
+
if (n > size) {
|
278 |
+
goto fail;
|
279 |
+
}
|
280 |
+
memcpy(p, def.doc, n);
|
281 |
+
p += n;
|
282 |
+
size -= n;
|
283 |
+
}
|
284 |
+
else {
|
285 |
+
n = PyOS_snprintf(p, size, "%s - no docs available", def.name);
|
286 |
+
if (n < 0 || n >= size) {
|
287 |
+
goto fail;
|
288 |
+
}
|
289 |
+
p += n;
|
290 |
+
size -= n;
|
291 |
+
}
|
292 |
+
}
|
293 |
+
else {
|
294 |
+
PyArray_Descr *d = PyArray_DescrFromType(def.type);
|
295 |
+
n = PyOS_snprintf(p, size, "%s : '%c'-", def.name, d->type);
|
296 |
+
Py_DECREF(d);
|
297 |
+
if (n < 0 || n >= size) {
|
298 |
+
goto fail;
|
299 |
+
}
|
300 |
+
p += n;
|
301 |
+
size -= n;
|
302 |
+
|
303 |
+
if (def.data == NULL) {
|
304 |
+
n = format_def(p, size, def);
|
305 |
+
if (n < 0) {
|
306 |
+
goto fail;
|
307 |
+
}
|
308 |
+
p += n;
|
309 |
+
size -= n;
|
310 |
+
}
|
311 |
+
else if (def.rank > 0) {
|
312 |
+
n = format_def(p, size, def);
|
313 |
+
if (n < 0) {
|
314 |
+
goto fail;
|
315 |
+
}
|
316 |
+
p += n;
|
317 |
+
size -= n;
|
318 |
+
}
|
319 |
+
else {
|
320 |
+
n = strlen("scalar");
|
321 |
+
if (size < n) {
|
322 |
+
goto fail;
|
323 |
+
}
|
324 |
+
memcpy(p, "scalar", n);
|
325 |
+
p += n;
|
326 |
+
size -= n;
|
327 |
+
}
|
328 |
+
}
|
329 |
+
if (size <= 1) {
|
330 |
+
goto fail;
|
331 |
+
}
|
332 |
+
*p++ = '\n';
|
333 |
+
size--;
|
334 |
+
|
335 |
+
/* p now points one beyond the last character of the string in buf */
|
336 |
+
s = PyUnicode_FromStringAndSize(buf, p - buf);
|
337 |
+
|
338 |
+
PyMem_Free(buf);
|
339 |
+
return s;
|
340 |
+
|
341 |
+
fail:
|
342 |
+
fprintf(stderr,
|
343 |
+
"fortranobject.c: fortran_doc: len(p)=%zd>%zd=size:"
|
344 |
+
" too long docstring required, increase size\n",
|
345 |
+
p - buf, origsize);
|
346 |
+
PyMem_Free(buf);
|
347 |
+
return NULL;
|
348 |
+
}
|
349 |
+
|
350 |
+
static FortranDataDef *save_def; /* save pointer of an allocatable array */
|
351 |
+
static void
|
352 |
+
set_data(char *d, npy_intp *f)
|
353 |
+
{ /* callback from Fortran */
|
354 |
+
if (*f) /* In fortran f=allocated(d) */
|
355 |
+
save_def->data = d;
|
356 |
+
else
|
357 |
+
save_def->data = NULL;
|
358 |
+
/* printf("set_data: d=%p,f=%d\n",d,*f); */
|
359 |
+
}
|
360 |
+
|
361 |
+
static PyObject *
|
362 |
+
fortran_getattr(PyFortranObject *fp, char *name)
|
363 |
+
{
|
364 |
+
int i, j, k, flag;
|
365 |
+
if (fp->dict != NULL) {
|
366 |
+
PyObject *v = _PyDict_GetItemStringWithError(fp->dict, name);
|
367 |
+
if (v == NULL && PyErr_Occurred()) {
|
368 |
+
return NULL;
|
369 |
+
}
|
370 |
+
else if (v != NULL) {
|
371 |
+
Py_INCREF(v);
|
372 |
+
return v;
|
373 |
+
}
|
374 |
+
}
|
375 |
+
for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
|
376 |
+
i++)
|
377 |
+
;
|
378 |
+
if (j == 0)
|
379 |
+
if (fp->defs[i].rank != -1) { /* F90 allocatable array */
|
380 |
+
if (fp->defs[i].func == NULL)
|
381 |
+
return NULL;
|
382 |
+
for (k = 0; k < fp->defs[i].rank; ++k) fp->defs[i].dims.d[k] = -1;
|
383 |
+
save_def = &fp->defs[i];
|
384 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, fp->defs[i].dims.d,
|
385 |
+
set_data, &flag);
|
386 |
+
if (flag == 2)
|
387 |
+
k = fp->defs[i].rank + 1;
|
388 |
+
else
|
389 |
+
k = fp->defs[i].rank;
|
390 |
+
if (fp->defs[i].data != NULL) { /* array is allocated */
|
391 |
+
PyObject *v = PyArray_New(
|
392 |
+
&PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type,
|
393 |
+
NULL, fp->defs[i].data, 0, NPY_ARRAY_FARRAY, NULL);
|
394 |
+
if (v == NULL)
|
395 |
+
return NULL;
|
396 |
+
/* Py_INCREF(v); */
|
397 |
+
return v;
|
398 |
+
}
|
399 |
+
else { /* array is not allocated */
|
400 |
+
Py_RETURN_NONE;
|
401 |
+
}
|
402 |
+
}
|
403 |
+
if (strcmp(name, "__dict__") == 0) {
|
404 |
+
Py_INCREF(fp->dict);
|
405 |
+
return fp->dict;
|
406 |
+
}
|
407 |
+
if (strcmp(name, "__doc__") == 0) {
|
408 |
+
PyObject *s = PyUnicode_FromString(""), *s2, *s3;
|
409 |
+
for (i = 0; i < fp->len; i++) {
|
410 |
+
s2 = fortran_doc(fp->defs[i]);
|
411 |
+
s3 = PyUnicode_Concat(s, s2);
|
412 |
+
Py_DECREF(s2);
|
413 |
+
Py_DECREF(s);
|
414 |
+
s = s3;
|
415 |
+
}
|
416 |
+
if (PyDict_SetItemString(fp->dict, name, s))
|
417 |
+
return NULL;
|
418 |
+
return s;
|
419 |
+
}
|
420 |
+
if ((strcmp(name, "_cpointer") == 0) && (fp->len == 1)) {
|
421 |
+
PyObject *cobj =
|
422 |
+
F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data), NULL);
|
423 |
+
if (PyDict_SetItemString(fp->dict, name, cobj))
|
424 |
+
return NULL;
|
425 |
+
return cobj;
|
426 |
+
}
|
427 |
+
PyObject *str, *ret;
|
428 |
+
str = PyUnicode_FromString(name);
|
429 |
+
ret = PyObject_GenericGetAttr((PyObject *)fp, str);
|
430 |
+
Py_DECREF(str);
|
431 |
+
return ret;
|
432 |
+
}
|
433 |
+
|
434 |
+
static int
|
435 |
+
fortran_setattr(PyFortranObject *fp, char *name, PyObject *v)
|
436 |
+
{
|
437 |
+
int i, j, flag;
|
438 |
+
PyArrayObject *arr = NULL;
|
439 |
+
for (i = 0, j = 1; i < fp->len && (j = strcmp(name, fp->defs[i].name));
|
440 |
+
i++)
|
441 |
+
;
|
442 |
+
if (j == 0) {
|
443 |
+
if (fp->defs[i].rank == -1) {
|
444 |
+
PyErr_SetString(PyExc_AttributeError,
|
445 |
+
"over-writing fortran routine");
|
446 |
+
return -1;
|
447 |
+
}
|
448 |
+
if (fp->defs[i].func != NULL) { /* is allocatable array */
|
449 |
+
npy_intp dims[F2PY_MAX_DIMS];
|
450 |
+
int k;
|
451 |
+
save_def = &fp->defs[i];
|
452 |
+
if (v != Py_None) { /* set new value (reallocate if needed --
|
453 |
+
see f2py generated code for more
|
454 |
+
details ) */
|
455 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
|
456 |
+
if ((arr = array_from_pyobj(fp->defs[i].type, dims,
|
457 |
+
fp->defs[i].rank, F2PY_INTENT_IN,
|
458 |
+
v)) == NULL)
|
459 |
+
return -1;
|
460 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, PyArray_DIMS(arr),
|
461 |
+
set_data, &flag);
|
462 |
+
}
|
463 |
+
else { /* deallocate */
|
464 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = 0;
|
465 |
+
(*(fp->defs[i].func))(&fp->defs[i].rank, dims, set_data,
|
466 |
+
&flag);
|
467 |
+
for (k = 0; k < fp->defs[i].rank; k++) dims[k] = -1;
|
468 |
+
}
|
469 |
+
memcpy(fp->defs[i].dims.d, dims,
|
470 |
+
fp->defs[i].rank * sizeof(npy_intp));
|
471 |
+
}
|
472 |
+
else { /* not allocatable array */
|
473 |
+
if ((arr = array_from_pyobj(fp->defs[i].type, fp->defs[i].dims.d,
|
474 |
+
fp->defs[i].rank, F2PY_INTENT_IN,
|
475 |
+
v)) == NULL)
|
476 |
+
return -1;
|
477 |
+
}
|
478 |
+
if (fp->defs[i].data !=
|
479 |
+
NULL) { /* copy Python object to Fortran array */
|
480 |
+
npy_intp s = PyArray_MultiplyList(fp->defs[i].dims.d,
|
481 |
+
PyArray_NDIM(arr));
|
482 |
+
if (s == -1)
|
483 |
+
s = PyArray_MultiplyList(PyArray_DIMS(arr), PyArray_NDIM(arr));
|
484 |
+
if (s < 0 || (memcpy(fp->defs[i].data, PyArray_DATA(arr),
|
485 |
+
s * PyArray_ITEMSIZE(arr))) == NULL) {
|
486 |
+
if ((PyObject *)arr != v) {
|
487 |
+
Py_DECREF(arr);
|
488 |
+
}
|
489 |
+
return -1;
|
490 |
+
}
|
491 |
+
if ((PyObject *)arr != v) {
|
492 |
+
Py_DECREF(arr);
|
493 |
+
}
|
494 |
+
}
|
495 |
+
else
|
496 |
+
return (fp->defs[i].func == NULL ? -1 : 0);
|
497 |
+
return 0; /* successful */
|
498 |
+
}
|
499 |
+
if (fp->dict == NULL) {
|
500 |
+
fp->dict = PyDict_New();
|
501 |
+
if (fp->dict == NULL)
|
502 |
+
return -1;
|
503 |
+
}
|
504 |
+
if (v == NULL) {
|
505 |
+
int rv = PyDict_DelItemString(fp->dict, name);
|
506 |
+
if (rv < 0)
|
507 |
+
PyErr_SetString(PyExc_AttributeError,
|
508 |
+
"delete non-existing fortran attribute");
|
509 |
+
return rv;
|
510 |
+
}
|
511 |
+
else
|
512 |
+
return PyDict_SetItemString(fp->dict, name, v);
|
513 |
+
}
|
514 |
+
|
515 |
+
static PyObject *
|
516 |
+
fortran_call(PyFortranObject *fp, PyObject *arg, PyObject *kw)
|
517 |
+
{
|
518 |
+
int i = 0;
|
519 |
+
/* printf("fortran call
|
520 |
+
name=%s,func=%p,data=%p,%p\n",fp->defs[i].name,
|
521 |
+
fp->defs[i].func,fp->defs[i].data,&fp->defs[i].data); */
|
522 |
+
if (fp->defs[i].rank == -1) { /* is Fortran routine */
|
523 |
+
if (fp->defs[i].func == NULL) {
|
524 |
+
PyErr_Format(PyExc_RuntimeError, "no function to call");
|
525 |
+
return NULL;
|
526 |
+
}
|
527 |
+
else if (fp->defs[i].data == NULL)
|
528 |
+
/* dummy routine */
|
529 |
+
return (*((fortranfunc)(fp->defs[i].func)))((PyObject *)fp, arg,
|
530 |
+
kw, NULL);
|
531 |
+
else
|
532 |
+
return (*((fortranfunc)(fp->defs[i].func)))(
|
533 |
+
(PyObject *)fp, arg, kw, (void *)fp->defs[i].data);
|
534 |
+
}
|
535 |
+
PyErr_Format(PyExc_TypeError, "this fortran object is not callable");
|
536 |
+
return NULL;
|
537 |
+
}
|
538 |
+
|
539 |
+
static PyObject *
|
540 |
+
fortran_repr(PyFortranObject *fp)
|
541 |
+
{
|
542 |
+
PyObject *name = NULL, *repr = NULL;
|
543 |
+
name = PyObject_GetAttrString((PyObject *)fp, "__name__");
|
544 |
+
PyErr_Clear();
|
545 |
+
if (name != NULL && PyUnicode_Check(name)) {
|
546 |
+
repr = PyUnicode_FromFormat("<fortran %U>", name);
|
547 |
+
}
|
548 |
+
else {
|
549 |
+
repr = PyUnicode_FromString("<fortran object>");
|
550 |
+
}
|
551 |
+
Py_XDECREF(name);
|
552 |
+
return repr;
|
553 |
+
}
|
554 |
+
|
555 |
+
PyTypeObject PyFortran_Type = {
|
556 |
+
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "fortran",
|
557 |
+
.tp_basicsize = sizeof(PyFortranObject),
|
558 |
+
.tp_dealloc = (destructor)fortran_dealloc,
|
559 |
+
.tp_getattr = (getattrfunc)fortran_getattr,
|
560 |
+
.tp_setattr = (setattrfunc)fortran_setattr,
|
561 |
+
.tp_repr = (reprfunc)fortran_repr,
|
562 |
+
.tp_call = (ternaryfunc)fortran_call,
|
563 |
+
};
|
564 |
+
|
565 |
+
/************************* f2py_report_atexit *******************************/
|
566 |
+
|
567 |
+
#ifdef F2PY_REPORT_ATEXIT
|
568 |
+
static int passed_time = 0;
|
569 |
+
static int passed_counter = 0;
|
570 |
+
static int passed_call_time = 0;
|
571 |
+
static struct timeb start_time;
|
572 |
+
static struct timeb stop_time;
|
573 |
+
static struct timeb start_call_time;
|
574 |
+
static struct timeb stop_call_time;
|
575 |
+
static int cb_passed_time = 0;
|
576 |
+
static int cb_passed_counter = 0;
|
577 |
+
static int cb_passed_call_time = 0;
|
578 |
+
static struct timeb cb_start_time;
|
579 |
+
static struct timeb cb_stop_time;
|
580 |
+
static struct timeb cb_start_call_time;
|
581 |
+
static struct timeb cb_stop_call_time;
|
582 |
+
|
583 |
+
extern void
|
584 |
+
f2py_start_clock(void)
|
585 |
+
{
|
586 |
+
ftime(&start_time);
|
587 |
+
}
|
588 |
+
extern void
|
589 |
+
f2py_start_call_clock(void)
|
590 |
+
{
|
591 |
+
f2py_stop_clock();
|
592 |
+
ftime(&start_call_time);
|
593 |
+
}
|
594 |
+
extern void
|
595 |
+
f2py_stop_clock(void)
|
596 |
+
{
|
597 |
+
ftime(&stop_time);
|
598 |
+
passed_time += 1000 * (stop_time.time - start_time.time);
|
599 |
+
passed_time += stop_time.millitm - start_time.millitm;
|
600 |
+
}
|
601 |
+
extern void
|
602 |
+
f2py_stop_call_clock(void)
|
603 |
+
{
|
604 |
+
ftime(&stop_call_time);
|
605 |
+
passed_call_time += 1000 * (stop_call_time.time - start_call_time.time);
|
606 |
+
passed_call_time += stop_call_time.millitm - start_call_time.millitm;
|
607 |
+
passed_counter += 1;
|
608 |
+
f2py_start_clock();
|
609 |
+
}
|
610 |
+
|
611 |
+
extern void
|
612 |
+
f2py_cb_start_clock(void)
|
613 |
+
{
|
614 |
+
ftime(&cb_start_time);
|
615 |
+
}
|
616 |
+
extern void
|
617 |
+
f2py_cb_start_call_clock(void)
|
618 |
+
{
|
619 |
+
f2py_cb_stop_clock();
|
620 |
+
ftime(&cb_start_call_time);
|
621 |
+
}
|
622 |
+
extern void
|
623 |
+
f2py_cb_stop_clock(void)
|
624 |
+
{
|
625 |
+
ftime(&cb_stop_time);
|
626 |
+
cb_passed_time += 1000 * (cb_stop_time.time - cb_start_time.time);
|
627 |
+
cb_passed_time += cb_stop_time.millitm - cb_start_time.millitm;
|
628 |
+
}
|
629 |
+
extern void
|
630 |
+
f2py_cb_stop_call_clock(void)
|
631 |
+
{
|
632 |
+
ftime(&cb_stop_call_time);
|
633 |
+
cb_passed_call_time +=
|
634 |
+
1000 * (cb_stop_call_time.time - cb_start_call_time.time);
|
635 |
+
cb_passed_call_time +=
|
636 |
+
cb_stop_call_time.millitm - cb_start_call_time.millitm;
|
637 |
+
cb_passed_counter += 1;
|
638 |
+
f2py_cb_start_clock();
|
639 |
+
}
|
640 |
+
|
641 |
+
static int f2py_report_on_exit_been_here = 0;
|
642 |
+
extern void
|
643 |
+
f2py_report_on_exit(int exit_flag, void *name)
|
644 |
+
{
|
645 |
+
if (f2py_report_on_exit_been_here) {
|
646 |
+
fprintf(stderr, " %s\n", (char *)name);
|
647 |
+
return;
|
648 |
+
}
|
649 |
+
f2py_report_on_exit_been_here = 1;
|
650 |
+
fprintf(stderr, " /-----------------------\\\n");
|
651 |
+
fprintf(stderr, " < F2PY performance report >\n");
|
652 |
+
fprintf(stderr, " \\-----------------------/\n");
|
653 |
+
fprintf(stderr, "Overall time spent in ...\n");
|
654 |
+
fprintf(stderr, "(a) wrapped (Fortran/C) functions : %8d msec\n",
|
655 |
+
passed_call_time);
|
656 |
+
fprintf(stderr, "(b) f2py interface, %6d calls : %8d msec\n",
|
657 |
+
passed_counter, passed_time);
|
658 |
+
fprintf(stderr, "(c) call-back (Python) functions : %8d msec\n",
|
659 |
+
cb_passed_call_time);
|
660 |
+
fprintf(stderr, "(d) f2py call-back interface, %6d calls : %8d msec\n",
|
661 |
+
cb_passed_counter, cb_passed_time);
|
662 |
+
|
663 |
+
fprintf(stderr,
|
664 |
+
"(e) wrapped (Fortran/C) functions (actual) : %8d msec\n\n",
|
665 |
+
passed_call_time - cb_passed_call_time - cb_passed_time);
|
666 |
+
fprintf(stderr,
|
667 |
+
"Use -DF2PY_REPORT_ATEXIT_DISABLE to disable this message.\n");
|
668 |
+
fprintf(stderr, "Exit status: %d\n", exit_flag);
|
669 |
+
fprintf(stderr, "Modules : %s\n", (char *)name);
|
670 |
+
}
|
671 |
+
#endif
|
672 |
+
|
673 |
+
/********************** report on array copy ****************************/
|
674 |
+
|
675 |
+
#ifdef F2PY_REPORT_ON_ARRAY_COPY
|
676 |
+
static void
|
677 |
+
f2py_report_on_array_copy(PyArrayObject *arr)
|
678 |
+
{
|
679 |
+
const npy_intp arr_size = PyArray_Size((PyObject *)arr);
|
680 |
+
if (arr_size > F2PY_REPORT_ON_ARRAY_COPY) {
|
681 |
+
fprintf(stderr,
|
682 |
+
"copied an array: size=%ld, elsize=%" NPY_INTP_FMT "\n",
|
683 |
+
arr_size, (npy_intp)PyArray_ITEMSIZE(arr));
|
684 |
+
}
|
685 |
+
}
|
686 |
+
static void
|
687 |
+
f2py_report_on_array_copy_fromany(void)
|
688 |
+
{
|
689 |
+
fprintf(stderr, "created an array from object\n");
|
690 |
+
}
|
691 |
+
|
692 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR \
|
693 |
+
f2py_report_on_array_copy((PyArrayObject *)arr)
|
694 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY f2py_report_on_array_copy_fromany()
|
695 |
+
#else
|
696 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMARR
|
697 |
+
#define F2PY_REPORT_ON_ARRAY_COPY_FROMANY
|
698 |
+
#endif
|
699 |
+
|
700 |
+
/************************* array_from_obj *******************************/
|
701 |
+
|
702 |
+
/*
|
703 |
+
* File: array_from_pyobj.c
|
704 |
+
*
|
705 |
+
* Description:
|
706 |
+
* ------------
|
707 |
+
* Provides array_from_pyobj function that returns a contiguous array
|
708 |
+
* object with the given dimensions and required storage order, either
|
709 |
+
* in row-major (C) or column-major (Fortran) order. The function
|
710 |
+
* array_from_pyobj is very flexible about its Python object argument
|
711 |
+
* that can be any number, list, tuple, or array.
|
712 |
+
*
|
713 |
+
* array_from_pyobj is used in f2py generated Python extension
|
714 |
+
* modules.
|
715 |
+
*
|
716 |
+
* Author: Pearu Peterson <[email protected]>
|
717 |
+
* Created: 13-16 January 2002
|
718 |
+
* $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $
|
719 |
+
*/
|
720 |
+
|
721 |
+
static int check_and_fix_dimensions(const PyArrayObject* arr,
|
722 |
+
const int rank,
|
723 |
+
npy_intp *dims,
|
724 |
+
const char *errmess);
|
725 |
+
|
726 |
+
static int
|
727 |
+
find_first_negative_dimension(const int rank, const npy_intp *dims)
|
728 |
+
{
|
729 |
+
int i;
|
730 |
+
for (i = 0; i < rank; ++i) {
|
731 |
+
if (dims[i] < 0) {
|
732 |
+
return i;
|
733 |
+
}
|
734 |
+
}
|
735 |
+
return -1;
|
736 |
+
}
|
737 |
+
|
738 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
739 |
+
void
|
740 |
+
dump_dims(int rank, npy_intp const *dims)
|
741 |
+
{
|
742 |
+
int i;
|
743 |
+
printf("[");
|
744 |
+
for (i = 0; i < rank; ++i) {
|
745 |
+
printf("%3" NPY_INTP_FMT, dims[i]);
|
746 |
+
}
|
747 |
+
printf("]\n");
|
748 |
+
}
|
749 |
+
void
|
750 |
+
dump_attrs(const PyArrayObject *obj)
|
751 |
+
{
|
752 |
+
const PyArrayObject_fields *arr = (const PyArrayObject_fields *)obj;
|
753 |
+
int rank = PyArray_NDIM(arr);
|
754 |
+
npy_intp size = PyArray_Size((PyObject *)arr);
|
755 |
+
printf("\trank = %d, flags = %d, size = %" NPY_INTP_FMT "\n", rank,
|
756 |
+
arr->flags, size);
|
757 |
+
printf("\tstrides = ");
|
758 |
+
dump_dims(rank, arr->strides);
|
759 |
+
printf("\tdimensions = ");
|
760 |
+
dump_dims(rank, arr->dimensions);
|
761 |
+
}
|
762 |
+
#endif
|
763 |
+
|
764 |
+
#define SWAPTYPE(a, b, t) \
|
765 |
+
{ \
|
766 |
+
t c; \
|
767 |
+
c = (a); \
|
768 |
+
(a) = (b); \
|
769 |
+
(b) = c; \
|
770 |
+
}
|
771 |
+
|
772 |
+
static int
|
773 |
+
swap_arrays(PyArrayObject *obj1, PyArrayObject *obj2)
|
774 |
+
{
|
775 |
+
PyArrayObject_fields *arr1 = (PyArrayObject_fields *)obj1,
|
776 |
+
*arr2 = (PyArrayObject_fields *)obj2;
|
777 |
+
SWAPTYPE(arr1->data, arr2->data, char *);
|
778 |
+
SWAPTYPE(arr1->nd, arr2->nd, int);
|
779 |
+
SWAPTYPE(arr1->dimensions, arr2->dimensions, npy_intp *);
|
780 |
+
SWAPTYPE(arr1->strides, arr2->strides, npy_intp *);
|
781 |
+
SWAPTYPE(arr1->base, arr2->base, PyObject *);
|
782 |
+
SWAPTYPE(arr1->descr, arr2->descr, PyArray_Descr *);
|
783 |
+
SWAPTYPE(arr1->flags, arr2->flags, int);
|
784 |
+
/* SWAPTYPE(arr1->weakreflist,arr2->weakreflist,PyObject*); */
|
785 |
+
return 0;
|
786 |
+
}
|
787 |
+
|
788 |
+
#define ARRAY_ISCOMPATIBLE(arr,type_num) \
|
789 |
+
((PyArray_ISINTEGER(arr) && PyTypeNum_ISINTEGER(type_num)) || \
|
790 |
+
(PyArray_ISFLOAT(arr) && PyTypeNum_ISFLOAT(type_num)) || \
|
791 |
+
(PyArray_ISCOMPLEX(arr) && PyTypeNum_ISCOMPLEX(type_num)) || \
|
792 |
+
(PyArray_ISBOOL(arr) && PyTypeNum_ISBOOL(type_num)) || \
|
793 |
+
(PyArray_ISSTRING(arr) && PyTypeNum_ISSTRING(type_num)))
|
794 |
+
|
795 |
+
static int
|
796 |
+
get_elsize(PyObject *obj) {
|
797 |
+
/*
|
798 |
+
get_elsize determines array itemsize from a Python object. Returns
|
799 |
+
elsize if successful, -1 otherwise.
|
800 |
+
|
801 |
+
Supported types of the input are: numpy.ndarray, bytes, str, tuple,
|
802 |
+
list.
|
803 |
+
*/
|
804 |
+
|
805 |
+
if (PyArray_Check(obj)) {
|
806 |
+
return PyArray_DESCR((PyArrayObject *)obj)->elsize;
|
807 |
+
} else if (PyBytes_Check(obj)) {
|
808 |
+
return PyBytes_GET_SIZE(obj);
|
809 |
+
} else if (PyUnicode_Check(obj)) {
|
810 |
+
return PyUnicode_GET_LENGTH(obj);
|
811 |
+
} else if (PySequence_Check(obj)) {
|
812 |
+
PyObject* fast = PySequence_Fast(obj, "f2py:fortranobject.c:get_elsize");
|
813 |
+
if (fast != NULL) {
|
814 |
+
Py_ssize_t i, n = PySequence_Fast_GET_SIZE(fast);
|
815 |
+
int sz, elsize = 0;
|
816 |
+
for (i=0; i<n; i++) {
|
817 |
+
sz = get_elsize(PySequence_Fast_GET_ITEM(fast, i) /* borrowed */);
|
818 |
+
if (sz > elsize) {
|
819 |
+
elsize = sz;
|
820 |
+
}
|
821 |
+
}
|
822 |
+
Py_DECREF(fast);
|
823 |
+
return elsize;
|
824 |
+
}
|
825 |
+
}
|
826 |
+
return -1;
|
827 |
+
}
|
828 |
+
|
829 |
+
extern PyArrayObject *
|
830 |
+
ndarray_from_pyobj(const int type_num,
|
831 |
+
const int elsize_,
|
832 |
+
npy_intp *dims,
|
833 |
+
const int rank,
|
834 |
+
const int intent,
|
835 |
+
PyObject *obj,
|
836 |
+
const char *errmess) {
|
837 |
+
/*
|
838 |
+
* Return an array with given element type and shape from a Python
|
839 |
+
* object while taking into account the usage intent of the array.
|
840 |
+
*
|
841 |
+
* - element type is defined by type_num and elsize
|
842 |
+
* - shape is defined by dims and rank
|
843 |
+
*
|
844 |
+
* ndarray_from_pyobj is used to convert Python object arguments
|
845 |
+
* to numpy ndarrays with given type and shape that data is passed
|
846 |
+
* to interfaced Fortran or C functions.
|
847 |
+
*
|
848 |
+
* errmess (if not NULL), contains a prefix of an error message
|
849 |
+
* for an exception to be triggered within this function.
|
850 |
+
*
|
851 |
+
* Negative elsize value means that elsize is to be determined
|
852 |
+
* from the Python object in runtime.
|
853 |
+
*
|
854 |
+
* Note on strings
|
855 |
+
* ---------------
|
856 |
+
*
|
857 |
+
* String type (type_num == NPY_STRING) does not have fixed
|
858 |
+
* element size and, by default, the type object sets it to
|
859 |
+
* 0. Therefore, for string types, one has to use elsize
|
860 |
+
* argument. For other types, elsize value is ignored.
|
861 |
+
*
|
862 |
+
* NumPy defines the type of a fixed-width string as
|
863 |
+
* dtype('S<width>'). In addition, there is also dtype('c'), that
|
864 |
+
* appears as dtype('S1') (these have the same type_num value),
|
865 |
+
* but is actually different (.char attribute is either 'S' or
|
866 |
+
* 'c', respecitely).
|
867 |
+
*
|
868 |
+
* In Fortran, character arrays and strings are different
|
869 |
+
* concepts. The relation between Fortran types, NumPy dtypes,
|
870 |
+
* and type_num-elsize pairs, is defined as follows:
|
871 |
+
*
|
872 |
+
* character*5 foo | dtype('S5') | elsize=5, shape=()
|
873 |
+
* character(5) foo | dtype('S1') | elsize=1, shape=(5)
|
874 |
+
* character*5 foo(n) | dtype('S5') | elsize=5, shape=(n,)
|
875 |
+
* character(5) foo(n) | dtype('S1') | elsize=1, shape=(5, n)
|
876 |
+
* character*(*) foo | dtype('S') | elsize=-1, shape=()
|
877 |
+
*
|
878 |
+
* Note about reference counting
|
879 |
+
* -----------------------------
|
880 |
+
*
|
881 |
+
* If the caller returns the array to Python, it must be done with
|
882 |
+
* Py_BuildValue("N",arr). Otherwise, if obj!=arr then the caller
|
883 |
+
* must call Py_DECREF(arr).
|
884 |
+
*
|
885 |
+
* Note on intent(cache,out,..)
|
886 |
+
* ----------------------------
|
887 |
+
* Don't expect correct data when returning intent(cache) array.
|
888 |
+
*
|
889 |
+
*/
|
890 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
891 |
+
PyArrayObject *arr = NULL;
|
892 |
+
int elsize = (elsize_ < 0 ? get_elsize(obj) : elsize_);
|
893 |
+
if (elsize < 0) {
|
894 |
+
if (errmess != NULL) {
|
895 |
+
strcpy(mess, errmess);
|
896 |
+
}
|
897 |
+
sprintf(mess + strlen(mess),
|
898 |
+
" -- failed to determine element size from %s",
|
899 |
+
Py_TYPE(obj)->tp_name);
|
900 |
+
PyErr_SetString(PyExc_SystemError, mess);
|
901 |
+
return NULL;
|
902 |
+
}
|
903 |
+
PyArray_Descr * descr = get_descr_from_type_and_elsize(type_num, elsize); // new reference
|
904 |
+
if (descr == NULL) {
|
905 |
+
return NULL;
|
906 |
+
}
|
907 |
+
elsize = descr->elsize;
|
908 |
+
if ((intent & F2PY_INTENT_HIDE)
|
909 |
+
|| ((intent & F2PY_INTENT_CACHE) && (obj == Py_None))
|
910 |
+
|| ((intent & F2PY_OPTIONAL) && (obj == Py_None))
|
911 |
+
) {
|
912 |
+
/* intent(cache), optional, intent(hide) */
|
913 |
+
int ineg = find_first_negative_dimension(rank, dims);
|
914 |
+
if (ineg >= 0) {
|
915 |
+
int i;
|
916 |
+
strcpy(mess, "failed to create intent(cache|hide)|optional array"
|
917 |
+
"-- must have defined dimensions but got (");
|
918 |
+
for(i = 0; i < rank; ++i)
|
919 |
+
sprintf(mess + strlen(mess), "%" NPY_INTP_FMT ",", dims[i]);
|
920 |
+
strcat(mess, ")");
|
921 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
922 |
+
Py_DECREF(descr);
|
923 |
+
return NULL;
|
924 |
+
}
|
925 |
+
arr = (PyArrayObject *) \
|
926 |
+
PyArray_NewFromDescr(&PyArray_Type, descr, rank, dims,
|
927 |
+
NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
|
928 |
+
if (arr == NULL) {
|
929 |
+
Py_DECREF(descr);
|
930 |
+
return NULL;
|
931 |
+
}
|
932 |
+
if (PyArray_ITEMSIZE(arr) != elsize) {
|
933 |
+
strcpy(mess, "failed to create intent(cache|hide)|optional array");
|
934 |
+
sprintf(mess+strlen(mess)," -- expected elsize=%d got %" NPY_INTP_FMT, elsize, (npy_intp)PyArray_ITEMSIZE(arr));
|
935 |
+
PyErr_SetString(PyExc_ValueError,mess);
|
936 |
+
Py_DECREF(arr);
|
937 |
+
return NULL;
|
938 |
+
}
|
939 |
+
if (!(intent & F2PY_INTENT_CACHE)) {
|
940 |
+
PyArray_FILLWBYTE(arr, 0);
|
941 |
+
}
|
942 |
+
return arr;
|
943 |
+
}
|
944 |
+
|
945 |
+
if (PyArray_Check(obj)) {
|
946 |
+
arr = (PyArrayObject *)obj;
|
947 |
+
if (intent & F2PY_INTENT_CACHE) {
|
948 |
+
/* intent(cache) */
|
949 |
+
if (PyArray_ISONESEGMENT(arr)
|
950 |
+
&& PyArray_ITEMSIZE(arr) >= elsize) {
|
951 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
952 |
+
Py_DECREF(descr);
|
953 |
+
return NULL;
|
954 |
+
}
|
955 |
+
if (intent & F2PY_INTENT_OUT)
|
956 |
+
Py_INCREF(arr);
|
957 |
+
Py_DECREF(descr);
|
958 |
+
return arr;
|
959 |
+
}
|
960 |
+
strcpy(mess, "failed to initialize intent(cache) array");
|
961 |
+
if (!PyArray_ISONESEGMENT(arr))
|
962 |
+
strcat(mess, " -- input must be in one segment");
|
963 |
+
if (PyArray_ITEMSIZE(arr) < elsize)
|
964 |
+
sprintf(mess + strlen(mess),
|
965 |
+
" -- expected at least elsize=%d but got "
|
966 |
+
"%" NPY_INTP_FMT,
|
967 |
+
elsize, (npy_intp)PyArray_ITEMSIZE(arr));
|
968 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
969 |
+
Py_DECREF(descr);
|
970 |
+
return NULL;
|
971 |
+
}
|
972 |
+
|
973 |
+
/* here we have always intent(in) or intent(inout) or intent(inplace)
|
974 |
+
*/
|
975 |
+
|
976 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
977 |
+
Py_DECREF(descr);
|
978 |
+
return NULL;
|
979 |
+
}
|
980 |
+
/*
|
981 |
+
printf("intent alignment=%d\n", F2PY_GET_ALIGNMENT(intent));
|
982 |
+
printf("alignment check=%d\n", F2PY_CHECK_ALIGNMENT(arr, intent));
|
983 |
+
int i;
|
984 |
+
for (i=1;i<=16;i++)
|
985 |
+
printf("i=%d isaligned=%d\n", i, ARRAY_ISALIGNED(arr, i));
|
986 |
+
*/
|
987 |
+
if ((! (intent & F2PY_INTENT_COPY)) &&
|
988 |
+
PyArray_ITEMSIZE(arr) == elsize &&
|
989 |
+
ARRAY_ISCOMPATIBLE(arr,type_num) &&
|
990 |
+
F2PY_CHECK_ALIGNMENT(arr, intent)) {
|
991 |
+
if ((intent & F2PY_INTENT_INOUT || intent & F2PY_INTENT_INPLACE)
|
992 |
+
? ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY(arr) : PyArray_ISFARRAY(arr))
|
993 |
+
: ((intent & F2PY_INTENT_C) ? PyArray_ISCARRAY_RO(arr) : PyArray_ISFARRAY_RO(arr))) {
|
994 |
+
if ((intent & F2PY_INTENT_OUT)) {
|
995 |
+
Py_INCREF(arr);
|
996 |
+
}
|
997 |
+
/* Returning input array */
|
998 |
+
Py_DECREF(descr);
|
999 |
+
return arr;
|
1000 |
+
}
|
1001 |
+
}
|
1002 |
+
if (intent & F2PY_INTENT_INOUT) {
|
1003 |
+
strcpy(mess, "failed to initialize intent(inout) array");
|
1004 |
+
/* Must use PyArray_IS*ARRAY because intent(inout) requires
|
1005 |
+
* writable input */
|
1006 |
+
if ((intent & F2PY_INTENT_C) && !PyArray_ISCARRAY(arr))
|
1007 |
+
strcat(mess, " -- input not contiguous");
|
1008 |
+
if (!(intent & F2PY_INTENT_C) && !PyArray_ISFARRAY(arr))
|
1009 |
+
strcat(mess, " -- input not fortran contiguous");
|
1010 |
+
if (PyArray_ITEMSIZE(arr) != elsize)
|
1011 |
+
sprintf(mess + strlen(mess),
|
1012 |
+
" -- expected elsize=%d but got %" NPY_INTP_FMT,
|
1013 |
+
elsize,
|
1014 |
+
(npy_intp)PyArray_ITEMSIZE(arr)
|
1015 |
+
);
|
1016 |
+
if (!(ARRAY_ISCOMPATIBLE(arr, type_num))) {
|
1017 |
+
sprintf(mess + strlen(mess),
|
1018 |
+
" -- input '%c' not compatible to '%c'",
|
1019 |
+
PyArray_DESCR(arr)->type, descr->type);
|
1020 |
+
}
|
1021 |
+
if (!(F2PY_CHECK_ALIGNMENT(arr, intent)))
|
1022 |
+
sprintf(mess + strlen(mess), " -- input not %d-aligned",
|
1023 |
+
F2PY_GET_ALIGNMENT(intent));
|
1024 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1025 |
+
Py_DECREF(descr);
|
1026 |
+
return NULL;
|
1027 |
+
}
|
1028 |
+
|
1029 |
+
/* here we have always intent(in) or intent(inplace) */
|
1030 |
+
|
1031 |
+
{
|
1032 |
+
PyArrayObject * retarr = (PyArrayObject *) \
|
1033 |
+
PyArray_NewFromDescr(&PyArray_Type, descr, PyArray_NDIM(arr), PyArray_DIMS(arr),
|
1034 |
+
NULL, NULL, !(intent & F2PY_INTENT_C), NULL);
|
1035 |
+
if (retarr==NULL) {
|
1036 |
+
Py_DECREF(descr);
|
1037 |
+
return NULL;
|
1038 |
+
}
|
1039 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
|
1040 |
+
if (PyArray_CopyInto(retarr, arr)) {
|
1041 |
+
Py_DECREF(retarr);
|
1042 |
+
return NULL;
|
1043 |
+
}
|
1044 |
+
if (intent & F2PY_INTENT_INPLACE) {
|
1045 |
+
if (swap_arrays(arr,retarr)) {
|
1046 |
+
Py_DECREF(retarr);
|
1047 |
+
return NULL; /* XXX: set exception */
|
1048 |
+
}
|
1049 |
+
Py_XDECREF(retarr);
|
1050 |
+
if (intent & F2PY_INTENT_OUT)
|
1051 |
+
Py_INCREF(arr);
|
1052 |
+
} else {
|
1053 |
+
arr = retarr;
|
1054 |
+
}
|
1055 |
+
}
|
1056 |
+
return arr;
|
1057 |
+
}
|
1058 |
+
|
1059 |
+
if ((intent & F2PY_INTENT_INOUT) || (intent & F2PY_INTENT_INPLACE) ||
|
1060 |
+
(intent & F2PY_INTENT_CACHE)) {
|
1061 |
+
PyErr_Format(PyExc_TypeError,
|
1062 |
+
"failed to initialize intent(inout|inplace|cache) "
|
1063 |
+
"array, input '%s' object is not an array",
|
1064 |
+
Py_TYPE(obj)->tp_name);
|
1065 |
+
Py_DECREF(descr);
|
1066 |
+
return NULL;
|
1067 |
+
}
|
1068 |
+
|
1069 |
+
{
|
1070 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMANY;
|
1071 |
+
arr = (PyArrayObject *)PyArray_FromAny(
|
1072 |
+
obj, descr, 0, 0,
|
1073 |
+
((intent & F2PY_INTENT_C) ? NPY_ARRAY_CARRAY
|
1074 |
+
: NPY_ARRAY_FARRAY) |
|
1075 |
+
NPY_ARRAY_FORCECAST,
|
1076 |
+
NULL);
|
1077 |
+
// Warning: in the case of NPY_STRING, PyArray_FromAny may
|
1078 |
+
// reset descr->elsize, e.g. dtype('S0') becomes dtype('S1').
|
1079 |
+
if (arr == NULL) {
|
1080 |
+
Py_DECREF(descr);
|
1081 |
+
return NULL;
|
1082 |
+
}
|
1083 |
+
if (type_num != NPY_STRING && PyArray_ITEMSIZE(arr) != elsize) {
|
1084 |
+
// This is internal sanity tests: elsize has been set to
|
1085 |
+
// descr->elsize in the beginning of this function.
|
1086 |
+
strcpy(mess, "failed to initialize intent(in) array");
|
1087 |
+
sprintf(mess + strlen(mess),
|
1088 |
+
" -- expected elsize=%d got %" NPY_INTP_FMT, elsize,
|
1089 |
+
(npy_intp)PyArray_ITEMSIZE(arr));
|
1090 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1091 |
+
Py_DECREF(arr);
|
1092 |
+
return NULL;
|
1093 |
+
}
|
1094 |
+
if (check_and_fix_dimensions(arr, rank, dims, errmess)) {
|
1095 |
+
Py_DECREF(arr);
|
1096 |
+
return NULL;
|
1097 |
+
}
|
1098 |
+
return arr;
|
1099 |
+
}
|
1100 |
+
}
|
1101 |
+
|
1102 |
+
extern PyArrayObject *
|
1103 |
+
array_from_pyobj(const int type_num,
|
1104 |
+
npy_intp *dims,
|
1105 |
+
const int rank,
|
1106 |
+
const int intent,
|
1107 |
+
PyObject *obj) {
|
1108 |
+
/*
|
1109 |
+
Same as ndarray_from_pyobj but with elsize determined from type,
|
1110 |
+
if possible. Provided for backward compatibility.
|
1111 |
+
*/
|
1112 |
+
PyArray_Descr* descr = PyArray_DescrFromType(type_num);
|
1113 |
+
int elsize = descr->elsize;
|
1114 |
+
Py_DECREF(descr);
|
1115 |
+
return ndarray_from_pyobj(type_num, elsize, dims, rank, intent, obj, NULL);
|
1116 |
+
}
|
1117 |
+
|
1118 |
+
/*****************************************/
|
1119 |
+
/* Helper functions for array_from_pyobj */
|
1120 |
+
/*****************************************/
|
1121 |
+
|
1122 |
+
static int
|
1123 |
+
check_and_fix_dimensions(const PyArrayObject* arr, const int rank,
|
1124 |
+
npy_intp *dims, const char *errmess)
|
1125 |
+
{
|
1126 |
+
/*
|
1127 |
+
* This function fills in blanks (that are -1's) in dims list using
|
1128 |
+
* the dimensions from arr. It also checks that non-blank dims will
|
1129 |
+
* match with the corresponding values in arr dimensions.
|
1130 |
+
*
|
1131 |
+
* Returns 0 if the function is successful.
|
1132 |
+
*
|
1133 |
+
* If an error condition is detected, an exception is set and 1 is
|
1134 |
+
* returned.
|
1135 |
+
*/
|
1136 |
+
char mess[F2PY_MESSAGE_BUFFER_SIZE];
|
1137 |
+
const npy_intp arr_size =
|
1138 |
+
(PyArray_NDIM(arr)) ? PyArray_Size((PyObject *)arr) : 1;
|
1139 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
1140 |
+
dump_attrs(arr);
|
1141 |
+
printf("check_and_fix_dimensions:init: dims=");
|
1142 |
+
dump_dims(rank, dims);
|
1143 |
+
#endif
|
1144 |
+
if (rank > PyArray_NDIM(arr)) { /* [1,2] -> [[1],[2]]; 1 -> [[1]] */
|
1145 |
+
npy_intp new_size = 1;
|
1146 |
+
int free_axe = -1;
|
1147 |
+
int i;
|
1148 |
+
npy_intp d;
|
1149 |
+
/* Fill dims where -1 or 0; check dimensions; calc new_size; */
|
1150 |
+
for (i = 0; i < PyArray_NDIM(arr); ++i) {
|
1151 |
+
d = PyArray_DIM(arr, i);
|
1152 |
+
if (dims[i] >= 0) {
|
1153 |
+
if (d > 1 && dims[i] != d) {
|
1154 |
+
PyErr_Format(
|
1155 |
+
PyExc_ValueError,
|
1156 |
+
"%d-th dimension must be fixed to %" NPY_INTP_FMT
|
1157 |
+
" but got %" NPY_INTP_FMT "\n",
|
1158 |
+
i, dims[i], d);
|
1159 |
+
return 1;
|
1160 |
+
}
|
1161 |
+
if (!dims[i])
|
1162 |
+
dims[i] = 1;
|
1163 |
+
}
|
1164 |
+
else {
|
1165 |
+
dims[i] = d ? d : 1;
|
1166 |
+
}
|
1167 |
+
new_size *= dims[i];
|
1168 |
+
}
|
1169 |
+
for (i = PyArray_NDIM(arr); i < rank; ++i)
|
1170 |
+
if (dims[i] > 1) {
|
1171 |
+
PyErr_Format(PyExc_ValueError,
|
1172 |
+
"%d-th dimension must be %" NPY_INTP_FMT
|
1173 |
+
" but got 0 (not defined).\n",
|
1174 |
+
i, dims[i]);
|
1175 |
+
return 1;
|
1176 |
+
}
|
1177 |
+
else if (free_axe < 0)
|
1178 |
+
free_axe = i;
|
1179 |
+
else
|
1180 |
+
dims[i] = 1;
|
1181 |
+
if (free_axe >= 0) {
|
1182 |
+
dims[free_axe] = arr_size / new_size;
|
1183 |
+
new_size *= dims[free_axe];
|
1184 |
+
}
|
1185 |
+
if (new_size != arr_size) {
|
1186 |
+
PyErr_Format(PyExc_ValueError,
|
1187 |
+
"unexpected array size: new_size=%" NPY_INTP_FMT
|
1188 |
+
", got array with arr_size=%" NPY_INTP_FMT
|
1189 |
+
" (maybe too many free indices)\n",
|
1190 |
+
new_size, arr_size);
|
1191 |
+
return 1;
|
1192 |
+
}
|
1193 |
+
}
|
1194 |
+
else if (rank == PyArray_NDIM(arr)) {
|
1195 |
+
npy_intp new_size = 1;
|
1196 |
+
int i;
|
1197 |
+
npy_intp d;
|
1198 |
+
for (i = 0; i < rank; ++i) {
|
1199 |
+
d = PyArray_DIM(arr, i);
|
1200 |
+
if (dims[i] >= 0) {
|
1201 |
+
if (d > 1 && d != dims[i]) {
|
1202 |
+
if (errmess != NULL) {
|
1203 |
+
strcpy(mess, errmess);
|
1204 |
+
}
|
1205 |
+
sprintf(mess + strlen(mess),
|
1206 |
+
" -- %d-th dimension must be fixed to %"
|
1207 |
+
NPY_INTP_FMT " but got %" NPY_INTP_FMT,
|
1208 |
+
i, dims[i], d);
|
1209 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1210 |
+
return 1;
|
1211 |
+
}
|
1212 |
+
if (!dims[i])
|
1213 |
+
dims[i] = 1;
|
1214 |
+
}
|
1215 |
+
else
|
1216 |
+
dims[i] = d;
|
1217 |
+
new_size *= dims[i];
|
1218 |
+
}
|
1219 |
+
if (new_size != arr_size) {
|
1220 |
+
PyErr_Format(PyExc_ValueError,
|
1221 |
+
"unexpected array size: new_size=%" NPY_INTP_FMT
|
1222 |
+
", got array with arr_size=%" NPY_INTP_FMT "\n",
|
1223 |
+
new_size, arr_size);
|
1224 |
+
return 1;
|
1225 |
+
}
|
1226 |
+
}
|
1227 |
+
else { /* [[1,2]] -> [[1],[2]] */
|
1228 |
+
int i, j;
|
1229 |
+
npy_intp d;
|
1230 |
+
int effrank;
|
1231 |
+
npy_intp size;
|
1232 |
+
for (i = 0, effrank = 0; i < PyArray_NDIM(arr); ++i)
|
1233 |
+
if (PyArray_DIM(arr, i) > 1)
|
1234 |
+
++effrank;
|
1235 |
+
if (dims[rank - 1] >= 0)
|
1236 |
+
if (effrank > rank) {
|
1237 |
+
PyErr_Format(PyExc_ValueError,
|
1238 |
+
"too many axes: %d (effrank=%d), "
|
1239 |
+
"expected rank=%d\n",
|
1240 |
+
PyArray_NDIM(arr), effrank, rank);
|
1241 |
+
return 1;
|
1242 |
+
}
|
1243 |
+
|
1244 |
+
for (i = 0, j = 0; i < rank; ++i) {
|
1245 |
+
while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
|
1246 |
+
if (j >= PyArray_NDIM(arr))
|
1247 |
+
d = 1;
|
1248 |
+
else
|
1249 |
+
d = PyArray_DIM(arr, j++);
|
1250 |
+
if (dims[i] >= 0) {
|
1251 |
+
if (d > 1 && d != dims[i]) {
|
1252 |
+
if (errmess != NULL) {
|
1253 |
+
strcpy(mess, errmess);
|
1254 |
+
}
|
1255 |
+
sprintf(mess + strlen(mess),
|
1256 |
+
" -- %d-th dimension must be fixed to %"
|
1257 |
+
NPY_INTP_FMT " but got %" NPY_INTP_FMT
|
1258 |
+
" (real index=%d)\n",
|
1259 |
+
i, dims[i], d, j-1);
|
1260 |
+
PyErr_SetString(PyExc_ValueError, mess);
|
1261 |
+
return 1;
|
1262 |
+
}
|
1263 |
+
if (!dims[i])
|
1264 |
+
dims[i] = 1;
|
1265 |
+
}
|
1266 |
+
else
|
1267 |
+
dims[i] = d;
|
1268 |
+
}
|
1269 |
+
|
1270 |
+
for (i = rank; i < PyArray_NDIM(arr);
|
1271 |
+
++i) { /* [[1,2],[3,4]] -> [1,2,3,4] */
|
1272 |
+
while (j < PyArray_NDIM(arr) && PyArray_DIM(arr, j) < 2) ++j;
|
1273 |
+
if (j >= PyArray_NDIM(arr))
|
1274 |
+
d = 1;
|
1275 |
+
else
|
1276 |
+
d = PyArray_DIM(arr, j++);
|
1277 |
+
dims[rank - 1] *= d;
|
1278 |
+
}
|
1279 |
+
for (i = 0, size = 1; i < rank; ++i) size *= dims[i];
|
1280 |
+
if (size != arr_size) {
|
1281 |
+
char msg[200];
|
1282 |
+
int len;
|
1283 |
+
snprintf(msg, sizeof(msg),
|
1284 |
+
"unexpected array size: size=%" NPY_INTP_FMT
|
1285 |
+
", arr_size=%" NPY_INTP_FMT
|
1286 |
+
", rank=%d, effrank=%d, arr.nd=%d, dims=[",
|
1287 |
+
size, arr_size, rank, effrank, PyArray_NDIM(arr));
|
1288 |
+
for (i = 0; i < rank; ++i) {
|
1289 |
+
len = strlen(msg);
|
1290 |
+
snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
|
1291 |
+
dims[i]);
|
1292 |
+
}
|
1293 |
+
len = strlen(msg);
|
1294 |
+
snprintf(msg + len, sizeof(msg) - len, " ], arr.dims=[");
|
1295 |
+
for (i = 0; i < PyArray_NDIM(arr); ++i) {
|
1296 |
+
len = strlen(msg);
|
1297 |
+
snprintf(msg + len, sizeof(msg) - len, " %" NPY_INTP_FMT,
|
1298 |
+
PyArray_DIM(arr, i));
|
1299 |
+
}
|
1300 |
+
len = strlen(msg);
|
1301 |
+
snprintf(msg + len, sizeof(msg) - len, " ]\n");
|
1302 |
+
PyErr_SetString(PyExc_ValueError, msg);
|
1303 |
+
return 1;
|
1304 |
+
}
|
1305 |
+
}
|
1306 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
1307 |
+
printf("check_and_fix_dimensions:end: dims=");
|
1308 |
+
dump_dims(rank, dims);
|
1309 |
+
#endif
|
1310 |
+
return 0;
|
1311 |
+
}
|
1312 |
+
|
1313 |
+
/* End of file: array_from_pyobj.c */
|
1314 |
+
|
1315 |
+
/************************* copy_ND_array *******************************/
|
1316 |
+
|
1317 |
+
extern int
|
1318 |
+
copy_ND_array(const PyArrayObject *arr, PyArrayObject *out)
|
1319 |
+
{
|
1320 |
+
F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
|
1321 |
+
return PyArray_CopyInto(out, (PyArrayObject *)arr);
|
1322 |
+
}
|
1323 |
+
|
1324 |
+
/********************* Various utility functions ***********************/
|
1325 |
+
|
1326 |
+
extern int
|
1327 |
+
f2py_describe(PyObject *obj, char *buf) {
|
1328 |
+
/*
|
1329 |
+
Write the description of a Python object to buf. The caller must
|
1330 |
+
provide buffer with size sufficient to write the description.
|
1331 |
+
|
1332 |
+
Return 1 on success.
|
1333 |
+
*/
|
1334 |
+
char localbuf[F2PY_MESSAGE_BUFFER_SIZE];
|
1335 |
+
if (PyBytes_Check(obj)) {
|
1336 |
+
sprintf(localbuf, "%d-%s", (npy_int)PyBytes_GET_SIZE(obj), Py_TYPE(obj)->tp_name);
|
1337 |
+
} else if (PyUnicode_Check(obj)) {
|
1338 |
+
sprintf(localbuf, "%d-%s", (npy_int)PyUnicode_GET_LENGTH(obj), Py_TYPE(obj)->tp_name);
|
1339 |
+
} else if (PyArray_CheckScalar(obj)) {
|
1340 |
+
PyArrayObject* arr = (PyArrayObject*)obj;
|
1341 |
+
sprintf(localbuf, "%c%" NPY_INTP_FMT "-%s-scalar", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
|
1342 |
+
} else if (PyArray_Check(obj)) {
|
1343 |
+
int i;
|
1344 |
+
PyArrayObject* arr = (PyArrayObject*)obj;
|
1345 |
+
strcpy(localbuf, "(");
|
1346 |
+
for (i=0; i<PyArray_NDIM(arr); i++) {
|
1347 |
+
if (i) {
|
1348 |
+
strcat(localbuf, " ");
|
1349 |
+
}
|
1350 |
+
sprintf(localbuf + strlen(localbuf), "%" NPY_INTP_FMT ",", PyArray_DIM(arr, i));
|
1351 |
+
}
|
1352 |
+
sprintf(localbuf + strlen(localbuf), ")-%c%" NPY_INTP_FMT "-%s", PyArray_DESCR(arr)->kind, PyArray_ITEMSIZE(arr), Py_TYPE(obj)->tp_name);
|
1353 |
+
} else if (PySequence_Check(obj)) {
|
1354 |
+
sprintf(localbuf, "%d-%s", (npy_int)PySequence_Length(obj), Py_TYPE(obj)->tp_name);
|
1355 |
+
} else {
|
1356 |
+
sprintf(localbuf, "%s instance", Py_TYPE(obj)->tp_name);
|
1357 |
+
}
|
1358 |
+
// TODO: detect the size of buf and make sure that size(buf) >= size(localbuf).
|
1359 |
+
strcpy(buf, localbuf);
|
1360 |
+
return 1;
|
1361 |
+
}
|
1362 |
+
|
1363 |
+
extern npy_intp
|
1364 |
+
f2py_size_impl(PyArrayObject* var, ...)
|
1365 |
+
{
|
1366 |
+
npy_intp sz = 0;
|
1367 |
+
npy_intp dim;
|
1368 |
+
npy_intp rank;
|
1369 |
+
va_list argp;
|
1370 |
+
va_start(argp, var);
|
1371 |
+
dim = va_arg(argp, npy_int);
|
1372 |
+
if (dim==-1)
|
1373 |
+
{
|
1374 |
+
sz = PyArray_SIZE(var);
|
1375 |
+
}
|
1376 |
+
else
|
1377 |
+
{
|
1378 |
+
rank = PyArray_NDIM(var);
|
1379 |
+
if (dim>=1 && dim<=rank)
|
1380 |
+
sz = PyArray_DIM(var, dim-1);
|
1381 |
+
else
|
1382 |
+
fprintf(stderr, "f2py_size: 2nd argument value=%" NPY_INTP_FMT
|
1383 |
+
" fails to satisfy 1<=value<=%" NPY_INTP_FMT
|
1384 |
+
". Result will be 0.\n", dim, rank);
|
1385 |
+
}
|
1386 |
+
va_end(argp);
|
1387 |
+
return sz;
|
1388 |
+
}
|
1389 |
+
|
1390 |
+
/*********************************************/
|
1391 |
+
/* Compatibility functions for Python >= 3.0 */
|
1392 |
+
/*********************************************/
|
1393 |
+
|
1394 |
+
PyObject *
|
1395 |
+
F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))
|
1396 |
+
{
|
1397 |
+
PyObject *ret = PyCapsule_New(ptr, NULL, dtor);
|
1398 |
+
if (ret == NULL) {
|
1399 |
+
PyErr_Clear();
|
1400 |
+
}
|
1401 |
+
return ret;
|
1402 |
+
}
|
1403 |
+
|
1404 |
+
void *
|
1405 |
+
F2PyCapsule_AsVoidPtr(PyObject *obj)
|
1406 |
+
{
|
1407 |
+
void *ret = PyCapsule_GetPointer(obj, NULL);
|
1408 |
+
if (ret == NULL) {
|
1409 |
+
PyErr_Clear();
|
1410 |
+
}
|
1411 |
+
return ret;
|
1412 |
+
}
|
1413 |
+
|
1414 |
+
int
|
1415 |
+
F2PyCapsule_Check(PyObject *ptr)
|
1416 |
+
{
|
1417 |
+
return PyCapsule_CheckExact(ptr);
|
1418 |
+
}
|
1419 |
+
|
1420 |
+
#ifdef __cplusplus
|
1421 |
+
}
|
1422 |
+
#endif
|
1423 |
+
/************************* EOF fortranobject.c *******************************/
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/src/fortranobject.h
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef Py_FORTRANOBJECT_H
|
2 |
+
#define Py_FORTRANOBJECT_H
|
3 |
+
#ifdef __cplusplus
|
4 |
+
extern "C" {
|
5 |
+
#endif
|
6 |
+
|
7 |
+
#include <Python.h>
|
8 |
+
|
9 |
+
#ifndef NPY_NO_DEPRECATED_API
|
10 |
+
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
|
11 |
+
#endif
|
12 |
+
#ifdef FORTRANOBJECT_C
|
13 |
+
#define NO_IMPORT_ARRAY
|
14 |
+
#endif
|
15 |
+
#define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API
|
16 |
+
#include "numpy/arrayobject.h"
|
17 |
+
#include "numpy/npy_3kcompat.h"
|
18 |
+
|
19 |
+
#ifdef F2PY_REPORT_ATEXIT
|
20 |
+
#include <sys/timeb.h>
|
21 |
+
// clang-format off
|
22 |
+
extern void f2py_start_clock(void);
|
23 |
+
extern void f2py_stop_clock(void);
|
24 |
+
extern void f2py_start_call_clock(void);
|
25 |
+
extern void f2py_stop_call_clock(void);
|
26 |
+
extern void f2py_cb_start_clock(void);
|
27 |
+
extern void f2py_cb_stop_clock(void);
|
28 |
+
extern void f2py_cb_start_call_clock(void);
|
29 |
+
extern void f2py_cb_stop_call_clock(void);
|
30 |
+
extern void f2py_report_on_exit(int, void *);
|
31 |
+
// clang-format on
|
32 |
+
#endif
|
33 |
+
|
34 |
+
#ifdef DMALLOC
|
35 |
+
#include "dmalloc.h"
|
36 |
+
#endif
|
37 |
+
|
38 |
+
/* Fortran object interface */
|
39 |
+
|
40 |
+
/*
|
41 |
+
123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
|
42 |
+
|
43 |
+
PyFortranObject represents various Fortran objects:
|
44 |
+
Fortran (module) routines, COMMON blocks, module data.
|
45 |
+
|
46 |
+
Author: Pearu Peterson <[email protected]>
|
47 |
+
*/
|
48 |
+
|
49 |
+
#define F2PY_MAX_DIMS 40
|
50 |
+
#define F2PY_MESSAGE_BUFFER_SIZE 300 // Increase on "stack smashing detected"
|
51 |
+
|
52 |
+
typedef void (*f2py_set_data_func)(char *, npy_intp *);
|
53 |
+
typedef void (*f2py_void_func)(void);
|
54 |
+
typedef void (*f2py_init_func)(int *, npy_intp *, f2py_set_data_func, int *);
|
55 |
+
|
56 |
+
/*typedef void* (*f2py_c_func)(void*,...);*/
|
57 |
+
|
58 |
+
typedef void *(*f2pycfunc)(void);
|
59 |
+
|
60 |
+
typedef struct {
|
61 |
+
char *name; /* attribute (array||routine) name */
|
62 |
+
int rank; /* array rank, 0 for scalar, max is F2PY_MAX_DIMS,
|
63 |
+
|| rank=-1 for Fortran routine */
|
64 |
+
struct {
|
65 |
+
npy_intp d[F2PY_MAX_DIMS];
|
66 |
+
} dims; /* dimensions of the array, || not used */
|
67 |
+
int type; /* PyArray_<type> || not used */
|
68 |
+
int elsize; /* Element size || not used */
|
69 |
+
char *data; /* pointer to array || Fortran routine */
|
70 |
+
f2py_init_func func; /* initialization function for
|
71 |
+
allocatable arrays:
|
72 |
+
func(&rank,dims,set_ptr_func,name,len(name))
|
73 |
+
|| C/API wrapper for Fortran routine */
|
74 |
+
char *doc; /* documentation string; only recommended
|
75 |
+
for routines. */
|
76 |
+
} FortranDataDef;
|
77 |
+
|
78 |
+
typedef struct {
|
79 |
+
PyObject_HEAD
|
80 |
+
int len; /* Number of attributes */
|
81 |
+
FortranDataDef *defs; /* An array of FortranDataDef's */
|
82 |
+
PyObject *dict; /* Fortran object attribute dictionary */
|
83 |
+
} PyFortranObject;
|
84 |
+
|
85 |
+
#define PyFortran_Check(op) (Py_TYPE(op) == &PyFortran_Type)
|
86 |
+
#define PyFortran_Check1(op) (0 == strcmp(Py_TYPE(op)->tp_name, "fortran"))
|
87 |
+
|
88 |
+
extern PyTypeObject PyFortran_Type;
|
89 |
+
extern int
|
90 |
+
F2PyDict_SetItemString(PyObject *dict, char *name, PyObject *obj);
|
91 |
+
extern PyObject *
|
92 |
+
PyFortranObject_New(FortranDataDef *defs, f2py_void_func init);
|
93 |
+
extern PyObject *
|
94 |
+
PyFortranObject_NewAsAttr(FortranDataDef *defs);
|
95 |
+
|
96 |
+
PyObject *
|
97 |
+
F2PyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *));
|
98 |
+
void *
|
99 |
+
F2PyCapsule_AsVoidPtr(PyObject *obj);
|
100 |
+
int
|
101 |
+
F2PyCapsule_Check(PyObject *ptr);
|
102 |
+
|
103 |
+
extern void *
|
104 |
+
F2PySwapThreadLocalCallbackPtr(char *key, void *ptr);
|
105 |
+
extern void *
|
106 |
+
F2PyGetThreadLocalCallbackPtr(char *key);
|
107 |
+
|
108 |
+
#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & NPY_ARRAY_C_CONTIGUOUS)
|
109 |
+
#define F2PY_INTENT_IN 1
|
110 |
+
#define F2PY_INTENT_INOUT 2
|
111 |
+
#define F2PY_INTENT_OUT 4
|
112 |
+
#define F2PY_INTENT_HIDE 8
|
113 |
+
#define F2PY_INTENT_CACHE 16
|
114 |
+
#define F2PY_INTENT_COPY 32
|
115 |
+
#define F2PY_INTENT_C 64
|
116 |
+
#define F2PY_OPTIONAL 128
|
117 |
+
#define F2PY_INTENT_INPLACE 256
|
118 |
+
#define F2PY_INTENT_ALIGNED4 512
|
119 |
+
#define F2PY_INTENT_ALIGNED8 1024
|
120 |
+
#define F2PY_INTENT_ALIGNED16 2048
|
121 |
+
|
122 |
+
#define ARRAY_ISALIGNED(ARR, SIZE) ((size_t)(PyArray_DATA(ARR)) % (SIZE) == 0)
|
123 |
+
#define F2PY_ALIGN4(intent) (intent & F2PY_INTENT_ALIGNED4)
|
124 |
+
#define F2PY_ALIGN8(intent) (intent & F2PY_INTENT_ALIGNED8)
|
125 |
+
#define F2PY_ALIGN16(intent) (intent & F2PY_INTENT_ALIGNED16)
|
126 |
+
|
127 |
+
#define F2PY_GET_ALIGNMENT(intent) \
|
128 |
+
(F2PY_ALIGN4(intent) \
|
129 |
+
? 4 \
|
130 |
+
: (F2PY_ALIGN8(intent) ? 8 : (F2PY_ALIGN16(intent) ? 16 : 1)))
|
131 |
+
#define F2PY_CHECK_ALIGNMENT(arr, intent) \
|
132 |
+
ARRAY_ISALIGNED(arr, F2PY_GET_ALIGNMENT(intent))
|
133 |
+
#define F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr) ((PyArray_DESCR(arr)->type_num == NPY_STRING && PyArray_DESCR(arr)->elsize >= 1) \
|
134 |
+
|| PyArray_DESCR(arr)->type_num == NPY_UINT8)
|
135 |
+
#define F2PY_IS_UNICODE_ARRAY(arr) (PyArray_DESCR(arr)->type_num == NPY_UNICODE)
|
136 |
+
|
137 |
+
extern PyArrayObject *
|
138 |
+
ndarray_from_pyobj(const int type_num, const int elsize_, npy_intp *dims,
|
139 |
+
const int rank, const int intent, PyObject *obj,
|
140 |
+
const char *errmess);
|
141 |
+
|
142 |
+
extern PyArrayObject *
|
143 |
+
array_from_pyobj(const int type_num, npy_intp *dims, const int rank,
|
144 |
+
const int intent, PyObject *obj);
|
145 |
+
extern int
|
146 |
+
copy_ND_array(const PyArrayObject *in, PyArrayObject *out);
|
147 |
+
|
148 |
+
#ifdef DEBUG_COPY_ND_ARRAY
|
149 |
+
extern void
|
150 |
+
dump_attrs(const PyArrayObject *arr);
|
151 |
+
#endif
|
152 |
+
|
153 |
+
extern int f2py_describe(PyObject *obj, char *buf);
|
154 |
+
|
155 |
+
/* Utility CPP macros and functions that can be used in signature file
|
156 |
+
expressions. See signature-file.rst for documentation.
|
157 |
+
*/
|
158 |
+
|
159 |
+
#define f2py_itemsize(var) (PyArray_DESCR((capi_ ## var ## _as_array))->elsize)
|
160 |
+
#define f2py_size(var, ...) f2py_size_impl((PyArrayObject *)(capi_ ## var ## _as_array), ## __VA_ARGS__, -1)
|
161 |
+
#define f2py_rank(var) var ## _Rank
|
162 |
+
#define f2py_shape(var,dim) var ## _Dims[dim]
|
163 |
+
#define f2py_len(var) f2py_shape(var,0)
|
164 |
+
#define f2py_fshape(var,dim) f2py_shape(var,rank(var)-dim-1)
|
165 |
+
#define f2py_flen(var) f2py_fshape(var,0)
|
166 |
+
#define f2py_slen(var) capi_ ## var ## _len
|
167 |
+
|
168 |
+
extern npy_intp f2py_size_impl(PyArrayObject* var, ...);
|
169 |
+
|
170 |
+
#ifdef __cplusplus
|
171 |
+
}
|
172 |
+
#endif
|
173 |
+
#endif /* !Py_FORTRANOBJECT_H */
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (181 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_abstract_interface.cpython-310.pyc
ADDED
Binary file (1.38 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_array_from_pyobj.cpython-310.pyc
ADDED
Binary file (20.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_assumed_shape.cpython-310.pyc
ADDED
Binary file (1.85 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_block_docstring.cpython-310.pyc
ADDED
Binary file (997 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_callback.cpython-310.pyc
ADDED
Binary file (8.89 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_character.cpython-310.pyc
ADDED
Binary file (22.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_common.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc
ADDED
Binary file (2.41 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_crackfortran.cpython-310.pyc
ADDED
Binary file (14.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_data.cpython-310.pyc
ADDED
Binary file (3.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_docs.cpython-310.pyc
ADDED
Binary file (2 kB). View file
|
|