Debian Codegraph @

pypy/module/micronumpy/concrete.py

raw symbols SCIP
1 from pypy.interpreter.buffer import BufferView
2 from pypy.interpreter.error import oefmt
3 from rpython.rlib import jit, rgc
4 from rpython.rlib.rarithmetic import ovfcheck
5 from rpython.rlib.listsort import make_timsort_class
6 from rpython.rlib.buffer import RawBuffer
7 from rpython.rlib.debug import make_sure_not_resized
8 from rpython.rlib.rstring import StringBuilder
9 from rpython.rlib.rawstorage import alloc_raw_storage, free_raw_storage, \
10 raw_storage_getitem, raw_storage_setitem, RAW_STORAGE
11 from rpython.rtyper.lltypesystem import rffi, lltype, llmemory
12 from pypy.module.micronumpy import support, loop, constants as NPY
13 from pypy.module.micronumpy.base import convert_to_array, W_NDimArray, \
14 ArrayArgumentException, W_NumpyObject
15 from pypy.module.micronumpy.iterators import ArrayIter
16 from pypy.module.micronumpy.strides import (
17 IntegerChunk, SliceChunk, NewAxisChunk, EllipsisChunk, BooleanChunk,
18 new_view, calc_strides, calc_new_strides, shape_agreement,
19 calculate_broadcast_strides, calc_backstrides, calc_start, is_c_contiguous,
20 is_f_contiguous)
21 from rpython.rlib.objectmodel import keepalive_until_here
22
23 TimSort = make_timsort_class()
24 class StrideSort(TimSort):
25 '''
26 argsort (return the indices to sort) a list of strides
27 '''
28 def __init__(self, rangelist, strides, order):
29 self.strides = strides
30 self.order = order
31 TimSort.__init__(self, rangelist)
32
33 def lt(self, a, b):
34 if self.order == NPY.CORDER:
35 return self.strides[a] <= self.strides[b]
36 return self.strides[a] < self.strides[b]
37
38
39 class BaseConcreteArray(object):
40 _immutable_fields_ = ['dtype?', 'storage', 'start', 'size', 'shape[*]',
41 'strides[*]', 'backstrides[*]', 'order', 'gcstruct',
42 'flags']
43 start = 0
44 parent = None
45 flags = 0
46
47 # JIT hints that length of all those arrays is a constant
48
49 def get_shape(self):
50 shape = self.shape
51 jit.hint(len(shape), promote=True)
52 return shape
53
54 def get_strides(self):
55 strides = self.strides
56 jit.hint(len(strides), promote=True)
57 return strides
58
59 def get_backstrides(self):
60 backstrides = self.backstrides
61 jit.hint(len(backstrides), promote=True)
62 return backstrides
63
64 def get_flags(self):
65 return self.flags
66
67 def getitem(self, index):
68 return self.dtype.read(self, index, 0)
69
70 def getitem_bool(self, index):
71 return self.dtype.read_bool(self, index, 0)
72
73 def setitem(self, index, value):
74 self.dtype.store(self, index, 0, value)
75
76 @jit.unroll_safe
77 def setslice(self, space, arr):
78 if arr.get_size() == 1:
79 # we can always set self[:] = scalar
80 pass
81 elif len(arr.get_shape()) > len(self.get_shape()):
82 # record arrays get one extra dimension
83 if not self.dtype.is_record() or \
84 len(arr.get_shape()) > len(self.get_shape()) + 1:
85 raise oefmt(space.w_ValueError,
86 "could not broadcast input array from shape "
87 "(%s) into shape (%s)",
88 ','.join([str(x) for x in arr.get_shape()]),
89 ','.join([str(x) for x in self.get_shape()]),
90 )
91 shape = shape_agreement(space, self.get_shape(), arr)
92 impl = arr.implementation
93 if impl.storage == self.storage:
94 impl = impl.copy(space)
95 loop.setslice(space, shape, self, impl)
96
97 def get_size(self):
98 return self.size // self.dtype.elsize
99
100 def get_storage_size(self):
101 return self.size
102
103 def reshape(self, orig_array, new_shape, order=NPY.ANYORDER):
104 # Since we got to here, prod(new_shape) == self.size
105 order = support.get_order_as_CF(self.order, order)
106 new_strides = None
107 if self.size == 0:
108 new_strides, _ = calc_strides(new_shape, self.dtype, order)
109 else:
110 if len(self.get_shape()) == 0:
111 new_strides = [self.dtype.elsize] * len(new_shape)
112 else:
113 new_strides = calc_new_strides(new_shape, self.get_shape(),
114 self.get_strides(), order)
115 if new_strides is None or len(new_strides) != len(new_shape):
116 return None
117 if new_strides is not None:
118 # We can create a view, strides somehow match up.
119 new_backstrides = calc_backstrides(new_strides, new_shape)
120 assert isinstance(orig_array, W_NDimArray) or orig_array is None
121 return SliceArray(self.start, new_strides, new_backstrides,
122 new_shape, self, orig_array)
123 return None
124
125 def get_view(self, space, orig_array, dtype, new_shape, strides=None, backstrides=None):
126 if not strides:
127 strides, backstrides = calc_strides(new_shape, dtype,
128 self.order)
129 return SliceArray(self.start, strides, backstrides, new_shape,
130 self, orig_array, dtype=dtype)
131
132 def get_real(self, space, orig_array):
133 strides = self.get_strides()
134 backstrides = self.get_backstrides()
135 if self.dtype.is_complex():
136 dtype = self.dtype.get_float_dtype(space)
137 return SliceArray(self.start, strides, backstrides,
138 self.get_shape(), self, orig_array, dtype=dtype)
139 return SliceArray(self.start, strides, backstrides,
140 self.get_shape(), self, orig_array)
141
142 def set_real(self, space, orig_array, w_value):
143 tmp = self.get_real(space, orig_array)
144 tmp.setslice(space, convert_to_array(space, w_value))
145
146 def get_imag(self, space, orig_array):
147 strides = self.get_strides()
148 backstrides = self.get_backstrides()
149 if self.dtype.is_complex():
150 dtype = self.dtype.get_float_dtype(space)
151 return SliceArray(self.start + dtype.elsize, strides, backstrides,
152 self.get_shape(), self, orig_array, dtype=dtype)
153 impl = NonWritableArray(self.get_shape(), self.dtype, self.order,
154 strides, backstrides)
155 if not self.dtype.is_flexible():
156 impl.fill(space, self.dtype.box(0))
157 return impl
158
159 def set_imag(self, space, orig_array, w_value):
160 tmp = self.get_imag(space, orig_array)
161 tmp.setslice(space, convert_to_array(space, w_value))
162
163 # -------------------- applevel get/setitem -----------------------
164
165 @jit.unroll_safe
166 def _lookup_by_index(self, space, view_w):
167 item = self.start
168 strides = self.get_strides()
169 for i, w_index in enumerate(view_w):
170 if space.isinstance_w(w_index, space.w_slice):
171 raise IndexError
172 idx = support.index_w(space, w_index)
173 if idx < 0:
174 idx = self.get_shape()[i] + idx
175 if idx < 0 or idx >= self.get_shape()[i]:
176 raise oefmt(space.w_IndexError,
177 "index %d is out of bounds for axis %d with size "
178 "%d", idx, i, self.get_shape()[i])
179 item += idx * strides[i]
180 return item
181
182 @jit.unroll_safe
183 def _lookup_by_unwrapped_index(self, space, lst):
184 item = self.start
185 shape = self.get_shape()
186 strides = self.get_strides()
187 assert len(lst) == len(shape)
188 for i, idx in enumerate(lst):
189 if idx < 0:
190 idx = shape[i] + idx
191 if idx < 0 or idx >= shape[i]:
192 raise oefmt(space.w_IndexError,
193 "index %d is out of bounds for axis %d with size "
194 "%d", idx, i, self.get_shape()[i])
195 item += idx * strides[i]
196 return item
197
198 def getitem_index(self, space, index):
199 return self.getitem(self._lookup_by_unwrapped_index(space, index))
200
201 def setitem_index(self, space, index, value):
202 self.setitem(self._lookup_by_unwrapped_index(space, index), value)
203
204 @jit.unroll_safe
205 def _single_item_index(self, space, w_idx):
206 """ Return an index of single item if possible, otherwise raises
207 IndexError
208 """
209 if (space.isinstance_w(w_idx, space.w_text) or
210 space.isinstance_w(w_idx, space.w_slice) or
211 space.is_w(w_idx, space.w_None)):
212 raise IndexError
213 if isinstance(w_idx, W_NDimArray) and not w_idx.is_scalar():
214 raise ArrayArgumentException
215 shape = self.get_shape()
216 shape_len = len(shape)
217 view_w = None
218 if space.isinstance_w(w_idx, space.w_list):
219 raise ArrayArgumentException
220 if space.isinstance_w(w_idx, space.w_tuple):
221 view_w = space.fixedview(w_idx)
222 if len(view_w) != shape_len:
223 raise IndexError
224 # check for arrays
225 for w_item in view_w:
226 if (isinstance(w_item, W_NDimArray) or
227 space.isinstance_w(w_item, space.w_list)):
228 raise ArrayArgumentException
229 elif space.is_w(w_item, space.w_Ellipsis):
230 raise IndexError
231 return self._lookup_by_index(space, view_w)
232 if shape_len == 0:
233 raise oefmt(space.w_IndexError, "too many indices for array")
234 elif shape_len > 1:
235 raise IndexError
236 idx = support.index_w(space, w_idx)
237 return self._lookup_by_index(space, [space.newint(idx)])
238
239 @jit.unroll_safe
240 def _prepare_slice_args(self, space, w_idx):
241 from pypy.module.micronumpy import boxes
242 if space.isinstance_w(w_idx, space.w_text):
243 raise oefmt(space.w_IndexError, "only integers, slices (`:`), "
244 "ellipsis (`...`), numpy.newaxis (`None`) and integer or "
245 "boolean arrays are valid indices")
246 if space.isinstance_w(w_idx, space.w_slice):
247 if len(self.get_shape()) == 0:
248 raise oefmt(space.w_ValueError, "cannot slice a 0-d array")
249 return [SliceChunk(w_idx), EllipsisChunk()]
250 elif space.isinstance_w(w_idx, space.w_int):
251 return [IntegerChunk(w_idx), EllipsisChunk()]
252 elif isinstance(w_idx, W_NDimArray) and w_idx.is_scalar():
253 w_idx = w_idx.get_scalar_value().item(space)
254 if not space.isinstance_w(w_idx, space.w_int) and \
255 not space.isinstance_w(w_idx, space.w_bool):
256 raise oefmt(space.w_IndexError,
257 "arrays used as indices must be of integer (or "
258 "boolean) type")
259 return [IntegerChunk(w_idx), EllipsisChunk()]
260 elif space.is_w(w_idx, space.w_None):
261 return [NewAxisChunk(), EllipsisChunk()]
262 result = []
263 has_ellipsis = False
264 has_filter = False
265 for w_item in space.fixedview(w_idx):
266 if space.is_w(w_item, space.w_Ellipsis):
267 if has_ellipsis:
268 # in CNumPy, this is only a deprecation warning
269 raise oefmt(space.w_ValueError,
270 "an index can only have a single Ellipsis (`...`); "
271 "replace all but one with slices (`:`).")
272 result.append(EllipsisChunk())
273 has_ellipsis = True
274 elif space.is_w(w_item, space.w_None):
275 result.append(NewAxisChunk())
276 elif space.isinstance_w(w_item, space.w_slice):
277 result.append(SliceChunk(w_item))
278 elif isinstance(w_item, W_NDimArray) and w_item.get_dtype().is_bool():
279 if has_filter:
280 # in CNumPy, the support for this is incomplete
281 raise oefmt(space.w_ValueError,
282 "an index can only have a single boolean mask; "
283 "use np.take or create a sinlge mask array")
284 has_filter = True
285 result.append(BooleanChunk(w_item))
286 elif isinstance(w_item, boxes.W_GenericBox):
287 result.append(IntegerChunk(w_item.descr_int(space)))
288 else:
289 result.append(IntegerChunk(w_item))
290 if not has_ellipsis:
291 result.append(EllipsisChunk())
292 return result
293
294 def descr_getitem(self, space, orig_arr, w_index):
295 try:
296 item = self._single_item_index(space, w_index)
297 return self.getitem(item)
298 except IndexError:
299 # not a single result
300 chunks = self._prepare_slice_args(space, w_index)
301 copy = False
302 if isinstance(chunks[0], BooleanChunk):
303 # numpy compatibility
304 copy = True
305 w_ret = new_view(space, orig_arr, chunks)
306 if copy:
307 w_ret = w_ret.descr_copy(space, space.newint(w_ret.get_order()))
308 return w_ret
309
310 def descr_setitem(self, space, orig_arr, w_index, w_value):
311 try:
312 item = self._single_item_index(space, w_index)
313 self.setitem(item, self.dtype.coerce(space, w_value))
314 except IndexError:
315 w_value = convert_to_array(space, w_value)
316 chunks = self._prepare_slice_args(space, w_index)
317 view = new_view(space, orig_arr, chunks)
318 view.implementation.setslice(space, w_value)
319
320 def transpose(self, orig_array, axes=None):
321 if len(self.get_shape()) < 2:
322 return self
323 strides = []
324 backstrides = []
325 shape = []
326 if axes is None:
327 axes = range(len(self.get_shape()) - 1, -1, -1)
328 for i in axes:
329 strides.append(self.get_strides()[i])
330 backstrides.append(self.get_backstrides()[i])
331 shape.append(self.get_shape()[i])
332 return SliceArray(self.start, strides,
333 backstrides, shape, self, orig_array)
334
335 def copy(self, space, order=NPY.ANYORDER):
336 if order == NPY.ANYORDER:
337 order = NPY.KEEPORDER
338 return self.astype(space, self.dtype, order, copy=True)
339
340 def create_iter(self, shape=None, backward_broadcast=False):
341 if shape is not None and \
342 support.product(shape) > support.product(self.get_shape()):
343 r = calculate_broadcast_strides(self.get_strides(),
344 self.get_backstrides(),
345 self.get_shape(), shape,
346 backward_broadcast)
347 i = ArrayIter(self, support.product(shape), shape, r[0], r[1])
348 else:
349 i = ArrayIter(self, self.get_size(), self.shape,
350 self.strides, self.backstrides)
351 return i, i.reset()
352
353 def swapaxes(self, space, orig_arr, axis1, axis2):
354 shape = self.get_shape()[:]
355 strides = self.get_strides()[:]
356 backstrides = self.get_backstrides()[:]
357 shape[axis1], shape[axis2] = shape[axis2], shape[axis1]
358 strides[axis1], strides[axis2] = strides[axis2], strides[axis1]
359 backstrides[axis1], backstrides[axis2] = backstrides[axis2], backstrides[axis1]
360 return W_NDimArray.new_slice(space, self.start, strides,
361 backstrides, shape, self, orig_arr)
362
363 def nonzero(self, space, index_type):
364 s = loop.count_all_true_concrete(self)
365 box = index_type.itemtype.box
366 nd = len(self.get_shape()) or 1
367 w_res = W_NDimArray.from_shape(space, [s, nd], index_type)
368 loop.nonzero(w_res, self, box)
369 w_res = w_res.implementation.swapaxes(space, w_res, 0, 1)
370 l_w = [w_res.descr_getitem(space, space.newint(d)) for d in range(nd)]
371 return space.newtuple(l_w)
372
373 ##def get_storage(self):
374 ## return self.storage
375 ## use a safer context manager
376 def __enter__(self):
377 return self.storage
378
379 def __exit__(self, typ, value, traceback):
380 keepalive_until_here(self)
381
382 def get_buffer(self, space, flags):
383 errtype = space.w_ValueError # should be BufferError, numpy does this instead
384 if ((flags & space.BUF_C_CONTIGUOUS) == space.BUF_C_CONTIGUOUS and
385 not self.flags & NPY.ARRAY_C_CONTIGUOUS):
386 raise oefmt(errtype, "ndarray is not C-contiguous")
387 if ((flags & space.BUF_F_CONTIGUOUS) == space.BUF_F_CONTIGUOUS and
388 not self.flags & NPY.ARRAY_F_CONTIGUOUS):
389 raise oefmt(errtype, "ndarray is not Fortran contiguous")
390 if ((flags & space.BUF_ANY_CONTIGUOUS) == space.BUF_ANY_CONTIGUOUS and
391 not (self.flags & NPY.ARRAY_F_CONTIGUOUS or
392 self.flags & NPY.ARRAY_C_CONTIGUOUS)):
393 raise oefmt(errtype, "ndarray is not contiguous")
394 if ((flags & space.BUF_STRIDES) != space.BUF_STRIDES and
395 not self.flags & NPY.ARRAY_C_CONTIGUOUS):
396 raise oefmt(errtype, "ndarray is not C-contiguous")
397 if ((flags & space.BUF_WRITABLE) == space.BUF_WRITABLE and
398 not self.flags & NPY.ARRAY_WRITEABLE):
399 raise oefmt(errtype, "buffer source array is read-only")
400 readonly = not (flags & space.BUF_WRITABLE) == space.BUF_WRITABLE
401 return ArrayView(self, readonly)
402
403 def astype(self, space, dtype, order, copy=True):
404 # copy the general pattern of the strides
405 # but make the array storage contiguous in memory
406 shape = self.get_shape()
407 strides = self.get_strides()
408 if order not in (NPY.KEEPORDER, NPY.FORTRANORDER, NPY.CORDER):
409 raise oefmt(space.w_ValueError, "Unknown order %d in astype", order)
410 if len(strides) == 0:
411 t_strides = []
412 backstrides = []
413 elif order in (NPY.FORTRANORDER, NPY.CORDER):
414 t_strides, backstrides = calc_strides(shape, dtype, order)
415 else:
416 indx_array = range(len(strides))
417 list_sorter = StrideSort(indx_array, strides, self.order)
418 list_sorter.sort()
419 t_elsize = dtype.elsize
420 t_strides = strides[:]
421 base = dtype.elsize
422 for i in indx_array:
423 t_strides[i] = base
424 base *= shape[i]
425 backstrides = calc_backstrides(t_strides, shape)
426 order = support.get_order_as_CF(self.order, order)
427 impl = ConcreteArray(shape, dtype, order, t_strides, backstrides)
428 if copy:
429 loop.setslice(space, impl.get_shape(), impl, self)
430 return impl
431
432 OBJECTSTORE = lltype.GcStruct('ObjectStore',
433 ('length', lltype.Signed),
434 ('step', lltype.Signed),
435 ('storage', llmemory.Address),
436 rtti=True)
437 offset_of_storage = llmemory.offsetof(OBJECTSTORE, 'storage')
438 offset_of_length = llmemory.offsetof(OBJECTSTORE, 'length')
439 offset_of_step = llmemory.offsetof(OBJECTSTORE, 'step')
440
441 V_OBJECTSTORE = lltype.nullptr(OBJECTSTORE)
442
443 def customtrace(gc, obj, callback, arg1, arg2):
444 #debug_print('in customtrace w/obj', obj)
445 length = (obj + offset_of_length).signed[0]
446 step = (obj + offset_of_step).signed[0]
447 storage = (obj + offset_of_storage).address[0]
448 #debug_print('tracing', length, 'objects in ndarray.storage')
449 i = 0
450 while i < length:
451 gc._trace_callback(callback, arg1, arg2, storage)
452 storage += step
453 i += 1
454
455 lambda_customtrace = lambda: customtrace
456
457 def _setup():
458 rgc.register_custom_trace_hook(OBJECTSTORE, lambda_customtrace)
459
460 @jit.dont_look_inside
461 def _create_objectstore(storage, length, elsize):
462 gcstruct = lltype.malloc(OBJECTSTORE)
463 # JIT does not support cast_ptr_to_adr
464 gcstruct.storage = llmemory.cast_ptr_to_adr(storage)
465 #print 'create gcstruct',gcstruct,'with storage',storage,'as',gcstruct.storage
466 gcstruct.length = length
467 gcstruct.step = elsize
468 return gcstruct
469
470
471 class ConcreteArrayNotOwning(BaseConcreteArray):
472 def __init__(self, shape, dtype, order, strides, backstrides, storage, start=0):
473 make_sure_not_resized(shape)
474 make_sure_not_resized(strides)
475 make_sure_not_resized(backstrides)
476 self.shape = shape
477 # already tested for overflow in from_shape_and_storage
478 self.size = support.product(shape) * dtype.elsize
479 if order not in (NPY.CORDER, NPY.FORTRANORDER):
480 raise oefmt(dtype.itemtype.space.w_ValueError, "ConcreteArrayNotOwning but order is not 0,1 rather %d", order)
481 self.order = order
482 self.dtype = dtype
483 self.strides = strides
484 self.backstrides = backstrides
485 self.storage = storage
486 self.start = start
487 self.gcstruct = V_OBJECTSTORE
488
489 def fill(self, space, box):
490 self.dtype.itemtype.fill(
491 self.storage, self.dtype.elsize, self.dtype.is_native(),
492 box, 0, self.size, 0, self.gcstruct)
493
494 def set_shape(self, space, orig_array, new_shape):
495 if len(new_shape) > NPY.MAXDIMS:
496 raise oefmt(space.w_ValueError,
497 "sequence too large; cannot be greater than %d", NPY.MAXDIMS)
498 try:
499 ovfcheck(support.product_check(new_shape) * self.dtype.elsize)
500 except OverflowError as e:
501 raise oefmt(space.w_ValueError, "array is too big.")
502 strides, backstrides = calc_strides(new_shape, self.dtype,
503 self.order)
504 return SliceArray(self.start, strides, backstrides, new_shape, self,
505 orig_array)
506
507 def set_dtype(self, space, dtype):
508 # size/shape/strides shouldn't change
509 assert dtype.elsize == self.dtype.elsize
510 self.dtype = dtype
511
512 def argsort(self, space, w_axis):
513 from .selection import argsort_array
514 return argsort_array(self, space, w_axis)
515
516 def sort(self, space, w_axis, w_order):
517 from .selection import sort_array
518 return sort_array(self, space, w_axis, w_order)
519
520 def base(self):
521 return None
522
523 class ConcreteArray(ConcreteArrayNotOwning):
524 def __init__(self, shape, dtype, order, strides, backstrides,
525 storage=lltype.nullptr(RAW_STORAGE), zero=True):
526 gcstruct = V_OBJECTSTORE
527 flags = NPY.ARRAY_ALIGNED | NPY.ARRAY_WRITEABLE
528 try:
529 length = support.product_check(shape)
530 self.size = ovfcheck(length * dtype.elsize)
531 except OverflowError:
532 raise oefmt(dtype.itemtype.space.w_ValueError, "array is too big.")
533 if storage == lltype.nullptr(RAW_STORAGE):
534 if dtype.num == NPY.OBJECT:
535 storage = dtype.itemtype.malloc(length * dtype.elsize, zero=True)
536 gcstruct = _create_objectstore(storage, length, dtype.elsize)
537 else:
538 storage = dtype.itemtype.malloc(length * dtype.elsize, zero=zero)
539 flags |= NPY.ARRAY_OWNDATA
540 start = calc_start(shape, strides)
541 ConcreteArrayNotOwning.__init__(self, shape, dtype, order, strides, backstrides,
542 storage, start=start)
543 self.gcstruct = gcstruct
544 if is_c_contiguous(self):
545 flags |= NPY.ARRAY_C_CONTIGUOUS
546 if is_f_contiguous(self):
547 flags |= NPY.ARRAY_F_CONTIGUOUS
548 self.flags = flags
549
550 def __del__(self):
551 if self.gcstruct:
552 self.gcstruct.length = 0
553 free_raw_storage(self.storage, track_allocation=False)
554
555
556 class ConcreteArrayWithBase(ConcreteArrayNotOwning):
557 def __init__(self, shape, dtype, order, strides, backstrides, storage,
558 orig_base, start=0):
559 ConcreteArrayNotOwning.__init__(self, shape, dtype, order,
560 strides, backstrides, storage, start)
561 self.orig_base = orig_base
562 if isinstance(orig_base, W_NumpyObject):
563 flags = orig_base.get_flags() & NPY.ARRAY_ALIGNED
564 flags |= orig_base.get_flags() & NPY.ARRAY_WRITEABLE
565 else:
566 flags = 0
567 if is_c_contiguous(self):
568 flags |= NPY.ARRAY_C_CONTIGUOUS
569 if is_f_contiguous(self):
570 flags |= NPY.ARRAY_F_CONTIGUOUS
571 self.flags = flags
572
573 def base(self):
574 return self.orig_base
575
576
577 class ConcreteNonWritableArrayWithBase(ConcreteArrayWithBase):
578 def __init__(self, shape, dtype, order, strides, backstrides, storage,
579 orig_base, start=0):
580 ConcreteArrayWithBase.__init__(self, shape, dtype, order, strides,
581 backstrides, storage, orig_base, start)
582 self.flags &= ~ NPY.ARRAY_WRITEABLE
583
584 def descr_setitem(self, space, orig_array, w_index, w_value):
585 raise oefmt(space.w_ValueError, "assignment destination is read-only")
586
587
588 class NonWritableArray(ConcreteArray):
589 def __init__(self, shape, dtype, order, strides, backstrides,
590 storage=lltype.nullptr(RAW_STORAGE), zero=True):
591 ConcreteArray.__init__(self, shape, dtype, order, strides, backstrides,
592 storage, zero)
593 self.flags &= ~ NPY.ARRAY_WRITEABLE
594
595 def descr_setitem(self, space, orig_array, w_index, w_value):
596 raise oefmt(space.w_ValueError, "assignment destination is read-only")
597
598
599 class SliceArray(BaseConcreteArray):
600 def __init__(self, start, strides, backstrides, shape, parent, orig_arr,
601 dtype=None):
602 self.strides = strides
603 self.backstrides = backstrides
604 self.shape = shape
605 if dtype is None:
606 dtype = parent.dtype
607 if isinstance(parent, SliceArray):
608 parent = parent.parent # one level only
609 self.parent = parent
610 self.storage = parent.storage
611 self.gcstruct = parent.gcstruct
612 if parent.order not in (NPY.CORDER, NPY.FORTRANORDER):
613 raise oefmt(dtype.itemtype.space.w_ValueError, "SliceArray but parent order is not 0,1 rather %d", parent.order)
614 self.order = parent.order
615 self.dtype = dtype
616 try:
617 self.size = ovfcheck(support.product_check(shape) * self.dtype.elsize)
618 except OverflowError:
619 raise oefmt(dtype.itemtype.space.w_ValueError, "array is too big.")
620 self.start = start
621 self.orig_arr = orig_arr
622 flags = parent.flags & NPY.ARRAY_ALIGNED
623 flags |= parent.flags & NPY.ARRAY_WRITEABLE
624 if is_c_contiguous(self):
625 flags |= NPY.ARRAY_C_CONTIGUOUS
626 if is_f_contiguous(self):
627 flags |= NPY.ARRAY_F_CONTIGUOUS
628 self.flags = flags
629
630 def base(self):
631 return self.orig_arr
632
633 def fill(self, space, box):
634 loop.fill(self, box.convert_to(space, self.dtype))
635
636 def set_shape(self, space, orig_array, new_shape):
637 if len(new_shape) > NPY.MAXDIMS:
638 raise oefmt(space.w_ValueError,
639 "sequence too large; cannot be greater than %d", NPY.MAXDIMS)
640 try:
641 ovfcheck(support.product_check(new_shape) * self.dtype.elsize)
642 except OverflowError as e:
643 raise oefmt(space.w_ValueError, "array is too big.")
644 if len(self.get_shape()) < 2 or self.size == 0:
645 # TODO: this code could be refactored into calc_strides
646 # but then calc_strides would have to accept a stepping factor
647 strides = []
648 backstrides = []
649 dtype = self.dtype
650 try:
651 s = self.get_strides()[0] // dtype.elsize
652 except IndexError:
653 s = 1
654 if self.order != NPY.FORTRANORDER:
655 new_shape.reverse()
656 for sh in new_shape:
657 strides.append(s * dtype.elsize)
658 backstrides.append(s * (sh - 1) * dtype.elsize)
659 s *= max(1, sh)
660 if self.order != NPY.FORTRANORDER:
661 strides.reverse()
662 backstrides.reverse()
663 new_shape.reverse()
664 return self.__class__(self.start, strides, backstrides, new_shape,
665 self, orig_array)
666 new_strides = calc_new_strides(new_shape, self.get_shape(),
667 self.get_strides(),
668 self.order)
669 if new_strides is None or len(new_strides) != len(new_shape):
670 raise oefmt(space.w_AttributeError,
671 "incompatible shape for a non-contiguous array")
672 new_backstrides = [0] * len(new_shape)
673 for nd in range(len(new_shape)):
674 new_backstrides[nd] = (new_shape[nd] - 1) * new_strides[nd]
675 return self.__class__(self.start, new_strides, new_backstrides, new_shape,
676 self, orig_array)
677
678 def sort(self, space, w_axis, w_order):
679 from .selection import sort_array
680 return sort_array(self, space, w_axis, w_order)
681
682 class NonWritableSliceArray(SliceArray):
683 def __init__(self, start, strides, backstrides, shape, parent, orig_arr,
684 dtype=None):
685 SliceArray.__init__(self, start, strides, backstrides, shape, parent,
686 orig_arr, dtype)
687 self.flags &= ~NPY.ARRAY_WRITEABLE
688
689 def descr_setitem(self, space, orig_array, w_index, w_value):
690 raise oefmt(space.w_ValueError, "assignment destination is read-only")
691
692
693 class VoidBoxStorage(BaseConcreteArray):
694 def __init__(self, size, dtype):
695 self.storage = alloc_raw_storage(size)
696 self.gcstruct = V_OBJECTSTORE
697 self.dtype = dtype
698 self.size = size
699 self.flags = (NPY.ARRAY_C_CONTIGUOUS | NPY.ARRAY_F_CONTIGUOUS |
700 NPY.ARRAY_WRITEABLE | NPY.ARRAY_ALIGNED)
701
702 def __del__(self):
703 free_raw_storage(self.storage)
704
705
706 class ArrayData(RawBuffer):
707 _immutable_ = True
708 def __init__(self, impl, readonly):
709 self.impl = impl
710 self.readonly = readonly
711
712 def getitem(self, index):
713 return raw_storage_getitem(lltype.Char, self.impl.storage,
714 index + self.impl.start)
715
716 def setitem(self, index, v):
717 # XXX what if self.readonly?
718 raw_storage_setitem(self.impl.storage, index + self.impl.start,
719 rffi.cast(lltype.Char, v))
720
721 def getlength(self):
722 return self.impl.size - self.impl.start
723
724 def get_raw_address(self):
725 from rpython.rtyper.lltypesystem import rffi
726 return rffi.ptradd(self.impl.storage, self.impl.start)
727
728
729 class ArrayView(BufferView):
730 _immutable_ = True
731
732 def __init__(self, impl, readonly):
733 self.impl = impl
734 self.readonly = readonly
735 self.data = ArrayData(impl, readonly)
736
737 def getlength(self):
738 return self.data.getlength()
739
740 def getbytes(self, start, size):
741 return self.data[start:start + size]
742
743 def as_readbuf(self):
744 return ArrayData(self.impl, readonly=True)
745
746 def as_writebuf(self):
747 assert not self.readonly
748 return ArrayData(self.impl, readonly=False)
749
750 def getformat(self):
751 sb = StringBuilder()
752 self.impl.dtype.getformat(sb)
753 return sb.build()
754
755 def getitemsize(self):
756 return self.impl.dtype.elsize
757
758 def getndim(self):
759 return len(self.impl.shape)
760
761 def getshape(self):
762 return self.impl.shape
763
764 def getstrides(self):
765 return self.impl.strides
766
767 def get_raw_address(self):
768 return self.data.get_raw_address()