Debian Codegraph @

pypy/module/micronumpy/strides.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from rpython.rlib import jit
3 from pypy.module.micronumpy import constants as NPY
4 from pypy.module.micronumpy.base import W_NDimArray
5
6
7 # structures to describe slicing
8
9 class BaseChunk(object):
10 _attrs_ = ['step', 'out_dim']
11
12
13 class Chunk(BaseChunk):
14 input_dim = 1
15
16 def __init__(self, start, stop, step, lgt):
17 self.start = start
18 self.stop = stop
19 self.step = step
20 self.lgt = lgt
21 if self.step == 0:
22 self.out_dim = 0
23 else:
24 self.out_dim = 1
25
26 def compute(self, space, base_length, base_stride):
27 stride = base_stride * self.step
28 backstride = base_stride * max(0, self.lgt - 1) * self.step
29 return self.start, self.lgt, stride, backstride
30
31 def __repr__(self):
32 return 'Chunk(%d, %d, %d, %d)' % (self.start, self.stop, self.step,
33 self.lgt)
34
35 class IntegerChunk(BaseChunk):
36 input_dim = 1
37 out_dim = 0
38
39 def __init__(self, w_idx):
40 self.w_idx = w_idx
41
42 def compute(self, space, base_length, base_stride):
43 start, _, _, _ = space.decode_index4_unsafe(self.w_idx, base_length)
44 return start, 0, 0, 0
45
46
47 class SliceChunk(BaseChunk):
48 input_dim = 1
49 out_dim = 1
50
51 def __init__(self, w_slice):
52 self.w_slice = w_slice
53
54 def compute(self, space, base_length, base_stride):
55 start, stop, step, length = space.decode_index4_unsafe(self.w_slice, base_length)
56 stride = base_stride * step
57 backstride = base_stride * max(0, length - 1) * step
58 return start, length, stride, backstride
59
60 class NewAxisChunk(Chunk):
61 input_dim = 0
62 out_dim = 1
63
64 def __init__(self):
65 pass
66
67 def compute(self, space, base_length, base_stride):
68 return 0, 1, 0, 0
69
70 class EllipsisChunk(BaseChunk):
71 input_dim = 0
72 out_dim = 0
73
74 def __init__(self):
75 pass
76
77 def compute(self, space, base_length, base_stride):
78 backstride = base_stride * max(0, base_length - 1)
79 return 0, base_length, base_stride, backstride
80
81 class BooleanChunk(BaseChunk):
82 input_dim = 1
83 out_dim = 1
84
85 def __init__(self, w_idx):
86 self.w_idx = w_idx
87
88 def compute(self, space, base_length, base_stride):
89 raise oefmt(space.w_NotImplementedError, 'cannot reach')
90
91 def new_view(space, w_arr, chunks):
92 arr = w_arr.implementation
93 dim = -1
94 for i, c in enumerate(chunks):
95 if isinstance(c, BooleanChunk):
96 dim = i
97 break
98 if dim >= 0:
99 # filter by axis dim
100 filtr = chunks[dim]
101 assert isinstance(filtr, BooleanChunk)
102 # XXX this creates a new array, and fails in setitem
103 w_arr = w_arr.getitem_filter(space, filtr.w_idx, axis=dim)
104 arr = w_arr.implementation
105 chunks[dim] = SliceChunk(space.newslice(space.newint(0),
106 space.w_None, space.w_None))
107 r = calculate_slice_strides(space, arr.shape, arr.start,
108 arr.get_strides(), arr.get_backstrides(), chunks)
109 else:
110 r = calculate_slice_strides(space, arr.shape, arr.start,
111 arr.get_strides(), arr.get_backstrides(), chunks)
112 shape, start, strides, backstrides = r
113 return W_NDimArray.new_slice(space, start, strides[:], backstrides[:],
114 shape[:], arr, w_arr)
115
116 @jit.unroll_safe
117 def _extend_shape(old_shape, chunks):
118 shape = []
119 i = -1
120 for i, c in enumerate_chunks(chunks):
121 if c.out_dim > 0:
122 shape.append(c.lgt)
123 s = i + 1
124 assert s >= 0
125 return shape[:] + old_shape[s:]
126
127
128 class BaseTransform(object):
129 pass
130
131
132 class ViewTransform(BaseTransform):
133 def __init__(self, chunks):
134 # 4-tuple specifying slicing
135 self.chunks = chunks
136
137
138 class BroadcastTransform(BaseTransform):
139 def __init__(self, res_shape):
140 self.res_shape = res_shape
141
142
143 @jit.look_inside_iff(lambda chunks: jit.isconstant(len(chunks)))
144 def enumerate_chunks(chunks):
145 result = []
146 i = -1
147 for chunk in chunks:
148 i += chunk.input_dim
149 result.append((i, chunk))
150 return result
151
152
153 @jit.look_inside_iff(lambda space, shape, start, strides, backstrides, chunks:
154 jit.isconstant(len(chunks)))
155 def calculate_slice_strides(space, shape, start, strides, backstrides, chunks):
156 """
157 Note: `chunks` can contain at most one EllipsisChunk object.
158 """
159 size = 0
160 used_dims = 0
161 for chunk in chunks:
162 used_dims += chunk.input_dim
163 size += chunk.out_dim
164 if used_dims > len(shape):
165 raise oefmt(space.w_IndexError, "too many indices for array")
166 else:
167 extra_dims = len(shape) - used_dims
168 rstrides = [0] * (size + extra_dims)
169 rbackstrides = [0] * (size + extra_dims)
170 rshape = [0] * (size + extra_dims)
171 rstart = start
172 i = 0 # index of the current dimension in the input array
173 j = 0 # index of the current dimension in the result view
174 for chunk in chunks:
175 if isinstance(chunk, NewAxisChunk):
176 rshape[j] = 1
177 j += 1
178 continue
179 elif isinstance(chunk, EllipsisChunk):
180 for k in range(extra_dims):
181 start, length, stride, backstride = chunk.compute(
182 space, shape[i], strides[i])
183 rshape[j] = length
184 rstrides[j] = stride
185 rbackstrides[j] = backstride
186 j += 1
187 i += 1
188 continue
189 start, length, stride, backstride = chunk.compute(space, shape[i], strides[i])
190 if chunk.out_dim == 1:
191 rshape[j] = length
192 rstrides[j] = stride
193 rbackstrides[j] = backstride
194 j += chunk.out_dim
195 rstart += strides[i] * start
196 i += chunk.input_dim
197 return rshape, rstart, rstrides, rbackstrides
198
199
200 def calculate_broadcast_strides(strides, backstrides, orig_shape, res_shape, backwards=False):
201 rstrides = []
202 rbackstrides = []
203 for i in range(len(orig_shape)):
204 if orig_shape[i] == 1:
205 rstrides.append(0)
206 rbackstrides.append(0)
207 else:
208 rstrides.append(strides[i])
209 rbackstrides.append(backstrides[i])
210 if backwards:
211 rstrides = rstrides + [0] * (len(res_shape) - len(orig_shape))
212 rbackstrides = rbackstrides + [0] * (len(res_shape) - len(orig_shape))
213 else:
214 rstrides = [0] * (len(res_shape) - len(orig_shape)) + rstrides
215 rbackstrides = [0] * (len(res_shape) - len(orig_shape)) + rbackstrides
216 return rstrides, rbackstrides
217
218
219 @jit.unroll_safe
220 def shape_agreement(space, shape1, w_arr2, broadcast_down=True):
221 if w_arr2 is None:
222 return shape1
223 assert isinstance(w_arr2, W_NDimArray)
224 shape2 = w_arr2.get_shape()
225 ret = _shape_agreement(shape1, shape2)
226 if len(ret) < max(len(shape1), len(shape2)):
227 def format_shape(shape):
228 if len(shape) > 1:
229 return ",".join([str(x) for x in shape])
230 else:
231 return '%d,' % shape[0]
232 raise oefmt(space.w_ValueError,
233 "operands could not be broadcast together with shapes "
234 "(%s) (%s)", format_shape(shape1), format_shape(shape2))
235 if not broadcast_down and len([x for x in ret if x != 1]) > len([x for x in shape2 if x != 1]):
236 raise oefmt(space.w_ValueError,
237 "unbroadcastable shape (%s) cannot be broadcasted to (%s)",
238 ",".join([str(x) for x in shape1]),
239 ",".join([str(x) for x in shape2])
240 )
241 return ret
242
243
244 @jit.unroll_safe
245 def shape_agreement_multiple(space, array_list, shape=None):
246 """ call shape_agreement recursively, allow elements from array_list to
247 be None (like w_out)
248 """
249 for arr in array_list:
250 if not space.is_none(arr):
251 if shape is None:
252 shape = arr.get_shape()
253 else:
254 shape = shape_agreement(space, shape, arr)
255 return shape
256
257 @jit.unroll_safe
258 def _shape_agreement(shape1, shape2):
259 """ Checks agreement about two shapes with respect to broadcasting. Returns
260 the resulting shape.
261 """
262 lshift = 0
263 rshift = 0
264 if len(shape1) > len(shape2):
265 m = len(shape1)
266 n = len(shape2)
267 rshift = len(shape2) - len(shape1)
268 remainder = shape1
269 else:
270 m = len(shape2)
271 n = len(shape1)
272 lshift = len(shape1) - len(shape2)
273 remainder = shape2
274 endshape = [0] * m
275 indices1 = [True] * m
276 indices2 = [True] * m
277 for i in range(m - 1, m - n - 1, -1):
278 left = shape1[i + lshift]
279 right = shape2[i + rshift]
280 if left == right:
281 endshape[i] = left
282 elif left == 1:
283 endshape[i] = right
284 indices1[i + lshift] = False
285 elif right == 1:
286 endshape[i] = left
287 indices2[i + rshift] = False
288 else:
289 return []
290 #raise oefmt(space.w_ValueError,
291 # "frames are not aligned")
292 for i in range(m - n):
293 endshape[i] = remainder[i]
294 return endshape
295
296
297 def get_shape_from_iterable(space, old_size, w_iterable):
298 new_size = 0
299 new_shape = []
300 if space.isinstance_w(w_iterable, space.w_int):
301 new_size = space.int_w(w_iterable)
302 if new_size < 0:
303 new_size = old_size
304 new_shape = [new_size]
305 else:
306 neg_dim = -1
307 batch = space.listview(w_iterable)
308 new_size = 1
309 new_shape = []
310 i = 0
311 for elem in batch:
312 s = space.int_w(elem)
313 if s < 0:
314 if neg_dim >= 0:
315 raise oefmt(space.w_ValueError,
316 "can only specify one unknown dimension")
317 s = 1
318 neg_dim = i
319 new_size *= s
320 new_shape.append(s)
321 i += 1
322 if neg_dim >= 0:
323 new_shape[neg_dim] = old_size / new_size
324 new_size *= new_shape[neg_dim]
325 if new_size != old_size:
326 raise oefmt(space.w_ValueError,
327 "total size of new array must be unchanged")
328 return new_shape
329
330
331 @jit.unroll_safe
332 def calc_strides(shape, dtype, order):
333 strides = []
334 backstrides = []
335 s = 1
336 shape_rev = shape[:]
337 if order in [NPY.CORDER, NPY.ANYORDER]:
338 shape_rev.reverse()
339 for sh in shape_rev:
340 slimit = max(sh, 1)
341 strides.append(s * dtype.elsize)
342 backstrides.append(s * (slimit - 1) * dtype.elsize)
343 s *= slimit
344 if order in [NPY.CORDER, NPY.ANYORDER]:
345 strides.reverse()
346 backstrides.reverse()
347 return strides, backstrides
348
349 @jit.unroll_safe
350 def calc_backstrides(strides, shape):
351 ndims = len(shape)
352 new_backstrides = [0] * ndims
353 for nd in range(ndims):
354 new_backstrides[nd] = (shape[nd] - 1) * strides[nd]
355 return new_backstrides
356
357 # Recalculating strides. Find the steps that the iteration does for each
358 # dimension, given the stride and shape. Then try to create a new stride that
359 # fits the new shape, using those steps. If there is a shape/step mismatch
360 # (meaning that the realignment of elements crosses from one step into another)
361 # return None so that the caller can raise an exception.
362 def calc_new_strides(new_shape, old_shape, old_strides, order):
363 # Return the proper strides for new_shape, or None if the mapping crosses
364 # stepping boundaries
365
366 # Assumes that prod(old_shape) == prod(new_shape), len(old_shape) > 1, and
367 # len(new_shape) > 0
368 steps = []
369 last_step = 1
370 oldI = 0
371 new_strides = []
372 if order == NPY.FORTRANORDER:
373 for i in range(len(old_shape)):
374 steps.append(old_strides[i] / last_step)
375 last_step *= old_shape[i]
376 cur_step = steps[0]
377 n_new_elems_used = 1
378 n_old_elems_to_use = old_shape[0]
379 for s in new_shape:
380 new_strides.append(cur_step * n_new_elems_used)
381 n_new_elems_used *= s
382 while n_new_elems_used > n_old_elems_to_use:
383 oldI += 1
384 if steps[oldI] != steps[oldI - 1]:
385 return None
386 n_old_elems_to_use *= old_shape[oldI]
387 if n_new_elems_used == n_old_elems_to_use:
388 oldI += 1
389 if oldI < len(old_shape):
390 cur_step = steps[oldI]
391 n_old_elems_to_use *= old_shape[oldI]
392 else:
393 for i in range(len(old_shape) - 1, -1, -1):
394 steps.insert(0, old_strides[i] / last_step)
395 last_step *= old_shape[i]
396 cur_step = steps[-1]
397 n_new_elems_used = 1
398 oldI = -1
399 n_old_elems_to_use = old_shape[-1]
400 for i in range(len(new_shape) - 1, -1, -1):
401 s = new_shape[i]
402 new_strides.insert(0, cur_step * n_new_elems_used)
403 n_new_elems_used *= s
404 while n_new_elems_used > n_old_elems_to_use:
405 oldI -= 1
406 if steps[oldI] != steps[oldI + 1]:
407 return None
408 n_old_elems_to_use *= old_shape[oldI]
409 if n_new_elems_used == n_old_elems_to_use:
410 oldI -= 1
411 if oldI >= -len(old_shape):
412 cur_step = steps[oldI]
413 n_old_elems_to_use *= old_shape[oldI]
414 return new_strides[:]
415
416 def calc_start(shape, strides):
417 ''' Strides can be negative for non-contiguous data.
418 Calculate the appropriate positive starting position so
419 the indexing still works properly
420 '''
421 start = 0
422 for i in range(len(shape)):
423 if strides[i] < 0:
424 start -= strides[i] * (shape[i] - 1)
425 return start
426
427 @jit.unroll_safe
428 def is_c_contiguous(arr):
429 shape = arr.get_shape()
430 strides = arr.get_strides()
431 ret = True
432 sd = arr.dtype.elsize
433 for i in range(len(shape) - 1, -1, -1):
434 dim = shape[i]
435 if strides[i] != sd:
436 ret = False
437 break
438 if dim == 0:
439 break
440 sd *= dim
441 return ret
442
443 @jit.unroll_safe
444 def is_f_contiguous(arr):
445 shape = arr.get_shape()
446 strides = arr.get_strides()
447 ret = True
448 sd = arr.dtype.elsize
449 for i in range(len(shape)):
450 dim = shape[i]
451 if strides[i] != sd:
452 ret = False
453 break
454 if dim == 0:
455 break
456 sd *= dim
457 return ret