Debian Codegraph @

pypy/module/micronumpy/test/test_selection.py

raw symbols SCIP
1 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
2
3 class AppTestSorting(BaseNumpyAppTest):
4 def test_argsort_dtypes(self):
5 from numpy import array, arange
6 assert array(2.0).argsort() == 0
7 nnp = self.non_native_prefix
8 for dtype in ['int', 'float', 'int16', 'float32', 'uint64',
9 nnp + 'i2', complex]:
10 a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
11 exp = list(a)
12 exp = sorted(range(len(exp)), key=exp.__getitem__)
13 c = a.copy()
14 res = a.argsort()
15 assert (res == exp).all(), 'Failed sortng %r\na=%r\nres=%r\nexp=%r' % (dtype,a,res,exp)
16 assert (a == c).all() # not modified
17
18 a = arange(100, dtype=dtype)
19 assert (a.argsort() == a).all()
20
21 def test_argsort_ndim(self):
22 from numpy import array
23 a = array([[4, 2], [1, 3]])
24 assert (a.argsort() == [[1, 0], [0, 1]]).all()
25 a = array(range(10) + range(10) + range(10))
26 b = a.argsort()
27 assert ((b[:3] == [0, 10, 20]).all() or
28 (b[:3] == [0, 20, 10]).all())
29 #trigger timsort 'run' mode which calls arg_getitem_slice
30 a = array(range(100) + range(100) + range(100))
31 b = a.argsort()
32 assert ((b[:3] == [0, 100, 200]).all() or
33 (b[:3] == [0, 200, 100]).all())
34 a = array([[[]]]).reshape(3,4,0)
35 b = a.argsort()
36 assert b.size == 0
37
38 def test_argsort_random(self):
39 from numpy import array
40 from _random import Random
41 rnd = Random(1)
42 a = array([rnd.random() for i in range(512*2)]).reshape(512,2)
43 a.argsort()
44
45 def test_argsort_axis(self):
46 from numpy import array
47 a = array([])
48 for axis in [None, -1, 0]:
49 assert a.argsort(axis=axis).shape == (0,)
50 a = array([[4, 2], [1, 3]])
51 assert (a.argsort(axis=None) == [2, 1, 3, 0]).all()
52 assert (a.argsort(axis=-1) == [[1, 0], [0, 1]]).all()
53 assert (a.argsort(axis=0) == [[1, 0], [0, 1]]).all()
54 assert (a.argsort(axis=1) == [[1, 0], [0, 1]]).all()
55 a = array([[3, 2, 1], [1, 2, 3]])
56 assert (a.argsort(axis=0) == [[1, 0, 0], [0, 1, 1]]).all()
57 assert (a.argsort(axis=1) == [[2, 1, 0], [0, 1, 2]]).all()
58
59 def test_sort_dtypes(self):
60 from numpy import array, arange
61 for dtype in ['int', 'float', 'int16', 'float32', 'uint64',
62 'i2', complex]:
63 a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
64 exp = sorted(list(a))
65 a.sort()
66 assert (a == exp).all(), 'Failed sorting %r\n%r\n%r' % (dtype, a, exp)
67
68 a = arange(100, dtype=dtype)
69 c = a.copy()
70 a.sort()
71 assert (a == c).all(), 'Failed sortng %r\na=%r\nc=%r' % (dtype,a,c)
72
73 def test_sort_nonnative(self):
74 from numpy import array
75 nnp = self.non_native_prefix
76 for dtype in [ nnp + 'i2']:
77 a = array([6, 4, -1, 3, 8, 3, 256+20, 100, 101], dtype=dtype)
78 b = array([-1, 3, 3, 4, 6, 8, 100, 101, 256+20], dtype=dtype)
79 c = a.copy()
80 import sys
81 if '__pypy__' in sys.builtin_module_names:
82 exc = raises(NotImplementedError, a.sort)
83 assert exc.value[0].find('supported') >= 0
84 #assert (a == b).all(), \
85 # 'a,orig,dtype %r,%r,%r' % (a,c,dtype)
86
87 def test_sort_noncontiguous(self):
88 from numpy import array
89 x = array([[2, 10], [1, 11]])
90 assert (x[:, 0].argsort() == [1, 0]).all()
91 x[:, 0].sort()
92 assert (x == [[1, 10], [2, 11]]).all()
93
94 # tests from numpy/tests/test_multiarray.py
95 def test_sort_corner_cases(self):
96 # test ordering for floats and complex containing nans. It is only
97 # necessary to check the lessthan comparison, so sorts that
98 # only follow the insertion sort path are sufficient. We only
99 # test doubles and complex doubles as the logic is the same.
100
101 # check doubles
102 from numpy import array, zeros, arange
103 from math import isnan
104 nan = float('nan')
105 a = array([nan, 1, 0])
106 b = a.copy()
107 b.sort()
108 assert [isnan(bb) for bb in b] == [isnan(aa) for aa in a[::-1]]
109 assert (b[:2] == a[::-1][:2]).all()
110
111 b = a.argsort()
112 assert (b == [2, 1, 0]).all()
113
114 # check complex
115 a = zeros(9, dtype='complex128')
116 a.real += [nan, nan, nan, 1, 0, 1, 1, 0, 0]
117 a.imag += [nan, 1, 0, nan, nan, 1, 0, 1, 0]
118 b = a.copy()
119 b.sort()
120 assert [isnan(bb) for bb in b] == [isnan(aa) for aa in a[::-1]]
121 assert (b[:4] == a[::-1][:4]).all()
122
123 b = a.argsort()
124 assert (b == [8, 7, 6, 5, 4, 3, 2, 1, 0]).all()
125
126 # all c scalar sorts use the same code with different types
127 # so it suffices to run a quick check with one type. The number
128 # of sorted items must be greater than ~50 to check the actual
129 # algorithm because quick and merge sort fall over to insertion
130 # sort for small arrays.
131 a = arange(101)
132 b = a[::-1].copy()
133 for kind in ['q', 'm', 'h'] :
134 msg = "scalar sort, kind=%s" % kind
135 c = a.copy();
136 c.sort(kind=kind)
137 assert (c == a).all(), msg
138 c = b.copy();
139 c.sort(kind=kind)
140 assert (c == a).all(), msg
141
142 # test complex sorts. These use the same code as the scalars
143 # but the compare fuction differs.
144 ai = a*1j + 1
145 bi = b*1j + 1
146 for kind in ['q', 'm', 'h'] :
147 msg = "complex sort, real part == 1, kind=%s" % kind
148 c = ai.copy();
149 c.sort(kind=kind)
150 assert (c == ai).all(), msg
151 c = bi.copy();
152 c.sort(kind=kind)
153 assert (c == ai).all(), msg
154 ai = a + 1j
155 bi = b + 1j
156 for kind in ['q', 'm', 'h'] :
157 msg = "complex sort, imag part == 1, kind=%s" % kind
158 c = ai.copy();
159 c.sort(kind=kind)
160 assert (c == ai).all(), msg
161 c = bi.copy();
162 c.sort(kind=kind)
163 assert (c == ai).all(), msg
164
165 # check axis handling. This should be the same for all type
166 # specific sorts, so we only check it for one type and one kind
167 a = array([[3, 2], [1, 0]])
168 b = array([[1, 0], [3, 2]])
169 c = array([[2, 3], [0, 1]])
170 d = a.copy()
171 d.sort(axis=0)
172 assert (d == b).all(), "test sort with axis=0"
173 d = a.copy()
174 d.sort(axis=1)
175 assert (d == c).all(), "test sort with axis=1"
176 d = a.copy()
177 d.sort()
178 assert (d == c).all(), "test sort with default axis"
179
180 def test_sort_corner_cases_string_records(self):
181 from numpy import array, dtype
182 import sys
183 if '__pypy__' in sys.builtin_module_names:
184 skip('not implemented yet in PyPy')
185 # test string sorts.
186 s = 'aaaaaaaa'
187 a = array([s + chr(i) for i in range(101)])
188 b = a[::-1].copy()
189 for kind in ['q', 'm', 'h'] :
190 msg = "string sort, kind=%s" % kind
191 c = a.copy();
192 c.sort(kind=kind)
193 assert (c == a).all(), msg
194 c = b.copy();
195 c.sort(kind=kind)
196 assert (c == a).all(), msg
197
198
199 # test record array sorts.
200 dt =dtype([('f', float), ('i', int)])
201 a = array([(i, i) for i in range(101)], dtype = dt)
202 b = a[::-1]
203 for kind in ['q', 'h', 'm'] :
204 msg = "object sort, kind=%s" % kind
205 c = a.copy();
206 c.sort(kind=kind)
207 assert (c == a).all(), msg
208 c = b.copy();
209 c.sort(kind=kind)
210 assert (c == a).all(), msg
211
212 def test_sort_unicode(self):
213 import sys
214 from numpy import array
215 # test unicode sorts.
216 s = 'aaaaaaaa'
217 a = array([s + chr(i) for i in range(101)], dtype=unicode)
218 b = a[::-1].copy()
219 for kind in ['q', 'm', 'h']:
220 msg = "unicode sort, kind=%s" % kind
221 c = a.copy()
222 if '__pypy__' in sys.builtin_module_names:
223 exc = raises(NotImplementedError, "c.sort(kind=kind)")
224 assert 'non-numeric types' in exc.value.message
225 else:
226 c.sort(kind=kind)
227 assert (c == a).all(), msg
228 c = b.copy()
229 if '__pypy__' in sys.builtin_module_names:
230 exc = raises(NotImplementedError, "c.sort(kind=kind)")
231 assert 'non-numeric types' in exc.value.message
232 else:
233 c.sort(kind=kind)
234 assert (c == a).all(), msg
235
236 def test_sort_objects(self):
237 # test object array sorts.
238 from numpy import empty
239 import sys
240 if '__pypy__' in sys.builtin_module_names:
241 skip('not implemented yet in PyPy')
242 try:
243 a = empty((101,), dtype=object)
244 except:
245 skip('object type not supported yet')
246 a[:] = list(range(101))
247 b = a[::-1]
248 for kind in ['q', 'h', 'm'] :
249 msg = "object sort, kind=%s" % kind
250 c = a.copy();
251 c.sort(kind=kind)
252 assert (c == a).all(), msg
253 c = b.copy();
254 c.sort(kind=kind)
255 assert (c == a).all(), msg
256
257 def test_sort_datetime(self):
258 from numpy import arange
259 # test datetime64 sorts.
260 try:
261 a = arange(0, 101, dtype='datetime64[D]')
262 except:
263 skip('datetime type not supported yet')
264 b = a[::-1]
265 for kind in ['q', 'h', 'm'] :
266 msg = "datetime64 sort, kind=%s" % kind
267 c = a.copy();
268 c.sort(kind=kind)
269 assert (c == a).all(), msg
270 c = b.copy();
271 c.sort(kind=kind)
272 assert (c == a).all(), msg
273
274 # test timedelta64 sorts.
275 a = arange(0, 101, dtype='timedelta64[D]')
276 b = a[::-1]
277 for kind in ['q', 'h', 'm'] :
278 msg = "timedelta64 sort, kind=%s" % kind
279 c = a.copy();
280 c.sort(kind=kind)
281 assert (c == a).all(), msg
282 c = b.copy();
283 c.sort(kind=kind)
284 assert (c == a).all(), msg
285
286 def test_sort_order(self):
287 from numpy import array, zeros
288 from sys import byteorder, builtin_module_names
289 if '__pypy__' in builtin_module_names:
290 skip('not implemented yet in PyPy')
291 # Test sorting an array with fields
292 x1 = array([21, 32, 14])
293 x2 = array(['my', 'first', 'name'])
294 x3=array([3.1, 4.5, 6.2])
295 r=zeros(3, dtype=[('id','i'),('word','S5'),('number','f')])
296 r['id'] = x1
297 r['word'] = x2
298 r['number'] = x3
299
300 r.sort(order=['id'])
301 assert (r['id'] == [14, 21, 32]).all()
302 assert (r['word'] == ['name', 'my', 'first']).all()
303 assert max(abs(r['number'] - [6.2, 3.1, 4.5])) < 1e-6
304
305 r.sort(order=['word'])
306 assert (r['id'] == [32, 21, 14]).all()
307 assert (r['word'] == ['first', 'my', 'name']).all()
308 assert max(abs(r['number'] - [4.5, 3.1, 6.2])) < 1e-6
309
310 r.sort(order=['number'])
311 assert (r['id'] == [21, 32, 14]).all()
312 assert (r['word'] == ['my', 'first', 'name']).all()
313 assert max(abs(r['number'] - [3.1, 4.5, 6.2])) < 1e-6
314
315 if byteorder == 'little':
316 strtype = '>i2'
317 else:
318 strtype = '<i2'
319 mydtype = [('name', 'S5'), ('col2', strtype)]
320 r = array([('a', 1), ('b', 255), ('c', 3), ('d', 258)],
321 dtype= mydtype)
322 r.sort(order='col2')
323 assert (r['col2'] == [1, 3, 255, 258]).all()
324 assert (r == array([('a', 1), ('c', 3), ('b', 255), ('d', 258)],
325 dtype=mydtype)).all()
326
327 # tests from numpy/core/tests/test_regression.py
328 def test_sort_bigendian(self):
329 from numpy import array, dtype
330 import sys
331
332 # little endian sorting for big endian machine
333 # is not yet supported! IMPL ME
334 if sys.byteorder == 'little':
335 a = array(range(11), dtype='float64')
336 c = a.astype(dtype('<f8'))
337 c.sort()
338 assert max(abs(a-c)) < 1e-32
339
340 def test_string_argsort_with_zeros(self):
341 import numpy as np
342 import sys
343 x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
344 if '__pypy__' in sys.builtin_module_names:
345 exc = raises(NotImplementedError, "x.argsort(kind='m')")
346 assert 'non-numeric types' in exc.value.message
347 exc = raises(NotImplementedError, "x.argsort(kind='q')")
348 assert 'non-numeric types' in exc.value.message
349 else:
350 assert (x.argsort(kind='m') == np.array([1, 0])).all()
351 assert (x.argsort(kind='q') == np.array([1, 0])).all()
352
353 def test_string_sort_with_zeros(self):
354 import numpy as np
355 import sys
356 x = np.fromstring("\x00\x02\x00\x01", dtype="S2")
357 y = np.fromstring("\x00\x01\x00\x02", dtype="S2")
358 if '__pypy__' in sys.builtin_module_names:
359 exc = raises(NotImplementedError, "x.sort(kind='q')")
360 assert 'non-numeric types' in exc.value.message
361 else:
362 x.sort(kind='q')
363 assert (x == y).all()
364
365 def test_string_mergesort(self):
366 import numpy as np
367 import sys
368 x = np.array(['a'] * 32)
369 if '__pypy__' in sys.builtin_module_names:
370 exc = raises(NotImplementedError, "x.argsort(kind='m')")
371 assert 'non-numeric types' in exc.value.message
372 else:
373 assert (x.argsort(kind='m') == np.arange(32)).all()
374
375 def test_searchsort(self):
376 import numpy as np
377
378 a = np.array(2)
379 raises(ValueError, a.searchsorted, 3)
380
381 a = np.arange(1, 6)
382
383 ret = a.searchsorted(3)
384 assert ret == 2
385 assert isinstance(ret, np.generic)
386
387 ret = a.searchsorted(np.array(3))
388 assert ret == 2
389 assert isinstance(ret, np.generic)
390
391 ret = a.searchsorted(np.array([]))
392 assert isinstance(ret, np.ndarray)
393 assert ret.shape == (0,)
394
395 ret = a.searchsorted(np.array([3]))
396 assert ret == 2
397 assert isinstance(ret, np.ndarray)
398
399 ret = a.searchsorted(np.array([[2, 3]]))
400 assert (ret == [1, 2]).all()
401 assert ret.shape == (1, 2)
402
403 ret = a.searchsorted(3, side='right')
404 assert ret == 3
405 assert isinstance(ret, np.generic)
406
407 assert a.searchsorted(3.1) == 3
408 assert a.searchsorted(3.9) == 3
409
410 exc = raises(ValueError, a.searchsorted, 3, side=None)
411 assert str(exc.value) == "expected nonempty string for keyword 'side'"
412 exc = raises(ValueError, a.searchsorted, 3, side='')
413 assert str(exc.value) == "expected nonempty string for keyword 'side'"
414 exc = raises(ValueError, a.searchsorted, 3, side=2)
415 assert str(exc.value) == "expected nonempty string for keyword 'side'"
416
417 ret = a.searchsorted([-10, 10, 2, 3])
418 assert (ret == [0, 5, 1, 2]).all()
419
420 import sys
421 if '__pypy__' in sys.builtin_module_names:
422 raises(NotImplementedError, "a.searchsorted(3, sorter=range(6))")