Debian Codegraph @

pypy/module/micronumpy/selection.py

raw symbols SCIP
1 from pypy.interpreter.error import oefmt
2 from rpython.rlib.listsort import make_timsort_class
3 from rpython.rlib.objectmodel import specialize
4 from rpython.rlib.rarithmetic import widen
5 from rpython.rlib.rawstorage import raw_storage_getitem, raw_storage_setitem, \
6 free_raw_storage, alloc_raw_storage
7 from rpython.rlib.unroll import unrolling_iterable
8 from rpython.rtyper.lltypesystem import rffi, lltype
9 from pypy.module.micronumpy import descriptor, types, constants as NPY
10 from pypy.module.micronumpy.base import W_NDimArray
11 from pypy.module.micronumpy.iterators import AllButAxisIter
12
13 INT_SIZE = rffi.sizeof(lltype.Signed)
14
15 all_types = (types.all_float_types + types.all_complex_types +
16 types.all_int_types)
17 all_types = [i for i in all_types if not issubclass(i[0], types.Float16)]
18 all_types = unrolling_iterable(all_types)
19
20
21 def make_argsort_function(space, itemtype, comp_type, count=1):
22 TP = itemtype.T
23 step = rffi.sizeof(TP)
24
25 class Repr(object):
26 def __init__(self, index_stride_size, stride_size, size, values,
27 indexes, index_start, start):
28 self.index_stride_size = index_stride_size
29 self.stride_size = stride_size
30 self.index_start = index_start
31 self.start = start
32 self.size = size
33 self.values = values
34 self.indexes = indexes
35
36 def getitem(self, idx):
37 if count < 2:
38 v = raw_storage_getitem(TP, self.values, idx * self.stride_size
39 + self.start)
40 else:
41 v = []
42 for i in range(count):
43 _v = raw_storage_getitem(TP, self.values, idx * self.stride_size
44 + self.start + step * i)
45 v.append(_v)
46 if comp_type == 'int':
47 v = widen(v)
48 elif comp_type == 'float':
49 v = float(v)
50 elif comp_type == 'complex':
51 v = [float(v[0]),float(v[1])]
52 else:
53 raise NotImplementedError('cannot reach')
54 return (v, raw_storage_getitem(lltype.Signed, self.indexes,
55 idx * self.index_stride_size +
56 self.index_start))
57
58 def setitem(self, idx, item):
59 if count < 2:
60 raw_storage_setitem(self.values, idx * self.stride_size +
61 self.start, rffi.cast(TP, item[0]))
62 else:
63 i = 0
64 for val in item[0]:
65 raw_storage_setitem(self.values, idx * self.stride_size +
66 self.start + i*step, rffi.cast(TP, val))
67 i += 1
68 raw_storage_setitem(self.indexes, idx * self.index_stride_size +
69 self.index_start, item[1])
70
71 class ArgArrayRepWithStorage(Repr):
72 def __init__(self, index_stride_size, stride_size, size):
73 start = 0
74 dtype = descriptor.get_dtype_cache(space).w_longdtype
75 indexes = dtype.itemtype.malloc(size * dtype.elsize)
76 values = alloc_raw_storage(size * stride_size,
77 track_allocation=False)
78 Repr.__init__(self, dtype.elsize, stride_size,
79 size, values, indexes, start, start)
80
81 def __del__(self):
82 free_raw_storage(self.indexes, track_allocation=False)
83 free_raw_storage(self.values, track_allocation=False)
84
85 def arg_getitem(lst, item):
86 return lst.getitem(item)
87
88 def arg_setitem(lst, item, value):
89 lst.setitem(item, value)
90
91 def arg_length(lst):
92 return lst.size
93
94 def arg_getitem_slice(lst, start, stop):
95 retval = ArgArrayRepWithStorage(lst.index_stride_size, lst.stride_size,
96 stop-start)
97 for i in range(stop-start):
98 retval.setitem(i, lst.getitem(i+start))
99 return retval
100
101 if count < 2:
102 def arg_lt(a, b):
103 # Does numpy do <= ?
104 return a[0] < b[0] or b[0] != b[0] and a[0] == a[0]
105 else:
106 def arg_lt(a, b):
107 for i in range(count):
108 if b[0][i] != b[0][i] and a[0][i] == a[0][i]:
109 return True
110 elif b[0][i] == b[0][i] and a[0][i] != a[0][i]:
111 return False
112 for i in range(count):
113 if a[0][i] < b[0][i]:
114 return True
115 elif a[0][i] > b[0][i]:
116 return False
117 # Does numpy do True?
118 return False
119
120 ArgSort = make_timsort_class(arg_getitem, arg_setitem, arg_length,
121 arg_getitem_slice, arg_lt)
122
123 def argsort(arr, space, w_axis):
124 if w_axis is space.w_None:
125 # note that it's fine ot pass None here as we're not going
126 # to pass the result around (None is the link to base in slices)
127 if arr.get_size() > 0:
128 arr = arr.reshape(None, [arr.get_size()])
129 axis = 0
130 elif w_axis is None:
131 axis = -1
132 else:
133 axis = space.int_w(w_axis)
134 # create array of indexes
135 dtype = descriptor.get_dtype_cache(space).w_longdtype
136 index_arr = W_NDimArray.from_shape(space, arr.get_shape(), dtype)
137 with index_arr.implementation as storage, arr as arr_storage:
138 if len(arr.get_shape()) == 1:
139 for i in range(arr.get_size()):
140 raw_storage_setitem(storage, i * INT_SIZE, i)
141 r = Repr(INT_SIZE, arr.strides[0], arr.get_size(), arr_storage,
142 storage, 0, arr.start)
143 ArgSort(r).sort()
144 else:
145 shape = arr.get_shape()
146 if axis < 0:
147 axis = len(shape) + axis
148 if axis < 0 or axis >= len(shape):
149 raise oefmt(space.w_IndexError, "Wrong axis %d", axis)
150 arr_iter = AllButAxisIter(arr, axis)
151 arr_state = arr_iter.reset()
152 index_impl = index_arr.implementation
153 index_iter = AllButAxisIter(index_impl, axis)
154 index_state = index_iter.reset()
155 stride_size = arr.strides[axis]
156 index_stride_size = index_impl.strides[axis]
157 axis_size = arr.shape[axis]
158 while not arr_iter.done(arr_state):
159 for i in range(axis_size):
160 raw_storage_setitem(storage, i * index_stride_size +
161 index_state.offset, i)
162 r = Repr(index_stride_size, stride_size, axis_size,
163 arr_storage, storage, index_state.offset, arr_state.offset)
164 ArgSort(r).sort()
165 arr_state = arr_iter.next(arr_state)
166 index_state = index_iter.next(index_state)
167 return index_arr
168
169 return argsort
170
171
172 def argsort_array(arr, space, w_axis):
173 cache = space.fromcache(ArgSortCache) # that populates ArgSortClasses
174 itemtype = arr.dtype.itemtype
175 for tp in all_types:
176 if isinstance(itemtype, tp[0]):
177 return cache._lookup(tp)(arr, space, w_axis)
178 # XXX this should probably be changed
179 raise oefmt(space.w_NotImplementedError,
180 "sorting of non-numeric types '%s' is not implemented",
181 arr.dtype.get_name())
182
183
184 def make_sort_function(space, itemtype, comp_type, count=1):
185 TP = itemtype.T
186 step = rffi.sizeof(TP)
187
188 class Repr(object):
189 def __init__(self, stride_size, size, values, start):
190 self.stride_size = stride_size
191 self.start = start
192 self.size = size
193 self.values = values
194
195 def getitem(self, item):
196 if count < 2:
197 v = raw_storage_getitem(TP, self.values, item * self.stride_size
198 + self.start)
199 else:
200 v = []
201 for i in range(count):
202 _v = raw_storage_getitem(TP, self.values, item * self.stride_size
203 + self.start + step * i)
204 v.append(_v)
205 if comp_type == 'int':
206 v = widen(v)
207 elif comp_type == 'float':
208 v = float(v)
209 elif comp_type == 'complex':
210 v = [float(v[0]),float(v[1])]
211 else:
212 raise NotImplementedError('cannot reach')
213 return (v)
214
215 def setitem(self, idx, item):
216 if count < 2:
217 raw_storage_setitem(self.values, idx * self.stride_size +
218 self.start, rffi.cast(TP, item))
219 else:
220 i = 0
221 for val in item:
222 raw_storage_setitem(self.values, idx * self.stride_size +
223 self.start + i*step, rffi.cast(TP, val))
224 i += 1
225
226 class ArgArrayRepWithStorage(Repr):
227 def __init__(self, stride_size, size):
228 start = 0
229 values = alloc_raw_storage(size * stride_size,
230 track_allocation=False)
231 Repr.__init__(self, stride_size,
232 size, values, start)
233
234 def __del__(self):
235 free_raw_storage(self.values, track_allocation=False)
236
237 def arg_getitem(lst, item):
238 return lst.getitem(item)
239
240 def arg_setitem(lst, item, value):
241 lst.setitem(item, value)
242
243 def arg_length(lst):
244 return lst.size
245
246 def arg_getitem_slice(lst, start, stop):
247 retval = ArgArrayRepWithStorage(lst.stride_size, stop-start)
248 for i in range(stop-start):
249 retval.setitem(i, lst.getitem(i+start))
250 return retval
251
252 if count < 2:
253 def arg_lt(a, b):
254 # handles NAN and INF
255 return a < b or b != b and a == a
256 else:
257 def arg_lt(a, b):
258 for i in range(count):
259 if b[i] != b[i] and a[i] == a[i]:
260 return True
261 elif b[i] == b[i] and a[i] != a[i]:
262 return False
263 for i in range(count):
264 if a[i] < b[i]:
265 return True
266 elif a[i] > b[i]:
267 return False
268 # Does numpy do True?
269 return False
270
271 ArgSort = make_timsort_class(arg_getitem, arg_setitem, arg_length,
272 arg_getitem_slice, arg_lt)
273
274 def sort(arr, space, w_axis):
275 if w_axis is space.w_None:
276 # note that it's fine to pass None here as we're not going
277 # to pass the result around (None is the link to base in slices)
278 arr = arr.reshape(None, [arr.get_size()])
279 axis = 0
280 elif w_axis is None:
281 axis = -1
282 else:
283 axis = space.int_w(w_axis)
284 with arr as storage:
285 if len(arr.get_shape()) == 1:
286 r = Repr(arr.strides[0], arr.get_size(), storage,
287 arr.start)
288 ArgSort(r).sort()
289 else:
290 shape = arr.get_shape()
291 if axis < 0:
292 axis = len(shape) + axis
293 if axis < 0 or axis >= len(shape):
294 raise oefmt(space.w_IndexError, "Wrong axis %d", axis)
295 arr_iter = AllButAxisIter(arr, axis)
296 arr_state = arr_iter.reset()
297 stride_size = arr.strides[axis]
298 axis_size = arr.shape[axis]
299 while not arr_iter.done(arr_state):
300 r = Repr(stride_size, axis_size, storage, arr_state.offset)
301 ArgSort(r).sort()
302 arr_state = arr_iter.next(arr_state)
303
304 return sort
305
306
307 def sort_array(arr, space, w_axis, w_order):
308 cache = space.fromcache(SortCache) # that populates SortClasses
309 itemtype = arr.dtype.itemtype
310 if arr.dtype.byteorder == NPY.OPPBYTE:
311 raise oefmt(space.w_NotImplementedError,
312 "sorting of non-native byteorder not supported yet")
313 for tp in all_types:
314 if isinstance(itemtype, tp[0]):
315 return cache._lookup(tp)(arr, space, w_axis)
316 # XXX this should probably be changed
317 raise oefmt(space.w_NotImplementedError,
318 "sorting of non-numeric types '%s' is not implemented",
319 arr.dtype.get_name())
320
321
322 class ArgSortCache(object):
323 built = False
324
325 def __init__(self, space):
326 if self.built:
327 return
328 self.built = True
329 cache = {}
330 for cls, it in all_types._items:
331 if it == 'complex':
332 cache[cls] = make_argsort_function(space, cls, it, 2)
333 else:
334 cache[cls] = make_argsort_function(space, cls, it)
335 self.cache = cache
336 self._lookup = specialize.memo()(lambda tp: cache[tp[0]])
337
338
339 class SortCache(object):
340 built = False
341
342 def __init__(self, space):
343 if self.built:
344 return
345 self.built = True
346 cache = {}
347 for cls, it in all_types._items:
348 if it == 'complex':
349 cache[cls] = make_sort_function(space, cls, it, 2)
350 else:
351 cache[cls] = make_sort_function(space, cls, it)
352 self.cache = cache
353 self._lookup = specialize.memo()(lambda tp: cache[tp[0]])