Debian Codegraph @

pypy/module/cpyext/ndarrayobject.py

raw symbols SCIP
1 """
2
3 Numpy C-API for PyPy - S. H. Muller, 2013/07/26
4 """
5
6 from pypy.interpreter.error import OperationError, oefmt
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from pypy.module.cpyext.api import cpython_api, Py_ssize_t, CANNOT_FAIL
9 from pypy.module.cpyext.api import PyObject
10 from pypy.module.micronumpy.ndarray import W_NDimArray
11 from pypy.module.micronumpy.ctors import array
12 from pypy.module.micronumpy.descriptor import get_dtype_cache, W_Dtype
13 from pypy.module.micronumpy.concrete import ConcreteArray
14 from pypy.module.micronumpy.constants import (ARRAY_C_CONTIGUOUS,
15 ARRAY_F_CONTIGUOUS, ARRAY_OWNDATA, ARRAY_ALIGNED, ARRAY_WRITEABLE,
16 ARRAY_NOTSWAPPED, CORDER, FORTRANORDER)
17 from pypy.module.micronumpy import ufuncs
18 from rpython.rlib.rawstorage import RAW_STORAGE_PTR
19 from pypy.interpreter.typedef import TypeDef
20 from pypy.interpreter.baseobjspace import W_Root
21 from pypy.interpreter.argument import Arguments
22 from pypy.interpreter.gateway import interp2app
23
24 ARRAY_BEHAVED = ARRAY_ALIGNED | ARRAY_WRITEABLE
25 ARRAY_BEHAVED_NS = ARRAY_ALIGNED | ARRAY_WRITEABLE | ARRAY_NOTSWAPPED
26 ARRAY_CARRAY = ARRAY_C_CONTIGUOUS | ARRAY_BEHAVED
27 ARRAY_DEFAULT = ARRAY_CARRAY
28
29 npy_intpp = rffi.CArrayPtr(Py_ssize_t)
30
31
32 HEADER = 'pypy_numpy.h'
33 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
34 def _PyArray_Check(space, w_obj):
35 w_obj_type = space.type(w_obj)
36 w_type = space.gettypeobject(W_NDimArray.typedef)
37 return (space.is_w(w_obj_type, w_type) or
38 space.issubtype_w(w_obj_type, w_type))
39
40 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
41 def _PyArray_CheckExact(space, w_obj):
42 w_obj_type = space.type(w_obj)
43 w_type = space.gettypeobject(W_NDimArray.typedef)
44 return space.is_w(w_obj_type, w_type)
45
46 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
47 def _PyArray_FLAGS(space, w_array):
48 assert isinstance(w_array, W_NDimArray)
49 flags = ARRAY_BEHAVED_NS | w_array.get_flags()
50 return flags
51
52 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
53 def _PyArray_NDIM(space, w_array):
54 assert isinstance(w_array, W_NDimArray)
55 return len(w_array.get_shape())
56
57 @cpython_api([PyObject, Py_ssize_t], Py_ssize_t, error=CANNOT_FAIL, header=HEADER)
58 def _PyArray_DIM(space, w_array, n):
59 assert isinstance(w_array, W_NDimArray)
60 return w_array.get_shape()[n]
61
62 @cpython_api([PyObject, Py_ssize_t], Py_ssize_t, error=CANNOT_FAIL, header=HEADER)
63 def _PyArray_STRIDE(space, w_array, n):
64 assert isinstance(w_array, W_NDimArray)
65 return w_array.implementation.get_strides()[n]
66
67 @cpython_api([PyObject], Py_ssize_t, error=CANNOT_FAIL, header=HEADER)
68 def _PyArray_SIZE(space, w_array):
69 assert isinstance(w_array, W_NDimArray)
70 return w_array.get_size()
71
72 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
73 def _PyArray_ITEMSIZE(space, w_array):
74 assert isinstance(w_array, W_NDimArray)
75 return w_array.get_dtype().elsize
76
77 @cpython_api([PyObject], Py_ssize_t, error=CANNOT_FAIL, header=HEADER)
78 def _PyArray_NBYTES(space, w_array):
79 assert isinstance(w_array, W_NDimArray)
80 return w_array.get_size() * w_array.get_dtype().elsize
81
82 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL, header=HEADER)
83 def _PyArray_TYPE(space, w_array):
84 assert isinstance(w_array, W_NDimArray)
85 return w_array.get_dtype().num
86
87
88 @cpython_api([PyObject], rffi.VOIDP, error=CANNOT_FAIL, header=HEADER)
89 def _PyArray_DATA(space, w_array):
90 # fails on scalars - see PyArray_FromAny()
91 assert isinstance(w_array, W_NDimArray)
92 return rffi.cast(rffi.VOIDP, w_array.implementation.storage)
93
94 PyArray_Descr = PyObject
95 NULL = lltype.nullptr(rffi.VOIDP.TO)
96
97 @cpython_api([PyObject, PyArray_Descr, Py_ssize_t, Py_ssize_t, Py_ssize_t, rffi.VOIDP],
98 PyObject, header=HEADER)
99 def _PyArray_FromAny(space, w_obj, w_dtype, min_depth, max_depth, requirements, context):
100 """ This is the main function used to obtain an array from any nested
101 sequence, or object that exposes the array interface, op. The
102 parameters allow specification of the required dtype, the
103 minimum (min_depth) and maximum (max_depth) number of dimensions
104 acceptable, and other requirements for the array.
105
106 The dtype argument needs to be a PyArray_Descr structure indicating
107 the desired data-type (including required byteorder). The dtype
108 argument may be NULL, indicating that any data-type (and byteorder)
109 is acceptable.
110 Unless FORCECAST is present in flags, this call will generate an error
111 if the data type cannot be safely obtained from the object. If you
112 want to use NULL for the dtype and ensure the array is notswapped then
113 use PyArray_CheckFromAny.
114
115 A value of 0 for either of the depth parameters causes the parameter
116 to be ignored.
117
118 Any of the following array flags can be added (e.g. using |) to get
119 the requirements argument. If your code can handle general (e.g.
120 strided, byte-swapped, or unaligned arrays) then requirements
121 may be 0. Also, if op is not already an array (or does not expose
122 the array interface), then a new array will be created (and filled
123 from op using the sequence protocol). The new array will have
124 ARRAY_DEFAULT as its flags member.
125
126 The context argument is passed to the __array__ method of op and is
127 only used if the array is constructed that way. Almost always this
128 parameter is NULL.
129 """
130 if requirements not in (0, ARRAY_DEFAULT):
131 raise oefmt(space.w_NotImplementedError,
132 "_PyArray_FromAny called with not-implemented "
133 "requirements argument")
134 w_array = array(space, w_obj, w_dtype=w_dtype, copy=False)
135 if min_depth !=0 and len(w_array.get_shape()) < min_depth:
136 raise oefmt(space.w_ValueError,
137 "object of too small depth for desired array")
138 elif max_depth !=0 and len(w_array.get_shape()) > max_depth:
139 raise oefmt(space.w_ValueError,
140 "object of too deep for desired array")
141 elif w_array.is_scalar():
142 # since PyArray_DATA() fails on scalars, create a 1D array and set empty
143 # shape. So the following combination works for *reading* scalars:
144 # PyObject *arr = PyArray_FromAny(obj);
145 # int nd = PyArray_NDIM(arr);
146 # void *data = PyArray_DATA(arr);
147 impl = w_array.implementation
148 w_array = W_NDimArray.from_shape(space, [1], impl.dtype)
149 w_array.implementation.setitem(0, impl.getitem(impl.start + 0))
150 w_array.implementation.shape = []
151 return w_array
152
153 @cpython_api([Py_ssize_t], PyObject, header=HEADER)
154 def PyArray_DescrFromType(space, typenum):
155 try:
156 dtype = get_dtype_cache(space).dtypes_by_num(typenum)
157 return dtype
158 except KeyError:
159 raise oefmt(space.w_ValueError,
160 "PyArray_DescrFromType called with invalid dtype %d",
161 typenum)
162
163 @cpython_api([PyObject, Py_ssize_t, Py_ssize_t, Py_ssize_t], PyObject, header=HEADER)
164 def _PyArray_FromObject(space, w_obj, typenum, min_depth, max_depth):
165 try:
166 dtype = get_dtype_cache(space).dtypes_by_num(typenum)
167 except KeyError:
168 raise oefmt(space.w_ValueError,
169 "_PyArray_FromObject called with invalid dtype %d",
170 typenum)
171 try:
172 return _PyArray_FromAny(space, w_obj, dtype, min_depth, max_depth,
173 0, NULL);
174 except OperationError as e:
175 if e.match(space, space.w_NotImplementedError):
176 errstr = space.text_w(e.get_w_value(space))
177 raise oefmt(space.w_NotImplementedError,
178 "_PyArray_FromObject %s", errstr[16:])
179 raise
180
181 def get_shape_and_dtype(space, nd, dims, typenum):
182 shape = []
183 for i in range(nd):
184 shape.append(rffi.cast(rffi.LONG, dims[i]))
185 dtype = get_dtype_cache(space).dtypes_by_num(typenum)
186 return shape, dtype
187
188 def simple_new(space, nd, dims, typenum,
189 order=CORDER, owning=False, w_subtype=None):
190 shape, dtype = get_shape_and_dtype(space, nd, dims, typenum)
191 return W_NDimArray.from_shape(space, shape, dtype)
192
193 def simple_new_from_data(space, nd, dims, typenum, data,
194 order=CORDER, owning=False, w_subtype=None):
195 shape, dtype = get_shape_and_dtype(space, nd, dims, typenum)
196 storage = rffi.cast(RAW_STORAGE_PTR, data)
197 return W_NDimArray.from_shape_and_storage(space, shape, storage, dtype,
198 order=order, owning=owning, w_subtype=w_subtype)
199
200
201 @cpython_api([Py_ssize_t, npy_intpp, Py_ssize_t], PyObject, header=HEADER)
202 def _PyArray_SimpleNew(space, nd, dims, typenum):
203 return simple_new(space, nd, dims, typenum)
204
205 @cpython_api([Py_ssize_t, npy_intpp, Py_ssize_t, rffi.VOIDP], PyObject, header=HEADER)
206 def _PyArray_SimpleNewFromData(space, nd, dims, typenum, data):
207 return simple_new_from_data(space, nd, dims, typenum, data, owning=False)
208
209 @cpython_api([Py_ssize_t, npy_intpp, Py_ssize_t, rffi.VOIDP], PyObject, header=HEADER)
210 def _PyArray_SimpleNewFromDataOwning(space, nd, dims, typenum, data):
211 # Variant to take over ownership of the memory, equivalent to:
212 # PyObject *arr = PyArray_SimpleNewFromData(nd, dims, typenum, data);
213 # ((PyArrayObject*)arr)->flags |= ARRAY_OWNDATA;
214 return simple_new_from_data(space, nd, dims, typenum, data, owning=True)
215
216
217 @cpython_api([rffi.VOIDP, Py_ssize_t, npy_intpp, Py_ssize_t, npy_intpp,
218 rffi.VOIDP, Py_ssize_t, Py_ssize_t, PyObject], PyObject, header=HEADER)
219 def _PyArray_New(space, subtype, nd, dims, typenum, strides, data, itemsize, flags, obj):
220 if strides:
221 raise oefmt(space.w_NotImplementedError, "strides must be NULL")
222
223 order = CORDER if flags & ARRAY_C_CONTIGUOUS else FORTRANORDER
224 owning = True if flags & ARRAY_OWNDATA else False
225 w_subtype = None
226
227 if data:
228 return simple_new_from_data(space, nd, dims, typenum, data,
229 order=order, owning=owning, w_subtype=w_subtype)
230 else:
231 return simple_new(space, nd, dims, typenum,
232 order=order, owning=owning, w_subtype=w_subtype)
233
234 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1, header=HEADER)
235 def PyArray_CopyInto(space, w_dest, w_src):
236 assert isinstance(w_dest, W_NDimArray)
237 assert isinstance(w_src, W_NDimArray)
238 space.appexec([w_dest, w_src], """(dest, src):
239 dest[:] = src
240 """ )
241 return 0
242
243
244 gufunctype = lltype.Ptr(ufuncs.GenericUfunc)
245 @cpython_api([rffi.CArrayPtr(gufunctype), rffi.VOIDP, rffi.CCHARP, Py_ssize_t, Py_ssize_t,
246 Py_ssize_t, Py_ssize_t, rffi.CCHARP, rffi.CCHARP, Py_ssize_t,
247 rffi.CCHARP], PyObject, header=HEADER)
248 def PyUFunc_FromFuncAndDataAndSignature(space, funcs, data, types, ntypes,
249 nin, nout, identity, name, doc, check_return, signature):
250 w_signature = rffi.charp2str(signature)
251 return do_ufunc(space, funcs, data, types, ntypes, nin, nout, identity, name, doc,
252 check_return, w_signature)
253
254
255 def do_ufunc(space, funcs, data, types, ntypes, nin, nout, identity, name, doc,
256 check_return, w_signature):
257 funcs_w = [None] * ntypes
258 dtypes_w = [None] * ntypes * (nin + nout)
259 for i in range(ntypes):
260 funcs_w[i] = ufuncs.W_GenericUFuncCaller(funcs[i], data)
261 for i in range(ntypes*(nin+nout)):
262 dtypes_w[i] = get_dtype_cache(space).dtypes_by_num(ord(types[i]))
263 w_funcs = space.newlist(funcs_w)
264 w_dtypes = space.newlist(dtypes_w)
265 w_doc = rffi.charp2str(doc)
266 w_name = rffi.charp2str(name)
267 w_identity = space.newint(identity)
268 ufunc_generic = ufuncs.frompyfunc(space, w_funcs, nin, nout, w_dtypes,
269 w_signature, w_identity, w_name, w_doc, stack_inputs=True)
270 return ufunc_generic
271
272 @cpython_api([rffi.CArrayPtr(gufunctype), rffi.VOIDP, rffi.CCHARP, Py_ssize_t, Py_ssize_t,
273 Py_ssize_t, Py_ssize_t, rffi.CCHARP, rffi.CCHARP, Py_ssize_t], PyObject, header=HEADER)
274 def PyUFunc_FromFuncAndData(space, funcs, data, types, ntypes,
275 nin, nout, identity, name, doc, check_return):
276 w_signature = ','.join(['()'] * nin) + '->' + ','.join(['()'] * nout)
277 return do_ufunc(space, funcs, data, types, ntypes, nin, nout, identity,
278 name, doc, check_return, w_signature)