Debian Codegraph @

pypy/module/micronumpy/test/test_ndarray.py

raw symbols SCIP
1 # -*- encoding: utf-8 -*-
2 import platform
3 import py
4 import sys
5
6 from pypy.conftest import option
7 from pypy.module.micronumpy.appbridge import get_appbridge_cache
8 from pypy.module.micronumpy.strides import Chunk, new_view, EllipsisChunk
9 from pypy.module.micronumpy.ndarray import W_NDimArray
10 import pypy.module.micronumpy.constants as NPY
11 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
12
13
14 class MockDtype(object):
15 class itemtype(object):
16 @staticmethod
17 def malloc(size, zero=True):
18 return None
19
20 def __init__(self):
21 self.base = self
22 self.elsize = 1
23 self.num = 0
24
25
26 def create_slice(space, a, chunks):
27 if not any(isinstance(c, EllipsisChunk) for c in chunks):
28 chunks.append(EllipsisChunk())
29 return new_view(space, W_NDimArray(a), chunks).implementation
30
31
32 def create_array(*args, **kwargs):
33 return W_NDimArray.from_shape(*args, **kwargs).implementation
34
35
36 class TestNumArrayDirect(object):
37 def newslice(self, *args):
38 return self.space.newslice(*[self.space.wrap(arg) for arg in args])
39
40 def newtuple(self, *args):
41 args_w = []
42 for arg in args:
43 if isinstance(arg, int):
44 args_w.append(self.space.wrap(arg))
45 else:
46 args_w.append(arg)
47 return self.space.newtuple(args_w)
48
49 def test_strides_f(self):
50 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.FORTRANORDER)
51 assert a.strides == [1, 10, 50]
52 assert a.backstrides == [9, 40, 100]
53
54 def test_strides_c(self):
55 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.CORDER)
56 assert a.strides == [15, 3, 1]
57 assert a.backstrides == [135, 12, 2]
58 a = create_array(self.space, [1, 0, 7], MockDtype(), order=NPY.CORDER)
59 assert a.strides == [7, 7, 1]
60 assert a.backstrides == [0, 0, 6]
61
62 def test_create_slice_f(self):
63 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.FORTRANORDER)
64 s = create_slice(self.space, a, [Chunk(3, 0, 0, 1)])
65 assert s.start == 3
66 assert s.strides == [10, 50]
67 assert s.backstrides == [40, 100]
68 s = create_slice(self.space, a, [Chunk(1, 9, 2, 4)])
69 assert s.start == 1
70 assert s.strides == [2, 10, 50]
71 assert s.backstrides == [6, 40, 100]
72 s = create_slice(self.space, a, [Chunk(1, 5, 3, 2), Chunk(1, 2, 1, 1),
73 Chunk(1, 0, 0, 1)])
74 assert s.shape == [2, 1]
75 assert s.strides == [3, 10]
76 assert s.backstrides == [3, 0]
77 s = create_slice(self.space, a, [Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
78 assert s.start == 20
79 assert s.shape == [10, 3]
80
81 def test_create_slice_c(self):
82 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.CORDER)
83 s = create_slice(self.space, a, [Chunk(3, 0, 0, 1)])
84 assert s.start == 45
85 assert s.strides == [3, 1]
86 assert s.backstrides == [12, 2]
87 s = create_slice(self.space, a, [Chunk(1, 9, 2, 4)])
88 assert s.start == 15
89 assert s.strides == [30, 3, 1]
90 assert s.backstrides == [90, 12, 2]
91 s = create_slice(self.space, a, [Chunk(1, 5, 3, 2), Chunk(1, 2, 1, 1),
92 Chunk(1, 0, 0, 1)])
93 assert s.start == 19
94 assert s.shape == [2, 1]
95 assert s.strides == [45, 3]
96 assert s.backstrides == [45, 0]
97 s = create_slice(self.space, a, [Chunk(0, 10, 1, 10), Chunk(2, 0, 0, 1)])
98 assert s.start == 6
99 assert s.shape == [10, 3]
100
101 def test_slice_of_slice_f(self):
102 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.FORTRANORDER)
103 s = create_slice(self.space, a, [Chunk(5, 0, 0, 1)])
104 assert s.start == 5
105 s2 = create_slice(self.space, s, [Chunk(3, 0, 0, 1)])
106 assert s2.shape == [3]
107 assert s2.strides == [50]
108 assert s2.parent is a
109 assert s2.backstrides == [100]
110 assert s2.start == 35
111 s = create_slice(self.space, a, [Chunk(1, 5, 3, 2)])
112 s2 = create_slice(self.space, s, [Chunk(0, 2, 1, 2), Chunk(2, 0, 0, 1)])
113 assert s2.shape == [2, 3]
114 assert s2.strides == [3, 50]
115 assert s2.backstrides == [3, 100]
116 assert s2.start == 1 * 15 + 2 * 3
117
118 def test_slice_of_slice_c(self):
119 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.CORDER)
120 s = create_slice(self.space, a, [Chunk(5, 0, 0, 1)])
121 assert s.start == 15 * 5
122 s2 = create_slice(self.space, s, [Chunk(3, 0, 0, 1)])
123 assert s2.shape == [3]
124 assert s2.strides == [1]
125 assert s2.parent is a
126 assert s2.backstrides == [2]
127 assert s2.start == 5 * 15 + 3 * 3
128 s = create_slice(self.space, a, [Chunk(1, 5, 3, 2)])
129 s2 = create_slice(self.space, s, [Chunk(0, 2, 1, 2), Chunk(2, 0, 0, 1)])
130 assert s2.shape == [2, 3]
131 assert s2.strides == [45, 1]
132 assert s2.backstrides == [45, 2]
133 assert s2.start == 1 * 15 + 2 * 3
134
135 def test_negative_step_f(self):
136 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.FORTRANORDER)
137 s = create_slice(self.space, a, [Chunk(9, -1, -2, 5)])
138 assert s.start == 9
139 assert s.strides == [-2, 10, 50]
140 assert s.backstrides == [-8, 40, 100]
141
142 def test_negative_step_c(self):
143 a = create_array(self.space, [10, 5, 3], MockDtype(), order=NPY.CORDER)
144 s = create_slice(self.space, a, [Chunk(9, -1, -2, 5)])
145 assert s.start == 135
146 assert s.strides == [-30, 3, 1]
147 assert s.backstrides == [-120, 12, 2]
148
149 def test_shape_agreement(self):
150 from pypy.module.micronumpy.strides import _shape_agreement
151 assert _shape_agreement([3], [3]) == [3]
152 assert _shape_agreement([1, 2, 3], [1, 2, 3]) == [1, 2, 3]
153 _shape_agreement([2], [3]) == 0
154 assert _shape_agreement([4, 4], []) == [4, 4]
155 assert _shape_agreement([8, 1, 6, 1], [7, 1, 5]) == [8, 7, 6, 5]
156 assert _shape_agreement([5, 2], [4, 3, 5, 2]) == [4, 3, 5, 2]
157
158 def test_calc_new_strides(self):
159 from pypy.module.micronumpy.strides import calc_new_strides
160 assert calc_new_strides([2, 4], [4, 2], [4, 2], NPY.CORDER) == [8, 2]
161 assert calc_new_strides([2, 4, 3], [8, 3], [1, 16], NPY.FORTRANORDER) == [1, 2, 16]
162 assert calc_new_strides([2, 3, 4], [8, 3], [1, 16], NPY.FORTRANORDER) is None
163 assert calc_new_strides([24], [2, 4, 3], [48, 6, 1], NPY.CORDER) is None
164 assert calc_new_strides([24], [2, 4, 3], [24, 6, 2], NPY.CORDER) == [2]
165 assert calc_new_strides([105, 1], [3, 5, 7], [35, 7, 1],NPY.CORDER) == [1, 1]
166 assert calc_new_strides([1, 105], [3, 5, 7], [35, 7, 1],NPY.CORDER) == [105, 1]
167 assert calc_new_strides([1, 105], [3, 5, 7], [35, 7, 1],NPY.FORTRANORDER) is None
168 assert calc_new_strides([1, 1, 1, 105, 1], [15, 7], [7, 1],NPY.CORDER) == \
169 [105, 105, 105, 1, 1]
170 assert calc_new_strides([1, 1, 105, 1, 1], [7, 15], [1, 7],NPY.FORTRANORDER) == \
171 [1, 1, 1, 105, 105]
172
173 def test_find_shape(self):
174 from pypy.module.micronumpy.ctors import find_shape_and_elems
175
176 space = self.space
177 shape, elems = find_shape_and_elems(space,
178 space.newlist([space.wrap("a"),
179 space.wrap("b")]),
180 None)
181 assert shape == [2]
182 assert space.text_w(elems[0]) == "a"
183 assert space.text_w(elems[1]) == "b"
184
185 def test_from_shape_and_storage(self):
186 from rpython.rlib.rawstorage import alloc_raw_storage, raw_storage_setitem
187 from rpython.rtyper.lltypesystem import rffi
188 from pypy.module.micronumpy.descriptor import get_dtype_cache
189 storage = alloc_raw_storage(4, track_allocation=False, zero=True)
190 for i in range(4):
191 raw_storage_setitem(storage, i, rffi.cast(rffi.UCHAR, i))
192 #
193 dtypes = get_dtype_cache(self.space)
194 w_array = W_NDimArray.from_shape_and_storage(self.space, [2, 2],
195 storage, dtypes.w_int8dtype,
196 storage_bytes=4)
197 def get(i, j):
198 return w_array.getitem(self.space, [i, j]).value
199 assert get(0, 0) == 0
200 assert get(0, 1) == 1
201 assert get(1, 0) == 2
202 assert get(1, 1) == 3
203
204
205 class AppTestNumArray(BaseNumpyAppTest):
206 spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii"])
207
208 def w_CustomIndexObject(self, index):
209 class CustomIndexObject(object):
210 def __init__(self, index):
211 self.index = index
212 def __index__(self):
213 return self.index
214
215 return CustomIndexObject(index)
216
217 def w_CustomIndexIntObject(self, index, value):
218 class CustomIndexIntObject(object):
219 def __init__(self, index, value):
220 self.index = index
221 self.value = value
222 def __index__(self):
223 return self.index
224 def __int__(self):
225 return self.value
226
227 return CustomIndexIntObject(index, value)
228
229 def w_CustomIntObject(self, value):
230 class CustomIntObject(object):
231 def __init__(self, value):
232 self.value = value
233 def __index__(self):
234 return self.value
235
236 return CustomIntObject(value)
237
238 def test_constants(self):
239 import numpy as np
240 assert np.MAXDIMS is 32
241 assert np.CLIP is 0
242 assert np.WRAP is 1
243 assert np.RAISE is 2
244
245 def test_creation(self):
246 from numpy import ndarray, array, dtype, flatiter
247
248 assert type(ndarray) is type
249 assert repr(ndarray) == "<type 'numpy.ndarray'>"
250 assert repr(flatiter) == "<type 'numpy.flatiter'>"
251 assert type(array) is not type
252 a = ndarray((2, 3))
253 assert a.shape == (2, 3)
254 assert a.dtype == dtype(float)
255
256 raises(TypeError, ndarray, [[1], [2], [3]])
257
258 a = ndarray(3, dtype=int)
259 assert a.shape == (3,)
260 assert a.dtype is dtype(int)
261 a = ndarray([], dtype=float)
262 assert a.shape == ()
263 # test uninitialized value crash?
264 assert len(str(a)) > 0
265
266 x = array([[0, 2], [1, 1], [2, 0]])
267 y = array(x.T, dtype=float)
268 assert (y == x.T).all()
269 y = array(x.T, copy=False)
270 assert (y == x.T).all()
271
272 exc = raises(ValueError, ndarray, [1,2,256]*10000)
273 assert exc.value[0] == 'sequence too large; cannot be greater than 32'
274 exc = raises(ValueError, ndarray, [1,2,256]*10)
275 assert exc.value[0] == 'array is too big.'
276
277 def test_ndmin(self):
278 from numpy import array
279
280 arr = array([[[1]]], ndmin=1)
281 assert arr.shape == (1, 1, 1)
282
283 def test_noop_ndmin(self):
284 from numpy import array
285 arr = array([1], ndmin=3)
286 assert arr.shape == (1, 1, 1)
287
288 def test_array_init(self):
289 import numpy as np
290 a = np.array('123', dtype='int64')
291 assert a == 123
292 assert a.dtype == np.int64
293 a = np.array('123', dtype='intp')
294 assert a == 123
295 assert a.dtype == np.intp
296 # required for numpy test suite
297 raises(ValueError, np.array, type(a))
298
299 def test_array_copy(self):
300 from numpy import array
301 a = array(range(12)).reshape(3,4)
302 b = array(a, ndmin=4)
303 assert b.shape == (1, 1, 3, 4)
304 b = array(a, copy=False)
305 b[0, 0] = 100
306 assert a[0, 0] == 100
307 b = array(a, copy=True, ndmin=2)
308 b[0, 0] = 0
309 assert a[0, 0] == 100
310 b = array(a, dtype=float)
311 assert (b[0] == [100, 1, 2, 3]).all()
312 assert b.dtype.kind == 'f'
313 b = array(a, copy=False, ndmin=4)
314 b[0,0,0,0] = 0
315 assert a[0, 0] == 0
316 a = array([[[]]])
317 # Simulate tiling an empty array, really tests repeat, reshape
318 # b = tile(a, (3, 2, 5))
319 reps = (3, 4, 5)
320 c = array(a, copy=False, subok=True, ndmin=len(reps))
321 d = c.reshape(3, 4, 0)
322 e = d.repeat(3, 0)
323 assert e.shape == (9, 4, 0)
324 a = array(123)
325 b = array(a, dtype=float)
326 assert b == 123.0
327
328 a = array([[123, 456]])
329 assert a.flags['C']
330 b = array(a, order='K')
331 assert b.flags['C']
332 assert (b == a).all()
333 b = array(a, order='K', copy=True)
334 assert b.flags['C']
335 assert (b == a).all()
336
337 def test_unicode(self):
338 import numpy as np
339 a = np.array([3, u'Aÿ', ''], dtype='U3')
340 assert a.shape == (3,)
341 assert a.dtype == np.dtype('U3')
342 assert a[0] == u'3'
343 assert a[1] == u'Aÿ'
344
345 def test_dtype_attribute(self):
346 import numpy as np
347 a = np.array(40000, dtype='uint16')
348 assert a.dtype == np.uint16
349 a.dtype = np.int16
350 assert a == -25536
351 a = np.array([1, 2, 3, 4, 40000], dtype='uint16')
352 assert a.dtype == np.uint16
353 a.dtype = np.int16
354 assert a[4] == -25536
355 exc = raises(ValueError, 'a.dtype = None')
356 assert exc.value[0] == 'new type not compatible with array.'
357 exc = raises(ValueError, 'a.dtype = np.int32')
358 assert exc.value[0] == 'new type not compatible with array.'
359 exc = raises(AttributeError, 'del a.dtype')
360 assert exc.value[0] == 'Cannot delete array dtype'
361
362 def test_buffer(self):
363 import numpy as np
364 a = np.array([1,2,3])
365 b = buffer(a)
366 assert type(b) is buffer
367 assert 'read-only buffer' in repr(b)
368 exc = raises(TypeError, "b[0] = '0'")
369 assert str(exc.value) == 'buffer is read-only'
370
371 def test_type(self):
372 from numpy import array
373 ar = array(range(5))
374 assert type(ar) is type(ar + ar)
375
376 def test_ndim(self):
377 from numpy import array
378 x = array(0.2)
379 assert x.ndim == 0
380 x = array([1, 2])
381 assert x.ndim == 1
382 x = array([[1, 2], [3, 4]])
383 assert x.ndim == 2
384 x = array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
385 assert x.ndim == 3
386 # numpy actually raises an AttributeError, but numpy.raises an
387 # TypeError
388 raises((TypeError, AttributeError), 'x.ndim = 3')
389
390 def test_zeros(self):
391 from numpy import zeros
392 a = zeros(15)
393 # Check that storage was actually zero'd.
394 assert a[10] == 0.0
395 # And check that changes stick.
396 a[13] = 5.3
397 assert a[13] == 5.3
398 assert zeros(()) == 0
399 assert zeros(()).shape == ()
400 assert zeros((), dtype='S') == ''
401 assert zeros((), dtype='S').shape == ()
402 assert zeros((), dtype='S').dtype == '|S1'
403 assert zeros(5, dtype='U')[4] == u''
404 assert zeros(5, dtype='U').shape == (5,)
405 assert zeros(5, dtype='U').dtype == '<U1'
406
407 def test_check_shape(self):
408 import numpy as np
409 for func in [np.zeros, np.empty]:
410 exc = raises(ValueError, func, [0, -1, 1], 'int8')
411 assert str(exc.value) == "negative dimensions are not allowed"
412 exc = raises(ValueError, func, [2, -1, 3], 'int8')
413 assert str(exc.value) == "negative dimensions are not allowed"
414
415 exc = raises(ValueError, func, [975]*7, 'int8')
416 assert str(exc.value) == "array is too big."
417 exc = raises(ValueError, func, [26244]*5, 'int8')
418 assert str(exc.value) == "array is too big."
419
420 def test_empty_like(self):
421 import numpy as np
422 a = np.empty_like(np.zeros(()))
423 assert a.shape == ()
424 assert a.dtype == np.float_
425 a = np.empty_like(a, dtype='S')
426 assert a.dtype == '|S1'
427 a = np.zeros((2, 3))
428 assert a.shape == (2, 3)
429 a[0,0] = 1
430 b = np.empty_like(a)
431 assert b.shape == a.shape
432 assert b.dtype == a.dtype
433 assert b[0,0] != 1
434 b = np.empty_like(np.array(True), dtype=None)
435 assert b.dtype is np.dtype(bool)
436 b = np.empty_like(a, dtype='i4')
437 assert b.shape == a.shape
438 assert b.dtype == np.dtype('i4')
439 # assert b[0,0] != 1 # no guarantees on values in b
440 b = np.empty_like([1,2,3])
441 assert b.shape == (3,)
442 assert b.dtype == np.int_
443 class A(np.ndarray):
444 pass
445 b = np.empty_like(A((2, 3)))
446 assert b.shape == (2, 3)
447 assert type(b) is A
448 b = np.empty_like(A((2, 3)), subok=False)
449 assert b.shape == (2, 3)
450 assert type(b) is np.ndarray
451 b = np.empty_like(np.array(3.0), order='A')
452 assert type(b) is np.ndarray
453
454 def test_size(self):
455 from numpy import array,arange,cos
456 assert array(3).size == 1
457 a = array([1, 2, 3])
458 assert a.size == 3
459 assert (a + a).size == 3
460 ten = cos(1 + arange(10)).size
461 assert ten == 10
462
463 def test_empty(self):
464 from numpy import empty
465 a = empty(2)
466 a[1] = 1.0
467 assert a[1] == 1.0
468
469 def test_ones(self):
470 from numpy import ones, dtype
471 a = ones(3)
472 assert len(a) == 3
473 assert a[0] == 1
474 raises(IndexError, "a[3]")
475 a[2] = 4
476 assert a[2] == 4
477 b = ones(3, complex)
478 assert b[0] == 1+0j
479 assert b.dtype is dtype(complex)
480
481 def test_arange(self):
482 from numpy import arange, dtype, array
483 a = arange(3)
484 assert (a == [0, 1, 2]).all()
485 assert a.dtype is dtype(int)
486 a = arange(3.0)
487 assert (a == [0., 1., 2.]).all()
488 assert a.dtype is dtype(float)
489 a = arange(3, 7)
490 assert (a == [3, 4, 5, 6]).all()
491 assert a.dtype is dtype(int)
492 a = arange(3, 7, 2)
493 assert (a == [3, 5]).all()
494 a = arange(3, 8, 2)
495 assert (a == [3, 5, 7]).all()
496 a = arange(3, dtype=float)
497 assert (a == [0., 1., 2.]).all()
498 assert a.dtype is dtype(float)
499 a = arange(0, 0.8, 0.1)
500 assert len(a) == 8
501 assert arange(False, True, True).dtype is dtype(int)
502
503 a = arange(array([10]))
504 assert a.shape == (10,)
505
506 def test_copy(self):
507 from numpy import arange, array
508 a = arange(5)
509 b = a.copy()
510 for i in xrange(5):
511 assert b[i] == a[i]
512 a[3] = 22
513 assert b[3] == 3
514
515 a = array(1)
516 assert a.copy() == a
517
518 a = arange(8)
519 b = a[::2]
520 c = b.copy()
521 assert (c == b).all()
522 assert ((a + a).copy() == (a + a)).all()
523
524 a = arange(15).reshape(5,3)
525 b = a.copy()
526 assert (b == a).all()
527
528 a = array(['abc', 'def','xyz'], dtype='S3')
529 b = a.copy()
530 assert b[0] == a[0]
531
532 a = arange(8)
533 b = a.copy(order=None)
534 assert (b == a).all()
535 b = a.copy(order=0)
536 assert (b == a).all()
537 b = a.copy(order='C')
538 assert (b == a).all()
539 b = a.copy(order='K')
540 assert (b == a).all()
541 b = a.copy(order='A')
542 assert (b == a).all()
543 b = a.copy(order='F')
544 assert (b == a).all()
545 b = a.copy(order=True)
546 assert (b == a).all()
547
548 def test_iterator_init(self):
549 from numpy import array
550 a = array(range(5))
551 assert a[3] == 3
552
553 def test_list_of_array_init(self):
554 import numpy as np
555 a = np.array([np.array(True), np.array(False)])
556 assert a.shape == (2,)
557 assert a.dtype == np.bool_
558 assert (a == [True, False]).all()
559 a = np.array([np.array(True), np.array(2)])
560 assert a.shape == (2,)
561 assert a.dtype == np.int_
562 assert (a == [1, 2]).all()
563 a = np.array([np.array(True), np.int_(2)])
564 assert a.shape == (2,)
565 assert a.dtype == np.int_
566 assert (a == [1, 2]).all()
567 a = np.array([np.array([True]), np.array([2])])
568 assert a.shape == (2, 1)
569 assert a.dtype == np.int_
570 assert (a == [[1], [2]]).all()
571
572 def test_getitem(self):
573 from numpy import array
574 a = array(range(5))
575 raises(IndexError, "a[5]")
576 a = a + a
577 raises(IndexError, "a[5]")
578 assert a[-1] == 8
579 raises(IndexError, "a[-6]")
580
581 def test_getitem_float(self):
582 from numpy import array
583 a = array([1, 2, 3, 4])
584 assert a[1.2] == 2
585 assert a[1.6] == 2
586 assert a[-1.2] == 4
587
588 def test_getitem_tuple(self):
589 from numpy import array
590 a = array(range(5))
591 raises(IndexError, "a[(1,2)]")
592 for i in xrange(5):
593 assert a[(i,)] == i
594 b = a[()]
595 for i in xrange(5):
596 assert a[i] == b[i]
597
598 def test_getitem_nd(self):
599 from numpy import arange
600 a = arange(15).reshape(3, 5)
601 assert a[1, 3] == 8
602 assert a.T[1, 2] == 11
603
604 def test_getitem_obj_index(self):
605 from numpy import arange
606 a = arange(10)
607 assert a[self.CustomIndexObject(1)] == 1
608
609 def test_getitem_obj_prefer_index_to_int(self):
610 from numpy import arange
611 a = arange(10)
612 assert a[self.CustomIndexIntObject(0, 1)] == 0
613
614 def test_getitem_obj_int(self):
615 from numpy import arange
616 a = arange(10)
617 assert a[self.CustomIntObject(1)] == 1
618
619 def test_setitem(self):
620 from numpy import array
621 a = array(range(5))
622 a[-1] = 5.0
623 assert a[4] == 5.0
624 raises(IndexError, "a[5] = 0.0")
625 raises(IndexError, "a[-6] = 3.0")
626 a[1] = array(100)
627 a[2] = array([100])
628 assert a[1] == 100
629 assert a[2] == 100
630 a = array(range(5), dtype=float)
631 a[0] = 0.005
632 assert a[0] == 0.005
633 a[1] = array(-0.005)
634 a[2] = array([-0.005])
635 assert a[1] == -0.005
636 assert a[2] == -0.005
637
638 def test_setitem_tuple(self):
639 from numpy import array
640 a = array(range(5))
641 raises(IndexError, "a[(1,2)] = [0,1]")
642 for i in xrange(5):
643 a[(i,)] = i + 1
644 assert a[i] == i + 1
645 a[()] = range(5)
646 for i in xrange(5):
647 assert a[i] == i
648
649 def test_setitem_record(self):
650 from numpy import zeros
651 trie = zeros(200, dtype= [ ("A","uint32"),("C","uint32"), ])
652 trie[0][0] = 1
653 assert trie[0]['A'] == 1
654
655 def test_setitem_array(self):
656 import numpy as np
657 a = np.array((-1., 0, 1))/0.
658 b = np.array([False, False, True], dtype=bool)
659 a[b] = 100
660 assert a[2] == 100
661
662 def test_setitem_obj_index(self):
663 from numpy import arange
664 a = arange(10)
665 a[self.CustomIndexObject(1)] = 100
666 assert a[1] == 100
667
668 def test_setitem_obj_prefer_index_to_int(self):
669 from numpy import arange
670 a = arange(10)
671 a[self.CustomIndexIntObject(0, 1)] = 100
672 assert a[0] == 100
673
674 def test_setitem_obj_int(self):
675 from numpy import arange
676 a = arange(10)
677 a[self.CustomIntObject(1)] = 100
678 assert a[1] == 100
679
680 def test_setitem_list_of_float(self):
681 from numpy import arange
682 a = arange(10)
683 a[[0.9]] = -10
684 assert a[0] == -10
685
686 def test_delitem(self):
687 import numpy as np
688 a = np.arange(10)
689 exc = raises(ValueError, 'del a[2]')
690 assert exc.value.message == 'cannot delete array elements'
691
692 def test_access_swallow_exception(self):
693 class ErrorIndex(object):
694 def __index__(self):
695 return 1 / 0
696
697 class ErrorInt(object):
698 def __int__(self):
699 return 1 / 0
700
701 # numpy will swallow errors in __int__ and __index__ and
702 # just raise IndexError.
703
704 from numpy import arange
705 a = arange(10)
706 exc = raises(IndexError, "a[ErrorIndex()] == 0")
707 assert exc.value.message.startswith('only integers, slices')
708 exc = raises(IndexError, "a[ErrorInt()] == 0")
709 assert exc.value.message.startswith('only integers, slices')
710
711 def test_setslice_array(self):
712 from numpy import array
713 a = array(5)
714 exc = raises(ValueError, "a[:] = 4")
715 assert exc.value[0] == "cannot slice a 0-d array"
716 a = array(range(5))
717 b = array(range(2))
718 a[1:4:2] = b
719 assert a[1] == 0.
720 assert a[3] == 1.
721 b[::-1] = b
722 assert b[0] == 1.
723 assert b[1] == 0.
724
725 def test_setslice_of_slice_array(self):
726 from numpy import array, zeros
727 a = zeros(5)
728 a[::2] = array([9., 10., 11.])
729 assert a[0] == 9.
730 assert a[2] == 10.
731 assert a[4] == 11.
732 a[1:4:2][::-1] = array([1., 2.])
733 assert a[0] == 9.
734 assert a[1] == 2.
735 assert a[2] == 10.
736 assert a[3] == 1.
737 assert a[4] == 11.
738 a = zeros(10)
739 a[::2][::-1][::2] = array(range(1, 4))
740 assert a[8] == 1.
741 assert a[4] == 2.
742 assert a[0] == 3.
743
744 def test_setslice_list(self):
745 from numpy import array
746 a = array(range(5), float)
747 b = [0., 1.]
748 a[1:4:2] = b
749 assert a[1] == 0.
750 assert a[3] == 1.
751
752 def test_setslice_constant(self):
753 from numpy import array
754 a = array(range(5), float)
755 a[1:4:2] = 0.
756 assert a[1] == 0.
757 assert a[3] == 0.
758
759 def test_newaxis(self):
760 import math
761 from numpy import array, cos, zeros, newaxis
762 a = array(range(5))
763 b = array([range(5)])
764 assert (a[newaxis] == b).all()
765 a = array(range(3))
766 b = array([1, 3])
767 expected = zeros((3, 2))
768 for x in range(3):
769 for y in range(2):
770 expected[x, y] = math.cos(a[x]) * math.cos(b[y])
771 assert ((cos(a)[:,newaxis] * cos(b).T) == expected).all()
772 o = array(1)
773 a = o[newaxis]
774 assert a == array([1])
775 assert a.shape == (1,)
776 o[newaxis, newaxis] = 2
777 assert o == 2
778 a[:] = 3
779 assert o == 3
780
781 def test_newaxis_slice(self):
782 from numpy import array, newaxis
783
784 a = array(range(5))
785 b = array(range(1,5))
786 c = array([range(1,5)])
787 d = array([[x] for x in range(1,5)])
788
789 assert (a[1:] == b).all()
790 assert (a[1:,newaxis] == d).all()
791 assert (a[newaxis,1:] == c).all()
792 n = a.dtype.itemsize
793 assert a.strides == (n,)
794 assert a[:, newaxis].strides == (n, 0)
795
796 def test_newaxis_assign(self):
797 from numpy import array, newaxis
798
799 a = array(range(5))
800 a[newaxis,1] = [2]
801 assert a[1] == 2
802
803 def test_newaxis_virtual(self):
804 from numpy import array, newaxis
805
806 a = array(range(5))
807 b = (a + a)[newaxis]
808 c = array([[0, 2, 4, 6, 8]])
809 assert (b == c).all()
810
811 def test_newaxis_then_slice(self):
812 from numpy import array, newaxis
813 a = array(range(5))
814 b = a[newaxis]
815 assert b.shape == (1, 5)
816 assert (b[0,1:] == a[1:]).all()
817
818 def test_slice_then_newaxis(self):
819 from numpy import array, newaxis
820 a = array(range(5))
821 b = a[2:]
822 assert (b[newaxis] == [[2, 3, 4]]).all()
823
824 def test_scalar(self):
825 from numpy import array, dtype, int_
826 a = array(3)
827 exc = raises(IndexError, "a[0]")
828 assert exc.value[0] == "too many indices for array"
829 exc = raises(IndexError, "a[0] = 5")
830 assert exc.value[0] == "too many indices for array"
831 assert a.size == 1
832 assert a.shape == ()
833 assert a.dtype is dtype(int)
834 b = a[()]
835 assert type(b) is int_
836 assert b == 3
837 a[()] = 4
838 assert a == 4
839
840 def test_build_scalar(self):
841 from numpy import dtype
842 import sys
843 try:
844 from numpy.core.multiarray import scalar
845 except ImportError:
846 from numpy import scalar
847 exc = raises(TypeError, scalar, int, 2)
848 assert exc.value[0] == 'argument 1 must be numpy.dtype, not type'
849 if '__pypy__' in sys.builtin_module_names:
850 exc = raises(TypeError, scalar, dtype('void'), 'abc')
851 else:
852 a = scalar(dtype('void'), 'abc')
853 exc = raises(TypeError, str, a)
854 assert exc.value[0] == 'Empty data-type'
855 exc = raises(TypeError, scalar, dtype(float), 2.5)
856 assert exc.value[0] == 'initializing object must be a string'
857 exc = raises(ValueError, scalar, dtype(float), 'abc')
858 assert exc.value[0] == 'initialization string is too small'
859 a = scalar(dtype('<f8'), dtype('<f8').type(2.5).tostring())
860 assert a == 2.5
861
862 def test_len(self):
863 from numpy import array
864 a = array(range(5))
865 assert len(a) == 5
866 assert len(a + a) == 5
867
868 def test_shape(self):
869 from numpy import array
870 a = array(range(5))
871 assert a.shape == (5,)
872 b = a + a
873 assert b.shape == (5,)
874 c = a[:3]
875 assert c.shape == (3,)
876 assert array([]).shape == (0,)
877
878 def test_set_shape(self):
879 from numpy import array, zeros
880 a = array([])
881 raises(ValueError, "a.shape = []")
882 a = array(range(12))
883 a.shape = (3, 4)
884 assert (a == [range(4), range(4, 8), range(8, 12)]).all()
885 a.shape = (3, 2, 2)
886 assert a[1, 1, 1] == 7
887 a.shape = (3, -1, 2)
888 assert a.shape == (3, 2, 2)
889 a.shape = 12
890 assert a.shape == (12, )
891 exc = raises(ValueError, "a.shape = 10")
892 assert str(exc.value) == "total size of new array must be unchanged"
893 a = array(3)
894 a.shape = ()
895 #numpy allows this
896 a.shape = (1,)
897 assert a[0] == 3
898 a = array(range(6)).reshape(2,3).T
899 raises(AttributeError, 'a.shape = 6')
900
901 def test_reshape(self):
902 from numpy import array, zeros
903 for a in [array(1), array([1])]:
904 for s in [(), (1,)]:
905 b = a.reshape(s)
906 assert b.shape == s
907 assert (b == [1]).all()
908 a = array(1.5)
909 b = a.reshape(None)
910 assert b is not a
911 assert b == a
912 b[...] = 2.5
913 assert a == 2.5
914 a = array([]).reshape((0, 2))
915 assert a.shape == (0, 2)
916 assert a.strides == (16, 8)
917 a = array([])
918 a.shape = (4, 0, 3, 0, 0, 2)
919 assert a.strides == (48, 48, 16, 16, 16, 8)
920 a = array(1.5)
921 assert a.reshape(()).shape == ()
922 a = array(1.5)
923 a.shape = ()
924 assert a.strides == ()
925 a = array(range(12))
926 exc = raises(ValueError, "b = a.reshape(())")
927 assert str(exc.value) == "total size of new array must be unchanged"
928 exc = raises(ValueError, "b = a.reshape((3, 10))")
929 assert str(exc.value) == "total size of new array must be unchanged"
930 b = a.reshape((3, 4))
931 assert b.shape == (3, 4)
932 assert (b == [range(4), range(4, 8), range(8, 12)]).all()
933 b[:, 0] = 1000
934 assert (a == [1000, 1, 2, 3, 1000, 5, 6, 7, 1000, 9, 10, 11]).all()
935 a = zeros((4, 2, 3))
936 a.shape = (12, 2)
937 (a + a).reshape(2, 12) # assert did not explode
938 a = array([[[[]]]])
939 assert a.reshape((0,)).shape == (0,)
940 assert a.reshape((0,), order='C').shape == (0,)
941 assert a.reshape((0,), order='A').shape == (0,)
942 raises(TypeError, a.reshape, (0,), badarg="C")
943 raises(ValueError, a.reshape, (0,), order="K")
944 b = a.reshape((0,), order='F')
945 assert b.shape == (0,)
946 a = array(range(24), 'uint8')
947 assert a.reshape([2, 3, 4], order=True).strides ==(1, 2, 6)
948 assert a.reshape([2, 3, 4], order=False).strides ==(12, 4, 1)
949
950 def test_slice_reshape(self):
951 from numpy import zeros, arange
952 a = zeros((4, 2, 3))
953 b = a[::2, :, :]
954 b.shape = (2, 6)
955 exc = raises(AttributeError, "b.shape = 12")
956 assert str(exc.value) == \
957 "incompatible shape for a non-contiguous array"
958 b = a[::2, :, :].reshape((2, 6))
959 assert b.shape == (2, 6)
960 b = arange(20)[1:17:2]
961 b.shape = (4, 2)
962 assert (b == [[1, 3], [5, 7], [9, 11], [13, 15]]).all()
963 c = b.reshape((2, 4))
964 assert (c == [[1, 3, 5, 7], [9, 11, 13, 15]]).all()
965
966 z = arange(96).reshape((12, -1))
967 assert z.shape == (12, 8)
968 y = z.reshape((4, 3, 8))
969 v = y[:, ::2, :]
970 w = y.reshape(96)
971 u = v.reshape(64)
972 assert y[1, 2, 1] == z[5, 1]
973 y[1, 2, 1] = 1000
974 # z, y, w, v are views of eachother
975 assert z[5, 1] == 1000
976 assert v[1, 1, 1] == 1000
977 assert w[41] == 1000
978 # u is not a view, it is a copy!
979 assert u[25] == 41
980
981 a = zeros((5, 2))
982 assert a.reshape(-1).shape == (10,)
983
984 raises(ValueError, arange(10).reshape, (5, -1, -1))
985
986 def test_reshape_varargs(self):
987 from numpy import arange
988 z = arange(96).reshape(12, -1)
989 y = z.reshape(4, 3, 8)
990 assert y.shape == (4, 3, 8)
991
992 def test_scalar_reshape(self):
993 from numpy import array
994 a = array(3)
995 assert a.reshape([1, 1]).shape == (1, 1)
996 assert a.reshape([1]).shape == (1,)
997 raises(ValueError, "a.reshape(3)")
998
999 def test_strides(self):
1000 from numpy import array
1001 a = array([[1.0, 2.0],
1002 [3.0, 4.0]])
1003 assert a.strides == (16, 8)
1004 assert a[1:].strides == (16, 8)
1005
1006 def test_strides_scalar(self):
1007 from numpy import array
1008 a = array(42)
1009 assert a.strides == ()
1010
1011 def test_add(self):
1012 from numpy import array
1013 a = array(range(5))
1014 b = a + a
1015 for i in range(5):
1016 assert b[i] == i + i
1017
1018 a = array([True, False, True, False], dtype="?")
1019 b = array([True, True, False, False], dtype="?")
1020 c = a + b
1021 for i in range(4):
1022 assert c[i] == bool(a[i] + b[i])
1023
1024 def test_add_other(self):
1025 from numpy import array
1026 a = array(range(5))
1027 b = array([i for i in reversed(range(5))])
1028 c = a + b
1029 for i in range(5):
1030 assert c[i] == 4
1031
1032 def test_add_constant(self):
1033 from numpy import array
1034 a = array(range(5))
1035 b = a + 5
1036 for i in range(5):
1037 assert b[i] == i + 5
1038
1039 def test_radd(self):
1040 from numpy import array
1041 r = 3 + array(range(3))
1042 for i in range(3):
1043 assert r[i] == i + 3
1044 r = [1, 2] + array([1, 2])
1045 assert (r == [2, 4]).all()
1046
1047 def test_inplace_op_scalar(self):
1048 from numpy import array
1049 for op in [
1050 '__iadd__',
1051 '__isub__',
1052 '__imul__',
1053 '__idiv__',
1054 '__ifloordiv__',
1055 '__imod__',
1056 '__ipow__',
1057 '__ilshift__',
1058 '__irshift__',
1059 '__iand__',
1060 '__ior__',
1061 '__ixor__']:
1062 a = b = array(range(3))
1063 getattr(a, op).__call__(2)
1064 assert id(a) == id(b)
1065
1066 def test_inplace_op_array(self):
1067 from numpy import array
1068 for op in [
1069 '__iadd__',
1070 '__isub__',
1071 '__imul__',
1072 '__idiv__',
1073 '__ifloordiv__',
1074 '__imod__',
1075 '__ipow__',
1076 '__ilshift__',
1077 '__irshift__',
1078 '__iand__',
1079 '__ior__',
1080 '__ixor__']:
1081 a = b = array(range(5))
1082 c = array(range(5))
1083 d = array(5 * [2])
1084 getattr(a, op).__call__(d)
1085 assert id(a) == id(b)
1086 reg_op = op.replace('__i', '__')
1087 for i in range(5):
1088 assert a[i] == getattr(c[i], reg_op).__call__(d[i])
1089
1090 def test_add_list(self):
1091 from numpy import array, ndarray
1092 a = array(range(5))
1093 b = list(reversed(range(5)))
1094 c = a + b
1095 assert isinstance(c, ndarray)
1096 for i in range(5):
1097 assert c[i] == 4
1098
1099 def test_subtract(self):
1100 from numpy import array
1101 a = array(range(5))
1102 b = a - a
1103 for i in range(5):
1104 assert b[i] == 0
1105
1106 def test_subtract_other(self):
1107 from numpy import array
1108 a = array(range(5))
1109 b = array([1, 1, 1, 1, 1])
1110 c = a - b
1111 for i in range(5):
1112 assert c[i] == i - 1
1113
1114 def test_subtract_constant(self):
1115 from numpy import array
1116 a = array(range(5))
1117 b = a - 5
1118 for i in range(5):
1119 assert b[i] == i - 5
1120
1121 def test_scalar_subtract(self):
1122 from numpy import dtype
1123 int32 = dtype('int32').type
1124 assert int32(2) - 1 == 1
1125 assert 1 - int32(2) == -1
1126
1127 def test_mul(self):
1128 import numpy
1129
1130 a = numpy.array(range(5))
1131 b = a * a
1132 for i in range(5):
1133 assert b[i] == i * i
1134 assert a.dtype.num == b.dtype.num
1135 assert b.dtype is a.dtype
1136
1137 a = numpy.array(range(5), dtype=bool)
1138 b = a * a
1139 assert b.dtype is numpy.dtype(bool)
1140 bool_ = numpy.dtype(bool).type
1141 assert b[0] is bool_(False)
1142 for i in range(1, 5):
1143 assert b[i] is bool_(True)
1144
1145 def test_mul_constant(self):
1146 from numpy import array
1147 a = array(range(5))
1148 b = a * 5
1149 for i in range(5):
1150 assert b[i] == i * 5
1151
1152 def test_div(self):
1153 from math import isnan
1154 from numpy import array, dtype
1155
1156 a = array(range(1, 6))
1157 b = a / a
1158 for i in range(5):
1159 assert b[i] == 1
1160
1161 a = array(range(1, 6), dtype=bool)
1162 b = a / a
1163 assert b.dtype is dtype("int8")
1164 for i in range(5):
1165 assert b[i] == 1
1166
1167 a = array([-1, 0, 1])
1168 b = array([0, 0, 0])
1169 c = a / b
1170 assert (c == [0, 0, 0]).all()
1171
1172 a = array([-1.0, 0.0, 1.0])
1173 b = array([0.0, 0.0, 0.0])
1174 c = a / b
1175 assert c[0] == float('-inf')
1176 assert isnan(c[1])
1177 assert c[2] == float('inf')
1178
1179 b = array([-0.0, -0.0, -0.0])
1180 c = a / b
1181 assert c[0] == float('inf')
1182 assert isnan(c[1])
1183 assert c[2] == float('-inf')
1184
1185 def test_div_other(self):
1186 from numpy import array
1187 a = array(range(5))
1188 b = array([2, 2, 2, 2, 2], float)
1189 c = a / b
1190 for i in range(5):
1191 assert c[i] == i / 2.0
1192
1193 def test_div_constant(self):
1194 from numpy import array
1195 a = array(range(5))
1196 b = a / 5.0
1197 for i in range(5):
1198 assert b[i] == i / 5.0
1199
1200 def test_floordiv(self):
1201 from math import isnan
1202 from numpy import array, dtype
1203
1204 a = array(range(1, 6))
1205 b = a // a
1206 assert (b == [1, 1, 1, 1, 1]).all()
1207
1208 a = array(range(1, 6), dtype=bool)
1209 b = a // a
1210 assert b.dtype is dtype("int8")
1211 assert (b == [1, 1, 1, 1, 1]).all()
1212
1213 a = array([-1, 0, 1])
1214 b = array([0, 0, 0])
1215 c = a // b
1216 assert (c == [0, 0, 0]).all()
1217
1218 a = array([-1.0, 0.0, 1.0])
1219 b = array([0.0, 0.0, 0.0])
1220 c = a // b
1221 assert c[0] == float('-inf')
1222 assert isnan(c[1])
1223 assert c[2] == float('inf')
1224
1225 b = array([-0.0, -0.0, -0.0])
1226 c = a // b
1227 assert c[0] == float('inf')
1228 assert isnan(c[1])
1229 assert c[2] == float('-inf')
1230
1231 def test_floordiv_other(self):
1232 from numpy import array
1233 a = array(range(5))
1234 b = array([2, 2, 2, 2, 2], float)
1235 c = a // b
1236 assert (c == [0, 0, 1, 1, 2]).all()
1237
1238 def test_rfloordiv(self):
1239 from numpy import array
1240 a = array(range(1, 6))
1241 b = 3 // a
1242 assert (b == [3, 1, 1, 0, 0]).all()
1243
1244 def test_floordiv_constant(self):
1245 from numpy import array
1246 a = array(range(5))
1247 b = a // 2
1248 assert (b == [0, 0, 1, 1, 2]).all()
1249
1250 def test_signed_integer_division_overflow(self):
1251 import numpy as np
1252 for s in (8, 16, 32, 64):
1253 for o in ['__div__', '__floordiv__']:
1254 a = np.array([-2**(s-1)], dtype='int%d' % s)
1255 assert getattr(a, o)(-1) == 0
1256
1257 def test_truediv(self):
1258 from operator import truediv
1259 from numpy import arange
1260
1261 assert (truediv(arange(5), 2) == [0., .5, 1., 1.5, 2.]).all()
1262 assert (truediv(2, arange(3)) == [float("inf"), 2., 1.]).all()
1263
1264 def test_divmod(self):
1265 from numpy import arange
1266
1267 a, b = divmod(arange(10), 3)
1268 assert (a == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3]).all()
1269 assert (b == [0, 1, 2, 0, 1, 2, 0, 1, 2, 0]).all()
1270
1271 def test_rdivmod(self):
1272 from numpy import arange
1273
1274 a, b = divmod(3, arange(1, 5))
1275 assert (a == [3, 1, 1, 0]).all()
1276 assert (b == [0, 1, 0, 3]).all()
1277
1278 def test_lshift(self):
1279 from numpy import array
1280
1281 a = array([0, 1, 2, 3])
1282 assert (a << 2 == [0, 4, 8, 12]).all()
1283 a = array([True, False])
1284 assert (a << 2 == [4, 0]).all()
1285 a = array([1.0])
1286 raises(TypeError, lambda: a << 2)
1287
1288 def test_rlshift(self):
1289 from numpy import arange
1290
1291 a = arange(3)
1292 assert (2 << a == [2, 4, 8]).all()
1293
1294 def test_rshift(self):
1295 import numpy as np
1296 a = np.arange(10)
1297 assert (a >> 2 == [0, 0, 0, 0, 1, 1, 1, 1, 2, 2]).all()
1298 a = np.array([True, False])
1299 assert (a >> 1 == [0, 0]).all()
1300 a = np.arange(3, dtype=float)
1301 raises(TypeError, lambda: a >> 1)
1302 a = np.array([123], dtype='uint64')
1303 b = a >> 1
1304 assert b == 61
1305 assert b.dtype.type is np.uint64
1306 a = np.array(123, dtype='uint64')
1307 exc = raises(TypeError, "a >> 1")
1308 assert 'not supported for the input types' in exc.value.message
1309
1310 def test_rrshift(self):
1311 from numpy import arange
1312
1313 a = arange(5)
1314 assert (2 >> a == [2, 1, 0, 0, 0]).all()
1315
1316 def test_pow(self):
1317 from numpy import array
1318 a = array(range(5), float)
1319 b = a ** a
1320 for i in range(5):
1321 assert b[i] == i ** i
1322
1323 a = array(range(5))
1324 assert (a ** 2 == a * a).all()
1325
1326 def test_pow_other(self):
1327 from numpy import array
1328 a = array(range(5), float)
1329 b = array([2, 2, 2, 2, 2])
1330 c = a ** b
1331 for i in range(5):
1332 assert c[i] == i ** 2
1333
1334 def test_pow_constant(self):
1335 from numpy import array
1336 a = array(range(5), float)
1337 b = a ** 2
1338 for i in range(5):
1339 assert b[i] == i ** 2
1340
1341 def test_mod(self):
1342 from numpy import array
1343 a = array(range(1, 6))
1344 b = a % a
1345 for i in range(5):
1346 assert b[i] == 0
1347
1348 a = array(range(1, 6), float)
1349 b = (a + 1) % a
1350 assert b[0] == 0
1351 for i in range(1, 5):
1352 assert b[i] == 1
1353
1354 def test_mod_other(self):
1355 from numpy import array
1356 a = array(range(5))
1357 b = array([2, 2, 2, 2, 2])
1358 c = a % b
1359 for i in range(5):
1360 assert c[i] == i % 2
1361
1362 def test_mod_constant(self):
1363 from numpy import array
1364 a = array(range(5))
1365 b = a % 2
1366 for i in range(5):
1367 assert b[i] == i % 2
1368
1369 def test_rand(self):
1370 from numpy import arange
1371
1372 a = arange(5)
1373 assert (3 & a == [0, 1, 2, 3, 0]).all()
1374
1375 def test_ror(self):
1376 from numpy import arange
1377
1378 a = arange(5)
1379 assert (3 | a == [3, 3, 3, 3, 7]).all()
1380
1381 def test_xor(self):
1382 from numpy import arange
1383
1384 a = arange(5)
1385 assert (a ^ 3 == [3, 2, 1, 0, 7]).all()
1386
1387 def test_rxor(self):
1388 from numpy import arange
1389
1390 a = arange(5)
1391 assert (3 ^ a == [3, 2, 1, 0, 7]).all()
1392
1393 def test_pos(self):
1394 from numpy import array
1395 a = array([1., -2., 3., -4., -5.])
1396 b = +a
1397 for i in range(5):
1398 assert b[i] == a[i]
1399
1400 a = +array(range(5))
1401 for i in range(5):
1402 assert a[i] == i
1403
1404 def test_neg(self):
1405 from numpy import array
1406 a = array([1., -2., 3., -4., -5.])
1407 b = -a
1408 for i in range(5):
1409 assert b[i] == -a[i]
1410
1411 a = -array(range(5), dtype="int8")
1412 for i in range(5):
1413 assert a[i] == -i
1414
1415 def test_abs(self):
1416 from numpy import array
1417 a = array([1., -2., 3., -4., -5.])
1418 b = abs(a)
1419 for i in range(5):
1420 assert b[i] == abs(a[i])
1421
1422 a = abs(array(range(-5, 5), dtype="int8"))
1423 for i in range(-5, 5):
1424 assert a[i + 5] == abs(i)
1425
1426 def test_auto_force(self):
1427 from numpy import array
1428 a = array(range(5))
1429 b = a - 1
1430 a[2] = 3
1431 for i in range(5):
1432 assert b[i] == i - 1
1433
1434 a = array(range(5))
1435 b = a + a
1436 c = b + b
1437 b[1] = 5
1438 assert c[1] == 4
1439
1440 def test_getslice(self):
1441 from numpy import array
1442 a = array(5)
1443 exc = raises(ValueError, "a[:]")
1444 assert exc.value[0] == "cannot slice a 0-d array"
1445 a = array(range(5))
1446 s = a[1:5]
1447 assert len(s) == 4
1448 for i in range(4):
1449 assert s[i] == a[i + 1]
1450
1451 s = (a + a)[1:2]
1452 assert len(s) == 1
1453 assert s[0] == 2
1454 s[:1] = array([5])
1455 assert s[0] == 5
1456
1457 def test_getslice_step(self):
1458 from numpy import array
1459 a = array(range(10))
1460 s = a[1:9:2]
1461 assert len(s) == 4
1462 for i in range(4):
1463 assert s[i] == a[2 * i + 1]
1464
1465 def test_slice_update(self):
1466 from numpy import array
1467 a = array(range(5))
1468 s = a[0:3]
1469 s[1] = 10
1470 assert a[1] == 10
1471 a[2] = 20
1472 assert s[2] == 20
1473
1474 def test_slice_invaidate(self):
1475 # check that slice shares invalidation list with
1476 from numpy import array
1477 a = array(range(5))
1478 s = a[0:2]
1479 b = array([10, 11])
1480 c = s + b
1481 a[0] = 100
1482 assert c[0] == 10
1483 assert c[1] == 12
1484 d = s + b
1485 a[1] = 101
1486 assert d[0] == 110
1487 assert d[1] == 12
1488
1489 def test_sum(self):
1490 from numpy import array, zeros, float16, complex64, str_, isscalar, add
1491 a = array(range(5))
1492 assert a.sum() == 10
1493 assert a[:4].sum() == 6
1494
1495 a = array([True] * 5, bool)
1496 assert a.sum() == 5
1497
1498 assert array([True, False] * 200).sum() == 200
1499 assert array([True, False] * 200, dtype='int8').sum() == 200
1500 assert array([True, False] * 200).sum(dtype='int8') == -56
1501 assert type(array([True, False] * 200, dtype='float16').sum()) is float16
1502 assert type(array([True, False] * 200, dtype='complex64').sum()) is complex64
1503
1504 raises(TypeError, 'a.sum(axis=0, out=3)')
1505 raises(ValueError, 'a.sum(axis=2)')
1506 d = array(0.)
1507 b = a.sum(out=d)
1508 assert b == d
1509 assert b is d
1510 c = array(1.5+2.5j)
1511 assert c.real == 1.5
1512 assert c.imag == 2.5
1513 a.sum(out=c.imag)
1514 assert c.real == 1.5
1515 assert c.imag == 5
1516
1517 assert list(zeros((0, 2)).sum(axis=1)) == []
1518
1519 a = array([1, 2, 3, 4]).sum()
1520 s = isscalar(a)
1521 assert s is True
1522 a = add.reduce([1.0, 2, 3, 4])
1523 s = isscalar(a)
1524 assert s is True,'%r is not a scalar' % type(a)
1525
1526 def test_reduce_nd(self):
1527 from numpy import arange, array
1528 a = arange(15).reshape(5, 3)
1529 assert a.sum() == 105
1530 assert a.sum(keepdims=True) == 105
1531 assert a.sum(keepdims=True).shape == (1, 1)
1532 assert a.max() == 14
1533 assert array([]).sum() == 0.0
1534 assert array([]).reshape(0, 2).sum() == 0.
1535 assert (array([]).reshape(0, 2).sum(0) == [0., 0.]).all()
1536 assert (array([]).reshape(0, 2).prod(0) == [1., 1.]).all()
1537 raises(ValueError, 'array([]).max()')
1538 assert (a.sum(0) == [30, 35, 40]).all()
1539 assert (a.sum(axis=0) == [30, 35, 40]).all()
1540 assert (a.sum(1) == [3, 12, 21, 30, 39]).all()
1541 assert (a.sum(-1) == a.sum(-1)).all()
1542 assert (a.sum(-2) == a.sum(-2)).all()
1543 raises(ValueError, a.sum, -3)
1544 raises(ValueError, a.sum, 2)
1545 assert (a.max(0) == [12, 13, 14]).all()
1546 assert (a.max(1) == [2, 5, 8, 11, 14]).all()
1547 assert ((a + a).max() == 28)
1548 assert ((a + a).max(0) == [24, 26, 28]).all()
1549 assert ((a + a).sum(1) == [6, 24, 42, 60, 78]).all()
1550 a = array(range(105)).reshape(3, 5, 7)
1551 assert (a[:, 1, :].sum(0) == [126, 129, 132, 135, 138, 141, 144]).all()
1552 assert (a[:, 1, :].sum(1) == [70, 315, 560]).all()
1553 raises (ValueError, 'a[:, 1, :].sum(2)')
1554 assert ((a + a).T.sum(2).T == (a + a).sum(0)).all()
1555 assert (a.reshape(1,-1).sum(0) == range(105)).all()
1556 assert (a.reshape(1,-1).sum(1) == 5460)
1557 assert (array([[1,2],[3,4]]).prod(0) == [3, 8]).all()
1558 assert (array([[1,2],[3,4]]).prod(1) == [2, 12]).all()
1559
1560 def test_prod(self):
1561 from numpy import array, dtype
1562 a = array(range(1, 6))
1563 assert a.prod() == 120.0
1564 assert a.prod(keepdims=True) == 120.0
1565 assert a.prod(keepdims=True).shape == (1,)
1566 assert a[:4].prod() == 24.0
1567 for dt in ['bool', 'int8', 'uint8', 'int16', 'uint16']:
1568 a = array([True, False], dtype=dt)
1569 assert a.prod() == 0
1570 assert a.prod().dtype is dtype('uint' if dt[0] == 'u' else 'int')
1571 for dt in ['l', 'L', 'q', 'Q', 'e', 'f', 'd', 'F', 'D']:
1572 a = array([True, False], dtype=dt)
1573 assert a.prod() == 0
1574 assert a.prod().dtype is dtype(dt)
1575
1576 def test_max(self):
1577 from numpy import array, zeros
1578 a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
1579 assert a.max() == 5.7
1580 assert a.max().shape == ()
1581 assert a.max(axis=(0,)) == 5.7
1582 assert a.max(axis=(0,)).shape == ()
1583 assert a.max(keepdims=True) == 5.7
1584 assert a.max(keepdims=True).shape == (1,)
1585 b = array([])
1586 raises(ValueError, "b.max()")
1587 assert list(zeros((0, 2)).max(axis=1)) == []
1588
1589 def test_max_add(self):
1590 from numpy import array
1591 a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
1592 assert (a + a).max() == 11.4
1593
1594 def test_min(self):
1595 from numpy import array, zeros
1596 a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
1597 assert a.min() == -3.0
1598 assert a.min().shape == ()
1599 assert a.min(axis=(0,)) == -3.0
1600 assert a.min(axis=(0,)).shape == ()
1601 assert a.min(keepdims=True) == -3.0
1602 assert a.min(keepdims=True).shape == (1,)
1603 b = array([])
1604 raises(ValueError, "b.min()")
1605 assert list(zeros((0, 2)).min(axis=1)) == []
1606
1607 def test_argmax(self):
1608 from numpy import array
1609 a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
1610 r = a.argmax()
1611 assert r == 2
1612 b = array([])
1613 raises(ValueError, b.argmax)
1614
1615 a = array(range(-5, 5))
1616 r = a.argmax()
1617 assert r == 9
1618 b = a[::2]
1619 r = b.argmax()
1620 assert r == 4
1621 r = (a + a).argmax()
1622 assert r == 9
1623 a = array([1, 0, 0])
1624 assert a.argmax() == 0
1625 a = array([0, 0, 1])
1626 assert a.argmax() == 2
1627
1628 a = array([[1, 2], [3, 4], [5, 6]])
1629 assert a.argmax() == 5
1630 assert a.argmax(axis=None, out=None) == 5
1631 assert a[:2, ].argmax() == 3
1632 assert (a.argmax(axis=0) == array([2, 2])).all()
1633
1634 def test_argmin(self):
1635 import numpy as np
1636 a = np.array([-1.2, 3.4, 5.7, -3.0, 2.7])
1637 assert a.argmin() == 3
1638 assert a.argmin(axis=0) == 3
1639 assert a.argmin(axis=None, out=None) == 3
1640 b = np.array([])
1641 raises(ValueError, "b.argmin()")
1642 c = np.arange(6).reshape(2, 3)
1643 assert c.argmin() == 0
1644 assert (c.argmin(axis=0) == np.array([0, 0, 0])).all()
1645 assert (c.argmin(axis=1) == [0, 0]).all()
1646
1647
1648 def test_all(self):
1649 from numpy import array
1650 a = array(range(5))
1651 assert a.all() == False
1652 a[0] = 3.0
1653 assert a.all() == True
1654 assert a.all(keepdims=True) == True
1655 assert a.all(keepdims=True).shape == (1,)
1656 b = array([])
1657 assert b.all() == True
1658
1659 def test_any(self):
1660 from numpy import array, zeros
1661 a = array(range(5))
1662 assert a.any() == True
1663 assert a.any(keepdims=True) == True
1664 assert a.any(keepdims=True).shape == (1,)
1665 b = zeros(5)
1666 assert b.any() == False
1667 c = array([])
1668 assert c.any() == False
1669
1670 def test_dtype_guessing(self):
1671 from numpy import array, dtype
1672 import sys
1673 assert array([True]).dtype is dtype(bool)
1674 assert array([True, False]).dtype is dtype(bool)
1675 assert array([True, 1]).dtype is dtype(int)
1676 assert array([1, 2, 3]).dtype is dtype(int)
1677 assert array([1L, 2, 3]).dtype is dtype('q')
1678 assert array([1.2, True]).dtype is dtype(float)
1679 assert array([1.2, 5]).dtype is dtype(float)
1680 assert array([]).dtype is dtype(float)
1681 float64 = dtype('float64').type
1682 int8 = dtype('int8').type
1683 bool_ = dtype('bool').type
1684 assert array([float64(2)]).dtype is dtype(float)
1685 assert array([int8(3)]).dtype is dtype("int8")
1686 assert array([bool_(True)]).dtype is dtype(bool)
1687 assert array([bool_(True), 3.0]).dtype is dtype(float)
1688 assert array(sys.maxint + 42).dtype is dtype('Q')
1689 assert array([sys.maxint + 42] * 2).dtype is dtype('Q')
1690 assert array([sys.maxint + 42, 123]).dtype is dtype(float)
1691 assert array([sys.maxint + 42, 123L]).dtype is dtype(float)
1692 assert array([1+2j, 123]).dtype is dtype(complex)
1693 assert array([1+2j, 123L]).dtype is dtype(complex)
1694
1695 def test_comparison(self):
1696 import operator
1697 from numpy import array, dtype
1698
1699 a = array(range(5))
1700 b = array(range(5), float)
1701 for func in [
1702 operator.eq, operator.ne, operator.lt, operator.le, operator.gt,
1703 operator.ge
1704 ]:
1705 c = func(a, 3)
1706 assert c.dtype is dtype(bool)
1707 for i in xrange(5):
1708 assert c[i] == func(a[i], 3)
1709
1710 c = func(b, 3)
1711 assert c.dtype is dtype(bool)
1712 for i in xrange(5):
1713 assert c[i] == func(b[i], 3)
1714
1715 def test___nonzero__(self):
1716 from numpy import array
1717 a = array([1, 2])
1718 raises(ValueError, bool, a)
1719 raises(ValueError, bool, a == a)
1720 assert bool(array(1))
1721 assert not bool(array(0))
1722 assert bool(array([1]))
1723 assert not bool(array([0]))
1724
1725 def test_slice_assignment(self):
1726 from numpy import array
1727 a = array(range(5))
1728 a[::-1] = a
1729 assert (a == [4, 3, 2, 1, 0]).all()
1730 # but we force intermediates
1731 a = array(range(5))
1732 a[::-1] = a + a
1733 assert (a == [8, 6, 4, 2, 0]).all()
1734
1735 def test_virtual_views(self):
1736 from numpy import arange
1737 a = arange(15)
1738 c = (a + a)
1739 d = c[::2]
1740 assert d[3] == 12
1741 c[6] = 5
1742 assert d[3] == 5
1743 a = arange(15)
1744 c = (a + a)
1745 d = c[::2][::2]
1746 assert d[1] == 8
1747 b = a + a
1748 c = b[::2]
1749 c[:] = 3
1750 assert b[0] == 3
1751 assert b[1] == 2
1752
1753 def test_realimag_views(self):
1754 from numpy import arange, array
1755 a = array(1.5)
1756 assert a.real == 1.5
1757 assert a.imag == 0.0
1758 a = array([1.5, 2.5])
1759 assert (a.real == [1.5, 2.5]).all()
1760 assert (a.imag == [0.0, 0.0]).all()
1761 a = arange(15)
1762 b = a.real
1763 b[5]=50
1764 assert a[5] == 50
1765 b = a.imag
1766 assert b[7] == 0
1767 raises(ValueError, 'b[7] = -2')
1768 raises(TypeError, 'a.imag = -2')
1769 a = array(['abc','def'],dtype='S3')
1770 b = a.real
1771 assert a[0] == b[0]
1772 assert a[1] == b[1]
1773 b[1] = 'xyz'
1774 assert a[1] == 'xyz'
1775 assert a.imag[0] == ''
1776 raises(TypeError, 'a.imag = "qop"')
1777 a=array([[1+1j, 2-3j, 4+5j],[-6+7j, 8-9j, -2-1j]])
1778 assert a.real[0,1] == 2
1779 a.real[0,1] = -20
1780 assert a[0,1].real == -20
1781 b = a.imag
1782 assert b[1,2] == -1
1783 b[1,2] = 30
1784 assert a[1,2].imag == 30
1785 a.real = 13
1786 assert a[1,1].real == 13
1787 a=array([1+1j, 2-3j, 4+5j, -6+7j, 8-9j, -2-1j])
1788 a.real = 13
1789 assert a[3].real == 13
1790 a.imag = -5
1791 a.imag[3] = -10
1792 assert a[3].imag == -10
1793 assert a[2].imag == -5
1794
1795 assert arange(4, dtype='>c8').imag.max() == 0.0
1796 assert arange(4, dtype='<c8').imag.max() == 0.0
1797 assert arange(4, dtype='>c8').real.max() == 3.0
1798 assert arange(4, dtype='<c8').real.max() == 3.0
1799
1800 def test_scalar_view(self):
1801 from numpy import array
1802 import sys
1803 a = array(3, dtype='int32')
1804 b = a.view(dtype='float32')
1805 assert b.shape == ()
1806 assert b < 1
1807 exc = raises(ValueError, a.view, 'int8')
1808 assert exc.value[0] == "new type not compatible with array."
1809 exc = raises(TypeError, a.view, 'string')
1810 assert exc.value[0] == "data-type must not be 0-sized"
1811 if sys.byteorder == 'big':
1812 assert a.view('S4') == '\x00\x00\x00\x03'
1813 else:
1814 assert a.view('S4') == '\x03'
1815 a = array('abc1', dtype='c')
1816 assert (a == ['a', 'b', 'c', '1']).all()
1817 assert a.view('S4') == 'abc1'
1818 b = a.view([('a', 'i2'), ('b', 'i2')])
1819 assert b.shape == (1,)
1820 if sys.byteorder == 'big':
1821 assert b[0][0] == 0x6162
1822 assert b[0][1] == 0x6331
1823 else:
1824 assert b[0][0] == 25185
1825 assert b[0][1] == 12643
1826 a = array([(1, 2)], dtype=[('a', 'int64'), ('b', 'int64')])[0]
1827 assert a.shape == ()
1828 if sys.byteorder == 'big':
1829 assert a.view('S16') == '\x00' * 7 + '\x01' + '\x00' * 7 + '\x02'
1830 else:
1831 assert a.view('S16') == '\x01' + '\x00' * 7 + '\x02'
1832 a = array(2, dtype='<i8')
1833 b = a.view('<c8')
1834 assert 0 < b.real < 1
1835 assert b.real.tostring() == '\x02\x00\x00\x00'
1836 assert b.imag.tostring() == '\x00' * 4
1837
1838 def test_array_view(self):
1839 from numpy import array, dtype
1840 import sys
1841 x = array((1, 2), dtype='int8')
1842 assert x.shape == (2,)
1843 y = x.view(dtype='int16')
1844 assert x.shape == (2,)
1845 if sys.byteorder == 'big':
1846 assert y[0] == 0x0102
1847 else:
1848 assert y[0] == 513 == 0x0201
1849 assert y.dtype == dtype('int16')
1850 y[0] = 670
1851 if sys.byteorder == 'little':
1852 assert x[0] == -98
1853 assert x[1] == 2
1854 else:
1855 assert x[0] == 2
1856 assert x[1] == -98
1857 f = array([1000, -1234], dtype='i4')
1858 nnp = self.non_native_prefix
1859 d = f.view(dtype=nnp + 'i4')
1860 assert (d == [-402456576, 788267007]).all()
1861 x = array(range(15), dtype='i2').reshape(3,5)
1862 exc = raises(ValueError, x.view, dtype='i4')
1863 assert exc.value[0] == "new type not compatible with array."
1864 exc = raises(TypeError, x.view, 'string')
1865 assert exc.value[0] == "data-type must not be 0-sized"
1866 assert x.view('int8').shape == (3, 10)
1867 x = array(range(15), dtype='int16').reshape(3,5).T
1868 assert x.view('int8').shape == (10, 3)
1869 #assert x.view('S2')[1][1] == '\x06'
1870 x = array(['abc', 'defg'], dtype='c')
1871 assert x.view('S1')[0] == 'a'
1872 assert x.view('S1')[1] == 'd'
1873 x = array(['abc', 'defg'], dtype='string')
1874 assert x.view('S4')[0] == 'abc'
1875 assert x.view('S4')[1] == 'defg'
1876 a = array([(1, 2)], dtype=[('a', 'int64'), ('b', 'int64')])
1877 if sys.byteorder == 'big':
1878 assert a.view('S16')[0] == '\x00' * 7 + '\x01' + '\x00' * 7 + '\x02'
1879 else:
1880 assert a.view('S16')[0] == '\x01' + '\x00' * 7 + '\x02'
1881
1882 def test_half_conversions(self):
1883 from numpy import array
1884 from math import isnan, isinf
1885 e = array([0, -1, -float('inf'), float('nan'), 6], dtype='float16')
1886 assert map(isnan, e) == [False, False, False, True, False]
1887 assert map(isinf, e) == [False, False, True, False, False]
1888 assert e.argmax() == 3
1889
1890 def test_half_conversions_preserve_nan_payload_float32(self):
1891 # self.machine comes from test_base.py
1892 if self.machine.startswith('riscv'):
1893 py.test.skip('riscv does not preserve nan payload in '
1894 'float64->float32 conversion')
1895 from numpy import array, arange
1896 # numpy preserves value for uint16 -> cast_as_float16 ->
1897 # convert_to_float64 -> convert_to_float16 -> uint16
1898 # even for float16 various float16 nans
1899 all_f16 = arange(0xfe00, 0xffff, dtype='uint16')
1900 all_f16.dtype = 'float16'
1901 all_f32 = array(all_f16, dtype='float32')
1902 b = array(all_f32, dtype='float16')
1903 c = b.view(dtype='uint16')
1904 d = all_f16.view(dtype='uint16')
1905 assert (c == d).all()
1906
1907 def test_half_conversions_preserve_nan_payload_float64(self):
1908 from numpy import array, arange
1909 # numpy preserves value for uint16 -> cast_as_float16 ->
1910 # convert_to_float64 -> convert_to_float16 -> uint16
1911 # even for float16 various float16 nans
1912 all_f16 = arange(0xfe00, 0xffff, dtype='uint16')
1913 all_f16.dtype = 'float16'
1914 all_f64 = array(all_f16, dtype='float64')
1915 b = array(all_f64, dtype='float16')
1916 c = b.view(dtype='uint16')
1917 d = all_f16.view(dtype='uint16')
1918 assert (c == d).all()
1919
1920 def test_ndarray_view_empty(self):
1921 from numpy import array, dtype
1922 x = array([], dtype=[('a', 'int8'), ('b', 'int8')])
1923 y = x.view(dtype='int16')
1924
1925 def test_view_of_slice(self):
1926 from numpy import empty, dtype
1927 x = empty([6], 'uint32')
1928 x.fill(0xdeadbeef)
1929 s = x[::3]
1930 exc = raises(ValueError, s.view, 'uint8')
1931 assert exc.value[0] == 'new type not compatible with array.'
1932 s[...] = 2
1933 v = s.view(x.__class__)
1934 assert v.strides == s.strides
1935 assert v.base is s.base
1936 assert (v == 2).all()
1937 y = empty([6,6], 'uint32')
1938 s = y.swapaxes(0, 1)
1939 v = s.view(y.__class__)
1940 assert v.strides == (4, 24)
1941
1942 x = empty([12, 8, 8], 'float64')
1943 y = x[::-4, :, :]
1944 assert y.base is x
1945 assert y.strides == (-2048, 64, 8)
1946 y[:] = 1000
1947 assert x[-1, 0, 0] == 1000
1948
1949 a = empty([3, 2, 1], dtype='float64')
1950 b = a.view(dtype('uint32'))
1951 assert b.strides == (16, 8, 4)
1952 assert b.shape == (3, 2, 2)
1953 b.fill(0xdeadbeef)
1954
1955 def test_tolist_scalar(self):
1956 from numpy import dtype
1957 int32 = dtype('int32').type
1958 bool_ = dtype('bool').type
1959 x = int32(23)
1960 assert x.tolist() == 23
1961 assert type(x.tolist()) is int
1962 y = bool_(True)
1963 assert y.tolist() is True
1964
1965 def test_tolist_zerodim(self):
1966 from numpy import array
1967 x = array(3)
1968 assert x.tolist() == 3
1969 assert type(x.tolist()) is int
1970
1971 def test_tolist_singledim(self):
1972 from numpy import array
1973 a = array(range(5))
1974 assert a.tolist() == [0, 1, 2, 3, 4]
1975 assert type(a.tolist()[0]) is int
1976 b = array([0.2, 0.4, 0.6])
1977 assert b.tolist() == [0.2, 0.4, 0.6]
1978
1979 def test_tolist_multidim(self):
1980 from numpy import array
1981 a = array([[1, 2], [3, 4]])
1982 assert a.tolist() == [[1, 2], [3, 4]]
1983
1984 def test_tolist_view(self):
1985 from numpy import array
1986 a = array([[1, 2], [3, 4]])
1987 assert (a + a).tolist() == [[2, 4], [6, 8]]
1988
1989 def test_tolist_object(self):
1990 from numpy import array
1991 a = array([0], dtype=object)
1992 assert a.tolist() == [0]
1993
1994 def test_tolist_object_slice(self):
1995 from numpy import array
1996 list_expected = [slice(0, 1), 0]
1997 a = array(list_expected, dtype=object)
1998 assert a.tolist() == list_expected
1999
2000 def test_tolist_object_slice_2d(self):
2001 from numpy import array
2002 a = array([(slice(0, 1), 1), (0, 1)], dtype=object)
2003 assert a.tolist() == [[slice(0, 1, None), 1], [0, 1]]
2004
2005 def test_tolist_slice(self):
2006 from numpy import array
2007 a = array([[17.1, 27.2], [40.3, 50.3]])
2008 assert a[:, 0].tolist() == [17.1, 40.3]
2009 assert a[0].tolist() == [17.1, 27.2]
2010
2011 def test_concatenate(self):
2012 from numpy import array, concatenate, dtype
2013 exc = raises(ValueError, concatenate, (array(1.5), array(2.5)))
2014 assert exc.value[0] == 'zero-dimensional arrays cannot be concatenated'
2015 a = concatenate((array(1.5), array(2.5)), axis=None)
2016 assert (a == [1.5, 2.5]).all()
2017 assert exc.value[0] == 'zero-dimensional arrays cannot be concatenated'
2018 exc = raises(ValueError, concatenate, (array([1.5]), array(2.5)))
2019 assert exc.value[0] == 'all the input arrays must have same number ' \
2020 'of dimensions'
2021 exc = raises(ValueError, concatenate, (array(1.5), array([2.5])))
2022 assert exc.value[0] == 'zero-dimensional arrays cannot be concatenated'
2023 a = concatenate((array([1.5]), array([2.5])))
2024 assert (a == [1.5, 2.5]).all()
2025 a1 = array([0,1,2])
2026 a2 = array([3,4,5])
2027 a = concatenate((a1, a2))
2028 assert len(a) == 6
2029 assert (a == [0,1,2,3,4,5]).all()
2030 assert a.dtype is dtype(int)
2031 a = concatenate((a1, a2), axis=0)
2032 assert (a == [0,1,2,3,4,5]).all()
2033 a = concatenate((a1, a2), axis=-1)
2034 assert (a == [0,1,2,3,4,5]).all()
2035 a = concatenate((a1, a2), axis=None)
2036 assert (a == [0,1,2,3,4,5]).all()
2037
2038 b1 = array([[1, 2], [3, 4]])
2039 b2 = array([[5, 6]])
2040 b = concatenate((b1, b2), axis=0)
2041 assert (b == [[1, 2],[3, 4],[5, 6]]).all()
2042 c = concatenate((b1, b2.T), axis=1)
2043 assert (c == [[1, 2, 5],[3, 4, 6]]).all()
2044 c1 = concatenate((b1, b2), axis=None)
2045 assert (c1 == [1, 2, 3, 4, 5, 6]).all()
2046 d = concatenate(([0],[1]))
2047 assert (d == [0,1]).all()
2048 e1 = array([[0,1],[2,3]])
2049 e = concatenate(e1)
2050 assert (e == [0,1,2,3]).all()
2051 f1 = array([0,1])
2052 f = concatenate((f1, [2], f1, [7]))
2053 assert (f == [0,1,2,0,1,7]).all()
2054
2055 g1 = array([[0,1,2]])
2056 g2 = array([[3,4,5]])
2057 g = concatenate((g1, g2), axis=-2)
2058 assert (g == [[0,1,2],[3,4,5]]).all()
2059 exc = raises(IndexError, concatenate, (g1, g2), axis=-3)
2060 assert str(exc.value) == "axis -3 out of bounds [0, 2)"
2061 exc = raises(IndexError, concatenate, (g1, g2), axis=2)
2062 assert str(exc.value) == "axis 2 out of bounds [0, 2)"
2063
2064 exc = raises(ValueError, concatenate, ())
2065 assert str(exc.value) == \
2066 "need at least one array to concatenate"
2067
2068 exc = raises(ValueError, concatenate, (a1, b1), axis=0)
2069 assert str(exc.value) == \
2070 "all the input arrays must have same number of dimensions"
2071
2072 exc = raises(ValueError, concatenate, (b1, b2), axis=1)
2073 assert str(exc.value) == \
2074 "all the input array dimensions except for the " \
2075 "concatenation axis must match exactly"
2076
2077 g1 = array([0,1,2])
2078 g2 = array([[3,4,5]])
2079 exc = raises(ValueError, concatenate, (g1, g2), axis=0)
2080 assert str(exc.value) == \
2081 "all the input arrays must have same number of dimensions"
2082
2083 a = array([1, 2, 3, 4, 5, 6])
2084 a = (a + a)[::2]
2085 b = concatenate((a[:3], a[-3:]))
2086 assert (b == [2, 6, 10, 2, 6, 10]).all()
2087 a = concatenate((array([1]), array(['abc'])))
2088 if dtype('l').itemsize == 4: # 32-bit platform
2089 assert str(a.dtype) == '|S11'
2090 else:
2091 assert str(a.dtype) == '|S21'
2092 a = concatenate((array([]), array(['abc'])))
2093 assert a[0] == 'abc'
2094 a = concatenate((['abcdef'], ['abc']))
2095 assert a[0] == 'abcdef'
2096 assert str(a.dtype) == '|S6'
2097
2098 def test_record_concatenate(self):
2099 # only an exact match can succeed
2100 from numpy import zeros, concatenate
2101 a = concatenate((zeros((2,),dtype=[('x', int), ('y', float)]),
2102 zeros((2,),dtype=[('x', int), ('y', float)])))
2103 assert a.shape == (4,)
2104 exc = raises(TypeError, concatenate,
2105 (zeros((2,), dtype=[('x', int), ('y', float)]),
2106 (zeros((2,), dtype=[('x', float), ('y', float)]))))
2107 assert str(exc.value).startswith('invalid type promotion')
2108 exc = raises(TypeError, concatenate, ([1], zeros((2,),
2109 dtype=[('x', int), ('y', float)])))
2110 assert str(exc.value).startswith('invalid type promotion')
2111 exc = raises(TypeError, concatenate, (['abc'], zeros((2,),
2112 dtype=[('x', int), ('y', float)])))
2113 assert str(exc.value).startswith('invalid type promotion')
2114
2115 def test_flatten(self):
2116 from numpy import array
2117
2118 assert array(3).flatten().shape == (1,)
2119 a = array([[1, 2], [3, 4]])
2120 b = a.flatten()
2121 c = a.ravel()
2122 a[0, 0] = 15
2123 assert b[0] == 1
2124 assert c[0] == 15
2125 a = array([[1, 2, 3], [4, 5, 6]])
2126 assert (a.flatten() == [1, 2, 3, 4, 5, 6]).all()
2127 a = array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
2128 assert (a.flatten() == [1, 2, 3, 4, 5, 6, 7, 8]).all()
2129 a = array([1, 2, 3, 4, 5, 6, 7, 8])
2130 assert (a[::2].flatten() == [1, 3, 5, 7]).all()
2131 a = array([1, 2, 3])
2132 assert ((a + a).flatten() == [2, 4, 6]).all()
2133 a = array(2)
2134 assert (a.flatten() == [2]).all()
2135 a = array([[1, 2], [3, 4]])
2136 assert (a.T.flatten() == [1, 3, 2, 4]).all()
2137
2138 def test_itemsize(self):
2139 from numpy import ones, dtype, array
2140
2141 for obj in [float, bool, int]:
2142 assert ones(1, dtype=obj).itemsize == dtype(obj).itemsize
2143 assert (ones(1) + ones(1)).itemsize == 8
2144 assert array(1.0).itemsize == 8
2145 assert ones(1)[:].itemsize == 8
2146
2147 def test_nbytes(self):
2148 from numpy import array, ones
2149
2150 assert ones(1).nbytes == 8
2151 assert ones((2, 2)).nbytes == 32
2152 assert ones((2, 2))[1:,].nbytes == 16
2153 assert (ones(1) + ones(1)).nbytes == 8
2154 assert array(3.0).nbytes == 8
2155
2156 def test_repeat(self):
2157 from numpy import array
2158 a = array([[1, 2], [3, 4]])
2159 assert (a.repeat(3) == [1, 1, 1, 2, 2, 2,
2160 3, 3, 3, 4, 4, 4]).all()
2161 assert (a.repeat(2, axis=0) == [[1, 2], [1, 2], [3, 4],
2162 [3, 4]]).all()
2163 assert (a.repeat(2, axis=1) == [[1, 1, 2, 2], [3, 3,
2164 4, 4]]).all()
2165 assert (array([1, 2]).repeat(2) == array([1, 1, 2, 2])).all()
2166
2167 def test_resize(self):
2168 import numpy as np
2169 a = np.array([1,2,3])
2170 import sys
2171 if '__pypy__' in sys.builtin_module_names:
2172 raises(NotImplementedError, a.resize, ())
2173
2174 def test_squeeze(self):
2175 import numpy as np
2176 a = np.array([1,2,3])
2177 assert a.squeeze() is a
2178 a = np.array([[1,2,3]])
2179 b = a.squeeze()
2180 assert b.shape == (3,)
2181 assert (b == a).all()
2182 b[1] = -1
2183 assert a[0][1] == -1
2184 a = np.arange(9).reshape((3, 1, 3, 1))
2185 b = a.squeeze(1)
2186 assert b.shape == (3, 3, 1)
2187 b = a.squeeze((1,))
2188 assert b.shape == (3, 3, 1)
2189 b = a.squeeze((1, -1))
2190 assert b.shape == (3, 3)
2191 exc = raises(ValueError, a.squeeze, 5)
2192 assert exc.value.message == "'axis' entry 5 is out of bounds [-4, 4)"
2193 exc = raises(ValueError, a.squeeze, 0)
2194 assert exc.value.message == "cannot select an axis to squeeze out " \
2195 "which has size not equal to one"
2196 exc = raises(ValueError, a.squeeze, (1, 1))
2197 assert exc.value.message == "duplicate value in 'axis'"
2198
2199 def test_swapaxes(self):
2200 from numpy import array
2201 x = array([])
2202 raises(ValueError, x.swapaxes,0, 2)
2203 x = array([[1, 2]])
2204 assert x.swapaxes(0, 0) is not x
2205 exc = raises(ValueError, x.swapaxes, -3, 0)
2206 assert exc.value.message == "bad axis1 argument to swapaxes"
2207 exc = raises(ValueError, x.swapaxes, 0, 3)
2208 assert exc.value.message == "bad axis2 argument to swapaxes"
2209 # testcases from numpy docstring
2210 x = array([[1, 2, 3]])
2211 assert (x.swapaxes(0, 1) == array([[1], [2], [3]])).all()
2212 x = array([[[0,1],[2,3]],[[4,5],[6,7]]]) # shape = (2, 2, 2)
2213 assert (x.swapaxes(0, 2) == array([[[0, 4], [2, 6]],
2214 [[1, 5], [3, 7]]])).all()
2215 assert (x.swapaxes(0, 1) == array([[[0, 1], [4, 5]],
2216 [[2, 3], [6, 7]]])).all()
2217 assert (x.swapaxes(1, 2) == array([[[0, 2], [1, 3]],
2218 [[4, 6],[5, 7]]])).all()
2219
2220 # more complex shape i.e. (2, 2, 3)
2221 x = array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
2222 assert (x.swapaxes(0, 1) == array([[[1, 2, 3], [7, 8, 9]],
2223 [[4, 5, 6], [10, 11, 12]]])).all()
2224 assert (x.swapaxes(0, 2) == array([[[1, 7], [4, 10]], [[2, 8], [5, 11]],
2225 [[3, 9], [6, 12]]])).all()
2226 assert (x.swapaxes(1, 2) == array([[[1, 4], [2, 5], [3, 6]],
2227 [[7, 10], [8, 11],[9, 12]]])).all()
2228
2229 # test slice
2230 assert (x[0:1,0:2].swapaxes(0,2) == array([[[1], [4]], [[2], [5]],
2231 [[3], [6]]])).all()
2232 # test virtual
2233 assert ((x + x).swapaxes(0,1) == array([[[ 2, 4, 6], [14, 16, 18]],
2234 [[ 8, 10, 12], [20, 22, 24]]])).all()
2235 raises(ValueError, array(1).swapaxes, 10, 12)
2236
2237 def test_filter_bug(self):
2238 from numpy import array
2239 a = array([1.0,-1.0])
2240 a[a<0] = -a[a<0]
2241 assert (a == [1, 1]).all()
2242
2243 def test_int_list_index(slf):
2244 from numpy import array, arange
2245 assert (array([10,11,12,13])[[1,2]] == [11, 12]).all()
2246 assert (arange(6).reshape((2,3))[[0,1]] == [[0, 1, 2], [3, 4, 5]]).all()
2247 assert arange(6).reshape((2,3))[(0,1)] == 1
2248
2249 def test_int_array_index(self):
2250 from numpy import array, arange, zeros
2251 b = arange(10)[array([3, 2, 1, 5])]
2252 assert (b == [3, 2, 1, 5]).all()
2253 raises(IndexError, "arange(10)[array([10])]")
2254 assert (arange(10)[[-5, -3]] == [5, 7]).all()
2255 raises(IndexError, "arange(10)[[-11]]")
2256 a = arange(1)
2257 a[[0, 0]] += 1
2258 assert a[0] == 1
2259 assert (zeros(1)[[]] == []).all()
2260
2261 def test_int_array_index_setitem(self):
2262 from numpy import arange, zeros, array
2263 a = arange(10)
2264 a[[3, 2, 1, 5]] = zeros(4, dtype=int)
2265 assert (a == [0, 0, 0, 0, 4, 0, 6, 7, 8, 9]).all()
2266 a[[-9, -8]] = [1, 1]
2267 assert (a == [0, 1, 1, 0, 4, 0, 6, 7, 8, 9]).all()
2268 raises(IndexError, "arange(10)[array([10])] = 3")
2269 raises(IndexError, "arange(10)[[-11]] = 3")
2270 a = zeros(10)
2271 b = array([3,4,5])
2272 a[b] = 1
2273 assert (a == [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]).all()
2274
2275 def test_array_scalar_index(self):
2276 import numpy as np
2277 a = np.array([[1, 2, 3],
2278 [4, 5, 6],
2279 [7, 8, 9]])
2280 assert (a[np.array(0)] == a[0]).all()
2281 assert (a[np.array(1)] == a[1]).all()
2282 exc = raises(IndexError, "a[np.array(True)]")
2283 assert exc.value.message == 'in the future, 0-d boolean arrays will be interpreted as a valid boolean index'
2284 exc = raises(IndexError, "a[np.array(1.1)]")
2285 assert exc.value.message == 'arrays used as indices must be of ' \
2286 'integer (or boolean) type'
2287
2288 a[np.array(1)] = a[2]
2289 assert a[1][1] == 8
2290 exc = raises(IndexError, "a[np.array(1.1)] = a[2]")
2291 assert exc.value.message == 'arrays used as indices must be of ' \
2292 'integer (or boolean) type'
2293
2294 def test_bool_array_index(self):
2295 from numpy import arange, array
2296 b = arange(10)
2297 assert (b[array([True, False, True])] == [0, 2]).all()
2298 raises(IndexError, "array([1, 2])[array([True, True, True])]")
2299 raises(IndexError, "b[array([[True, False], [True, False]])]")
2300 a = array([[1,2,3],[4,5,6],[7,8,9]],int)
2301 c = array([True,False,True],bool)
2302 b = a[c]
2303 assert (a[c] == [[1, 2, 3], [7, 8, 9]]).all()
2304 c = array([True])
2305 b = a[c]
2306 assert b.shape == (1, 3)
2307
2308 def test_bool_array_index_setitem(self):
2309 from numpy import arange, array
2310 b = arange(5)
2311 b[array([True, False, True])] = [20, 21, 0, 0, 0, 0, 0]
2312 assert (b == [20, 1, 21, 3, 4]).all()
2313 raises(IndexError, "array([1, 2])[array([True, False, True])] = [1, 2, 3]")
2314
2315 def test_weakref(self):
2316 import _weakref
2317 from numpy import array
2318 a = array([1, 2, 3])
2319 assert _weakref.ref(a)
2320 a = array(42)
2321 assert _weakref.ref(a)
2322
2323 def test_astype(self):
2324 from numpy import array, arange, empty
2325 b = array(1).astype(float)
2326 assert b == 1
2327 assert b.dtype == float
2328 b = array([1, 2]).astype(float)
2329 assert (b == [1, 2]).all()
2330 assert b.dtype == 'float'
2331 b = array([1, 2], dtype=complex).astype(int)
2332 assert (b == [1, 2]).all()
2333 assert b.dtype == 'int'
2334 b = array([0, 1, 2], dtype=complex).astype(bool)
2335 assert (b == [False, True, True]).all()
2336 assert b.dtype == 'bool'
2337
2338 a = arange(11)[::-1]
2339 b = a.astype('int32')
2340 assert (b == a).all()
2341
2342 a = arange(6, dtype='f4').reshape(2,3)
2343 b = a.T.astype('i4')
2344 assert (a.T.strides == b.strides)
2345
2346 a = array('x').astype('S3').dtype
2347 assert a.itemsize == 3
2348 # scalar vs. array
2349 a = array([1, 2, 3.14156]).astype('S3').dtype
2350 assert a.itemsize == 3
2351 a = array(3.1415).astype('S3').dtype
2352 assert a.itemsize == 3
2353
2354 a = array(['1', '2','3']).astype(float)
2355 assert a[2] == 3.0
2356
2357 a = array('123')
2358 assert a.astype('S0').dtype == 'S3'
2359 assert a.astype('i8') == 123
2360 a = array('abcdefgh')
2361 exc = raises(ValueError, a.astype, 'i8')
2362 assert exc.value.message.startswith('invalid literal for int()')
2363
2364 a = arange(5, dtype=complex)
2365 b = a.real
2366 c = b.astype("int64")
2367 assert c.shape == b.shape
2368 assert c.strides == (8,)
2369
2370 exc = raises(TypeError, a.astype, 'i8', casting='safe')
2371 assert exc.value.message.startswith(
2372 "Cannot cast array from dtype('complex128') to dtype('int64')")
2373 a = arange(6, dtype='f4').reshape(2, 3)
2374 b = a.astype('f4', copy=False)
2375 assert a is b
2376 b = a.astype('f4', order='C', copy=False)
2377 assert a is b
2378
2379 a = empty([3, 3, 3, 3], 'uint8')
2380 a[:] = 0
2381 b = a[2]
2382 c = b[:, :2, :]
2383 d = c.swapaxes(1, -1)
2384 e = d.astype('complex128')
2385 assert e.shape == (3, 3, 2)
2386 assert e.strides == (96, 16, 48)
2387 assert (e.real == d).all()
2388
2389 def test_base(self):
2390 from numpy import array, empty
2391 assert array(1).base is None
2392 assert array([1, 2]).base is None
2393 a = array([1, 2, 3, 4])
2394 b = a[::2]
2395 assert b.base is a
2396
2397 a = empty([3, 3, 3, 3], 'uint8')
2398 a[:] = 0
2399 b = a[2]
2400 assert b.base.base is None
2401 c = b[:, :2, :]
2402 d = c.swapaxes(1, -1)
2403 assert c.base.base is None
2404 assert d.base.base is None
2405 assert d.shape == (3, 3, 2)
2406 assert d.__array_interface__['data'][0] == \
2407 a.__array_interface__['data'][0] + a.strides[0] * 2
2408
2409 def test_byteswap(self):
2410 from numpy import array
2411
2412 s1 = array(1.).byteswap().tostring()
2413 s2 = array([1.]).byteswap().tostring()
2414 assert s1 == s2
2415
2416 a = array([1, 256 + 2, 3], dtype='i2')
2417 assert (a.byteswap() == [0x0100, 0x0201, 0x0300]).all()
2418 assert (a == [1, 256 + 2, 3]).all()
2419 assert (a.byteswap(True) == [0x0100, 0x0201, 0x0300]).all()
2420 assert (a == [0x0100, 0x0201, 0x0300]).all()
2421
2422 a = array([1, -1, 1e300], dtype=float)
2423 s1 = map(ord, a.tostring())
2424 s2 = map(ord, a.byteswap().tostring())
2425 assert a.dtype.itemsize == 8
2426 for i in range(a.size):
2427 i1 = i * a.dtype.itemsize
2428 i2 = (i+1) * a.dtype.itemsize
2429 assert list(reversed(s1[i1:i2])) == s2[i1:i2]
2430
2431 a = array([1+1e30j, -1, 1e10], dtype=complex)
2432 s1 = map(ord, a.tostring())
2433 s2 = map(ord, a.byteswap().tostring())
2434 assert a.dtype.itemsize == 16
2435 for i in range(a.size*2):
2436 i1 = i * a.dtype.itemsize/2
2437 i2 = (i+1) * a.dtype.itemsize/2
2438 assert list(reversed(s1[i1:i2])) == s2[i1:i2]
2439
2440 a = array([3.14, -1.5, 10000], dtype='float16')
2441 s1 = map(ord, a.tostring())
2442 s2 = map(ord, a.byteswap().tostring())
2443 assert a.dtype.itemsize == 2
2444 for i in range(a.size):
2445 i1 = i * a.dtype.itemsize
2446 i2 = (i+1) * a.dtype.itemsize
2447 assert list(reversed(s1[i1:i2])) == s2[i1:i2]
2448
2449 a = array([1, -1, 10000], dtype='longfloat')
2450 s1 = map(ord, a.tostring())
2451 s2 = map(ord, a.byteswap().tostring())
2452 assert a.dtype.itemsize >= 8
2453 for i in range(a.size):
2454 i1 = i * a.dtype.itemsize
2455 i2 = (i+1) * a.dtype.itemsize
2456 assert list(reversed(s1[i1:i2])) == s2[i1:i2]
2457
2458 def test_clip(self):
2459 from numpy import array
2460 a = array([1, 2, 17, -3, 12])
2461 exc = raises(ValueError, a.clip)
2462 assert str(exc.value) == "One of max or min must be given."
2463 assert (a.clip(-2, 13) == [1, 2, 13, -2, 12]).all()
2464 assert (a.clip(min=-2) == [1, 2, 17, -2, 12]).all()
2465 assert (a.clip(min=-2, max=None) == [1, 2, 17, -2, 12]).all()
2466 assert (a.clip(max=13) == [1, 2, 13, -3, 12]).all()
2467 assert (a.clip(min=None, max=13) == [1, 2, 13, -3, 12]).all()
2468 assert (a.clip(-1, 1, out=None) == [1, 1, 1, -1, 1]).all()
2469 assert (a == [1, 2, 17, -3, 12]).all()
2470 assert (a.clip(-1, [1, 2, 3, 4, 5]) == [1, 2, 3, -1, 5]).all()
2471 assert (a.clip(-2, 13, out=a) == [1, 2, 13, -2, 12]).all()
2472 assert (a == [1, 2, 13, -2, 12]).all()
2473
2474 def test_data(self):
2475 from numpy import array
2476 import sys
2477 a = array([1, 2, 3, 4], dtype='i4')
2478 assert a.data[0] == ('\x01' if sys.byteorder == 'little' else '\x00')
2479 assert a.data[1] == '\x00'
2480 assert a.data[3] == ('\x00' if sys.byteorder == 'little' else '\x01')
2481 assert a.data[4] == ('\x02' if sys.byteorder == 'little' else '\x00')
2482 a.data[4] = '\x7f'
2483 if sys.byteorder == 'big':
2484 a.data[7] = '\x00' # make sure 0x02 is reset to 0
2485 assert a[1] == (0x7f000000)
2486 else:
2487 assert a[1] == 0x7f
2488 assert len(a.data) == 16
2489 assert type(a.data) is buffer
2490 if '__pypy__' in sys.builtin_module_names:
2491 assert a[1:].data._pypy_raw_address() - a.data._pypy_raw_address() == a.strides[0]
2492
2493 def test_explicit_dtype_conversion(self):
2494 from numpy import array
2495 a = array([1.0, 2.0])
2496 b = array(a, dtype='d')
2497 assert a.dtype is b.dtype
2498
2499 def test_notequal_different_shapes(self):
2500 from numpy import array
2501 a = array([1, 2])
2502 b = array([1, 2, 3, 4])
2503 assert (a == b) == False
2504
2505 def test__int__(self):
2506 from numpy import array
2507 assert int(array(1)) == 1
2508 assert int(array([1])) == 1
2509 assert raises(TypeError, "int(array([1, 2]))")
2510 assert int(array([1.5])) == 1
2511 for op in ["int", "float", "long"]:
2512 for a in [array('123'), array(['123'])]:
2513 exc = raises(TypeError, "%s(a)" % op)
2514 assert exc.value.message == "don't know how to convert " \
2515 "scalar number to %s" % op
2516
2517 def test__float__(self):
2518 import numpy as np
2519 assert float(np.array(1.5)) == 1.5
2520 exc = raises(TypeError, "float(np.array([1.5, 2.5]))")
2521 assert exc.value[0] == 'only length-1 arrays can be converted to Python scalars'
2522
2523 def test__hex__(self):
2524 import numpy as np
2525 assert hex(np.array(True)) == '0x1'
2526 assert hex(np.array(15)) == '0xf'
2527 assert hex(np.array([15])) == '0xf'
2528 exc = raises(TypeError, "hex(np.array(1.5))")
2529 assert str(exc.value) == "don't know how to convert scalar number to hex"
2530 exc = raises(TypeError, "hex(np.array('15'))")
2531 assert str(exc.value) == "don't know how to convert scalar number to hex"
2532 exc = raises(TypeError, "hex(np.array([1, 2]))")
2533 assert str(exc.value) == "only length-1 arrays can be converted to Python scalars"
2534
2535 def test__oct__(self):
2536 import numpy as np
2537 assert oct(np.array(True)) == '01'
2538 assert oct(np.array(15)) == '017'
2539 assert oct(np.array([15])) == '017'
2540 exc = raises(TypeError, "oct(np.array(1.5))")
2541 assert str(exc.value) == "don't know how to convert scalar number to oct"
2542 exc = raises(TypeError, "oct(np.array('15'))")
2543 assert str(exc.value) == "don't know how to convert scalar number to oct"
2544 exc = raises(TypeError, "oct(np.array([1, 2]))")
2545 assert str(exc.value) == "only length-1 arrays can be converted to Python scalars"
2546
2547 def test__reduce__(self):
2548 from numpy import array, dtype
2549 from cPickle import loads, dumps
2550 import sys
2551
2552 a = array([1, 2], dtype="int64")
2553 data = a.__reduce__()
2554
2555 if sys.byteorder == 'big':
2556 assert data[2][4] == '\x00\x00\x00\x00\x00\x00\x00\x01' \
2557 '\x00\x00\x00\x00\x00\x00\x00\x02'
2558 else:
2559 assert data[2][4] == '\x01\x00\x00\x00\x00\x00\x00\x00' \
2560 '\x02\x00\x00\x00\x00\x00\x00\x00'
2561
2562 pickled_data = dumps(a)
2563 assert (loads(pickled_data) == a).all()
2564
2565 def test_pickle_slice(self):
2566 from cPickle import loads, dumps
2567 import numpy
2568
2569 a = numpy.arange(10.).reshape((5, 2))[::2]
2570 assert (loads(dumps(a)) == a).all()
2571
2572 def test_string_filling(self):
2573 import numpy
2574 a = numpy.empty((10,10), dtype='S1')
2575 a.fill(12)
2576 assert (a == '1').all()
2577
2578 def test_unicode_filling(self):
2579 import numpy as np
2580 a = np.empty((10,10), dtype='U1')
2581 a.fill(12)
2582 assert (a == u'1').all()
2583
2584 def test_unicode_record_array(self) :
2585 from numpy import dtype, array
2586 t = dtype([('a', 'S3'), ('b', 'U2')])
2587 x = array([('a', u'b')], dtype=t)
2588 assert str(x) == "[('a', u'b')]"
2589
2590 t = dtype([('a', 'U3'), ('b', 'S2')])
2591 x = array([(u'a', 'b')], dtype=t)
2592 x['a'] = u'1'
2593 assert str(x) == "[(u'1', 'b')]"
2594
2595
2596 def test_boolean_indexing(self):
2597 import numpy as np
2598 a = np.zeros((1, 3))
2599 b = np.array([True])
2600
2601 assert (a[b] == a).all()
2602 a[b] = 1.
2603 assert (a == [[1., 1., 1.]]).all()
2604 a[b] = np.array(2.)
2605 assert (a == [[2., 2., 2.]]).all()
2606 a[b] = np.array([3.])
2607 assert (a == [[3., 3., 3.]]).all()
2608 a[b] = np.array([[4.]])
2609 assert (a == [[4., 4., 4.]]).all()
2610
2611 def test_indexing_by_boolean(self):
2612 import numpy as np
2613 a = np.arange(6).reshape(2,3)
2614 assert (a[[True, False], :] == [[3, 4, 5], [0, 1, 2]]).all()
2615 b = a[np.array([True, False]), :]
2616 assert (b == [[0, 1, 2]]).all()
2617 assert b.base is None
2618 b = a[:, np.array([True, False, True])]
2619 assert b.base is not None
2620 a[np.array([True, False]), 0] = 100
2621 b = a[np.array([True, False]), 0]
2622 assert b.shape == (1,)
2623 assert (b ==[100]).all()
2624
2625 def test_scalar_indexing(self):
2626 import numpy as np
2627 a = np.arange(6).reshape(2,3)
2628 i = np.dtype('int32').type(0)
2629 assert (a[0] == a[i]).all()
2630
2631
2632 def test_ellipsis_indexing(self):
2633 import numpy as np
2634 import sys
2635 a = np.array(1.5)
2636 assert a[...].base is a
2637 a[...] = 2.5
2638 assert a == 2.5
2639 a = np.array([1, 2, 3])
2640 assert a[...].base is a
2641 a[...] = 4
2642 assert (a == [4, 4, 4]).all()
2643 assert a[..., 0] == 4
2644
2645 b = np.arange(24).reshape(2,3,4)
2646 b[...] = 100
2647 assert (b == 100).all()
2648 assert b.shape == (2, 3, 4)
2649 b[...] = [10, 20, 30, 40]
2650 assert (b[:,:,0] == 10).all()
2651 assert (b[0,0,:] == [10, 20, 30, 40]).all()
2652 assert b.shape == b[...].shape
2653 assert (b == b[...]).all()
2654
2655 a = np.arange(6)
2656 if '__pypy__' in sys.builtin_module_names:
2657 raises(ValueError, "a[..., ...]")
2658 b = a.reshape(2, 3)[..., 0]
2659 assert (b == [0, 3]).all()
2660 assert b.base is a
2661
2662 def test_empty_indexing(self):
2663 import numpy as np
2664 r = np.ones(3)
2665 ind = np.array([], np.int32)
2666 tmp = np.array([], np.float64)
2667 assert r[ind].shape == (0,)
2668 r[ind] = 0
2669 assert (r == np.ones(3)).all()
2670 r[ind] = tmp
2671 assert (r == np.ones(3)).all()
2672 r[[]] = 0
2673 assert (r == np.ones(3)).all()
2674
2675
2676 class AppTestNumArrayFromBuffer(BaseNumpyAppTest):
2677 spaceconfig = dict(usemodules=["micronumpy", "array", "mmap"])
2678
2679 def setup_class(cls):
2680 from rpython.tool.udir import udir
2681 BaseNumpyAppTest.setup_class.im_func(cls)
2682 cls.w_tmpname = cls.space.wrap(str(udir.join('mmap-')))
2683
2684 def test_ndarray_from_buffer(self):
2685 import numpy as np
2686 import array
2687 import sys
2688 buf = array.array('c', ['\x00']*2*3)
2689 a = np.ndarray((3,), buffer=buf, dtype='i2')
2690 a[0] = ord('b')
2691 a[1] = ord('a')
2692 a[2] = ord('r')
2693 if sys.byteorder == 'big':
2694 assert list(buf) == ['\x00', 'b', '\x00', 'a', '\x00', 'r']
2695 else:
2696 assert list(buf) == ['b', '\x00', 'a', '\x00', 'r', '\x00']
2697 assert a.base is buf
2698
2699 def test_ndarray_subclass_from_buffer(self):
2700 import numpy as np
2701 import array
2702 buf = array.array('c', ['\x00']*2*3)
2703 class X(np.ndarray):
2704 pass
2705 a = X((3,), buffer=buf, dtype='i2')
2706 assert type(a) is X
2707
2708 def test_ndarray_from_buffer_and_offset(self):
2709 import numpy as np
2710 import array
2711 import sys
2712 buf = array.array('c', ['\x00']*7)
2713 buf[0] = 'X'
2714 a = np.ndarray((3,), buffer=buf, offset=1, dtype='i2')
2715 a[0] = ord('b')
2716 a[1] = ord('a')
2717 a[2] = ord('r')
2718 if sys.byteorder == 'big':
2719 assert list(buf) == ['X', '\x00', 'b', '\x00', 'a', '\x00', 'r']
2720 else:
2721 assert list(buf) == ['X', 'b', '\x00', 'a', '\x00', 'r', '\x00']
2722
2723 def test_ndarray_from_buffer_out_of_bounds(self):
2724 import numpy as np
2725 import array
2726 buf = array.array('c', ['\x00']*2*10) # 20 bytes
2727 info = raises(TypeError, "np.ndarray((11,), buffer=buf, dtype='i2')")
2728 assert str(info.value).startswith('buffer is too small')
2729 info = raises(TypeError, "np.ndarray((5,), buffer=buf, offset=15, dtype='i2')")
2730 assert str(info.value).startswith('buffer is too small')
2731
2732 def test_ndarray_from_readonly_buffer(self):
2733 import numpy as np
2734 from mmap import mmap, ACCESS_READ
2735 f = open(self.tmpname, "w+")
2736 f.write("hello")
2737 f.flush()
2738 buf = mmap(f.fileno(), 5, access=ACCESS_READ)
2739 a = np.ndarray((5,), buffer=buf, dtype='c')
2740 raises(ValueError, "a[0] = 'X'")
2741 buf.close()
2742 f.close()
2743
2744
2745 class AppTestMultiDim(BaseNumpyAppTest):
2746 def test_init(self):
2747 import numpy
2748 a = numpy.zeros((2, 2))
2749 assert len(a) == 2
2750
2751 def test_shape(self):
2752 import numpy
2753 assert numpy.zeros(1).shape == (1,)
2754 assert numpy.zeros((2, 2)).shape == (2, 2)
2755 assert numpy.zeros((3, 1, 2)).shape == (3, 1, 2)
2756 assert numpy.array([[1], [2], [3]]).shape == (3, 1)
2757 assert len(numpy.zeros((3, 1, 2))) == 3
2758 raises(TypeError, len, numpy.zeros(()))
2759 raises(ValueError, numpy.array, [[1, 2], 3], dtype=float)
2760
2761 def test_getsetitem(self):
2762 import numpy
2763 a = numpy.zeros((2, 3, 1))
2764 raises(IndexError, a.__getitem__, (2, 0, 0))
2765 raises(IndexError, a.__getitem__, (0, 3, 0))
2766 raises(IndexError, a.__getitem__, (0, 0, 1))
2767 assert a[1, 1, 0] == 0
2768 a[1, 2, 0] = 3
2769 assert a[1, 2, 0] == 3
2770 assert a[1, 1, 0] == 0
2771 assert a[1, -1, 0] == 3
2772
2773 def test_slices(self):
2774 import numpy
2775 a = numpy.zeros((4, 3, 2))
2776 raises(IndexError, a.__getitem__, (4,))
2777 raises(IndexError, a.__getitem__, (3, 3))
2778 raises(IndexError, a.__getitem__, (slice(None), 3))
2779 a[0, 1, 1] = 13
2780 a[1, 2, 1] = 15
2781 b = a[0]
2782 assert len(b) == 3
2783 assert b.shape == (3, 2)
2784 assert b[1, 1] == 13
2785 b = a[1]
2786 assert b.shape == (3, 2)
2787 assert b[2, 1] == 15
2788 b = a[:, 1]
2789 assert b.shape == (4, 2)
2790 assert b[0, 1] == 13
2791 b = a[:, 1, :]
2792 assert b.shape == (4, 2)
2793 assert b[0, 1] == 13
2794 b = a[1, 2]
2795 assert b[1] == 15
2796 b = a[:]
2797 assert b.shape == (4, 3, 2)
2798 assert b[1, 2, 1] == 15
2799 assert b[0, 1, 1] == 13
2800 b = a[:][:, 1][:]
2801 assert b[2, 1] == 0.0
2802 assert b[0, 1] == 13
2803 raises(IndexError, b.__getitem__, (4, 1))
2804 assert a[0][1][1] == 13
2805 assert a[1][2][1] == 15
2806
2807 def test_create_order(self):
2808 import numpy as np
2809 for order in [False, True, 'C', 'F']:
2810 a = np.empty((2, 3), float, order=order)
2811 assert a.shape == (2, 3)
2812 if order in [True, 'F']:
2813 assert a.flags['F']
2814 assert not a.flags['C']
2815 else:
2816 assert a.flags['C'], "flags['C'] False for %r" % order
2817 assert not a.flags['F']
2818
2819 def test_setitem_slice(self):
2820 import numpy
2821 a = numpy.zeros((3, 4))
2822 a[1] = [1, 2, 3, 4]
2823 assert a[1, 2] == 3
2824 raises(TypeError, a[1].__setitem__, [1, 2, 3])
2825 a = numpy.array([[1, 2], [3, 4]])
2826 assert (a == [[1, 2], [3, 4]]).all()
2827 a[1] = numpy.array([5, 6])
2828 assert (a == [[1, 2], [5, 6]]).all()
2829 a[:, 1] = numpy.array([8, 10])
2830 assert (a == [[1, 8], [5, 10]]).all()
2831 a[0, :: -1] = numpy.array([11, 12])
2832 assert (a == [[12, 11], [5, 10]]).all()
2833
2834 a = numpy.zeros((3, 2), int)
2835 b = numpy.ones((3, 1), int)
2836 exc = raises(ValueError, 'a[:, 1] = b')
2837 assert str(exc.value) == "could not broadcast " +\
2838 "input array from shape (3,1) into shape (3)"
2839 a[:, 1] = b[:,0] > 0.5
2840 assert (a == [[0, 1], [0, 1], [0, 1]]).all()
2841
2842
2843 def test_ufunc(self):
2844 from numpy import array
2845 a = array([[1, 2], [3, 4], [5, 6]])
2846 assert ((a + a) == \
2847 array([[1 + 1, 2 + 2], [3 + 3, 4 + 4], [5 + 5, 6 + 6]])).all()
2848
2849 def test_getitem_add(self):
2850 from numpy import array
2851 a = array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
2852 assert (a + a)[1, 1] == 8
2853
2854 def test_getitem_3(self):
2855 from numpy import array
2856 a = array([[1, 2], [3, 4], [5, 6], [7, 8],
2857 [9, 10], [11, 12], [13, 14]])
2858 b = a[::2]
2859 assert (b == [[1, 2], [5, 6], [9, 10], [13, 14]]).all()
2860 c = b + b
2861 assert c[1][1] == 12
2862
2863 def test_multidim_ones(self):
2864 from numpy import ones
2865 a = ones((1, 2, 3))
2866 assert a[0, 1, 2] == 1.0
2867
2868 def test_multidim_setslice(self):
2869 from numpy import zeros, ones
2870 a = zeros((3, 3))
2871 b = ones((3, 3))
2872 a[:, 1:3] = b[:, 1:3]
2873 assert (a == [[0, 1, 1], [0, 1, 1], [0, 1, 1]]).all()
2874 a = zeros((3, 3))
2875 b = ones((3, 3))
2876 a[:, ::2] = b[:, ::2]
2877 assert (a == [[1, 0, 1], [1, 0, 1], [1, 0, 1]]).all()
2878
2879 def test_broadcast_ufunc(self):
2880 from numpy import array
2881 a = array([[1, 2], [3, 4], [5, 6]])
2882 b = array([5, 6])
2883 c = ((a + b) == [[1 + 5, 2 + 6], [3 + 5, 4 + 6], [5 + 5, 6 + 6]])
2884 assert c.all()
2885
2886 def test_broadcast_setslice(self):
2887 from numpy import zeros, ones
2888 a = zeros((10, 10))
2889 b = ones(10)
2890 a[:, :] = b
2891 assert a[3, 5] == 1
2892
2893 def test_broadcast_shape_agreement(self):
2894 from numpy import zeros, array
2895 a = zeros((3, 1, 3))
2896 b = array(((10, 11, 12), (20, 21, 22), (30, 31, 32)))
2897 c = ((a + b) == [b, b, b])
2898 assert c.all()
2899 a = array((((10, 11, 12), ), ((20, 21, 22), ), ((30, 31, 32), )))
2900 assert(a.shape == (3, 1, 3))
2901 d = zeros((3, 3))
2902 c = ((a + d) == [b, b, b])
2903 c = ((a + d) == array([[[10., 11., 12.]] * 3,
2904 [[20., 21., 22.]] * 3, [[30., 31., 32.]] * 3]))
2905 assert c.all()
2906
2907 def test_broadcast_scalar(self):
2908 from numpy import zeros
2909 a = zeros((4, 5), 'd')
2910 a[:, 1] = 3
2911 assert a[2, 1] == 3
2912 assert a[0, 2] == 0
2913 a[0, :] = 5
2914 assert a[0, 3] == 5
2915 assert a[2, 1] == 3
2916 assert a[3, 2] == 0
2917
2918 def test_broadcast_call2(self):
2919 from numpy import zeros, ones
2920 a = zeros((4, 1, 5))
2921 b = ones((4, 3, 5))
2922 b[:] = (a + a)
2923 assert (b == zeros((4, 3, 5))).all()
2924
2925 def test_broadcast_virtualview(self):
2926 from numpy import arange, zeros
2927 a = arange(8).reshape([2, 2, 2])
2928 b = (a + a)[1, 1]
2929 c = zeros((2, 2, 2))
2930 c[:] = b
2931 assert (c == [[[12, 14], [12, 14]], [[12, 14], [12, 14]]]).all()
2932
2933 def test_broadcast_wrong_shapes(self):
2934 from numpy import zeros
2935 a = zeros((4, 3, 2))
2936 b = zeros((4, 2))
2937 exc = raises(ValueError, lambda: a + b)
2938 assert str(exc.value).startswith("operands could not be broadcast")
2939
2940 def test_reduce(self):
2941 from numpy import array
2942 a = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
2943 assert a.sum() == (13 * 12) / 2
2944 b = a[1:, 1::2]
2945 c = b + b
2946 assert c.sum() == (6 + 8 + 10 + 12) * 2
2947 assert isinstance(c.sum(dtype='f8'), float)
2948 assert isinstance(c.sum(None, 'f8'), float)
2949
2950 def test_transpose(self):
2951 from numpy import array
2952 a = array(((range(3), range(3, 6)),
2953 (range(6, 9), range(9, 12)),
2954 (range(12, 15), range(15, 18)),
2955 (range(18, 21), range(21, 24))))
2956 assert a.shape == (4, 2, 3)
2957 b = a.T
2958 assert b.shape == (3, 2, 4)
2959 assert(b[0, :, 0] == [0, 3]).all()
2960
2961 c = a.transpose((1, 0, 2))
2962 assert c.shape == (2, 4, 3)
2963 assert (c.transpose(1, 0, 2) == a).all()
2964
2965 b[:, 0, 0] = 1000
2966 assert(a[0, 0, :] == [1000, 1000, 1000]).all()
2967 a = array(range(5))
2968 b = a.T
2969 assert(b == range(5)).all()
2970 a = array((range(10), range(20, 30)))
2971 b = a.T
2972 assert(b[:, 0] == a[0, :]).all()
2973 assert (a.transpose() == b).all()
2974 assert (a.transpose(None) == b).all()
2975
2976 def test_transpose_arg_tuple(self):
2977 import numpy as np
2978 a = np.arange(24).reshape(2, 3, 4)
2979 transpose_args = a.transpose(1, 2, 0)
2980
2981 transpose_test = a.transpose((1, 2, 0))
2982
2983 assert transpose_test.shape == (3, 4, 2)
2984 assert (transpose_args == transpose_test).all()
2985
2986 def test_transpose_arg_list(self):
2987 import numpy as np
2988 a = np.arange(24).reshape(2, 3, 4)
2989 transpose_args = a.transpose(1, 2, 0)
2990
2991 transpose_test = a.transpose([1, 2, 0])
2992
2993 assert transpose_test.shape == (3, 4, 2)
2994 assert (transpose_args == transpose_test).all()
2995
2996 def test_transpose_arg_array(self):
2997 import numpy as np
2998 a = np.arange(24).reshape(2, 3, 4)
2999 transpose_args = a.transpose(1, 2, 0)
3000
3001 transpose_test = a.transpose(np.array([1, 2, 0]))
3002
3003 assert transpose_test.shape == (3, 4, 2)
3004 assert (transpose_args == transpose_test).all()
3005
3006 def test_transpose_error(self):
3007 import numpy as np
3008 a = np.arange(24).reshape(2, 3, 4)
3009 raises(ValueError, a.transpose, 2, 1)
3010 raises(ValueError, a.transpose, 1, 0, 3)
3011 raises(ValueError, a.transpose, 1, 0, 1)
3012 raises(TypeError, a.transpose, 1, 0, '2')
3013
3014 def test_transpose_unexpected_argument(self):
3015 import numpy as np
3016 a = np.array([[1, 2], [3, 4], [5, 6]])
3017 raises(TypeError, 'a.transpose(axes=(1,2,0))')
3018
3019 def test_flatiter(self):
3020 from numpy import array, flatiter, arange, zeros
3021 a = array([[10, 30], [40, 60]])
3022 f_iter = a.flat
3023 assert f_iter.next() == 10
3024 assert f_iter.next() == 30
3025 assert f_iter.next() == 40
3026 assert f_iter.next() == 60
3027 raises(StopIteration, "f_iter.next()")
3028 raises(TypeError, "flatiter()")
3029 s = 0
3030 for k in a.flat:
3031 s += k
3032 assert s == 140
3033 a = arange(10).reshape(5, 2)
3034 raises(IndexError, 'a.flat[(1, 2)]')
3035 assert a.flat.base is a
3036 m = zeros((2,2), dtype='S3')
3037 m.flat[1] = 1
3038 assert m[0,1] == '1'
3039
3040 def test_flatiter_array_conv(self):
3041 from numpy import array, dot
3042 a = array([1, 2, 3])
3043 assert dot(a.flat, a.flat) == 14
3044
3045 def test_flatiter_varray(self):
3046 from numpy import ones
3047 a = ones((2, 2))
3048 assert list(((a + a).flat)) == [2, 2, 2, 2]
3049
3050 def test_flatiter_getitem(self):
3051 from numpy import arange
3052 a = arange(10)
3053 assert a.flat[3] == 3
3054 assert a[2:].flat[3] == 5
3055 assert (a + a).flat[3] == 6
3056 assert a[::2].flat[3] == 6
3057 assert a.reshape(2,5).flat[3] == 3
3058 b = a.reshape(2,5).flat
3059 b.next()
3060 b.next()
3061 b.next()
3062 assert b.index == 3
3063 assert b.coords == (0, 3)
3064 b.next()
3065 assert b[3] == 3
3066 assert b.index == 0
3067 assert b.coords == (0, 0)
3068 b.next()
3069 assert (b[::3] == [0, 3, 6, 9]).all()
3070 assert b.index == 0
3071 assert b.coords == (0, 0)
3072 b.next()
3073 assert (b[2::5] == [2, 7]).all()
3074 assert b.index == 0
3075 assert b.coords == (0, 0)
3076 b.next()
3077 assert b[-2] == 8
3078 assert b.index == 0
3079 assert b.coords == (0, 0)
3080 b.next()
3081 raises(IndexError, "b[11]")
3082 assert b.index == 0
3083 assert b.coords == (0, 0)
3084 b.next()
3085 raises(IndexError, "b[-11]")
3086 assert b.index == 0
3087 assert b.coords == (0, 0)
3088 b.next()
3089 exc = raises(IndexError, 'b[0, 1]')
3090 assert str(exc.value) == "unsupported iterator index"
3091 assert b.index == 1
3092 assert b.coords == (0, 1)
3093
3094 def test_flatiter_setitem(self):
3095 from numpy import arange, array
3096 a = arange(12).reshape(3,4)
3097 b = a.T.flat
3098 b[6::2] = [-1, -2]
3099 assert (a == [[0, 1, -1, 3], [4, 5, 6, -1], [8, 9, -2, 11]]).all()
3100 assert b[2] == 8
3101 assert b.index == 0
3102 b.next()
3103 b[6::2] = [-21, -42]
3104 assert (a == [[0, 1, -21, 3], [4, 5, 6, -21], [8, 9, -42, 11]]).all()
3105 b[0:2] = [[[100]]]
3106 assert(a[0,0] == 100)
3107 assert(a[1,0] == 100)
3108 b.next()
3109 assert b.index == 1
3110 exc = raises(ValueError, "b[0] = [1, 2]")
3111 assert str(exc.value) == "Error setting single item of array."
3112 assert b.index == 0
3113 b.next()
3114 raises(IndexError, "b[100] = 42")
3115 assert b.index == 1
3116 exc = raises(IndexError, "b[0, 1] = 42")
3117 assert str(exc.value) == "unsupported iterator index"
3118 assert b.index == 1
3119 a = array([(False, False, False),
3120 (False, False, False),
3121 (False, False, False),
3122 ],
3123 dtype=[('a', '|b1'), ('b', '|b1'), ('c', '|b1')])
3124 a.flat = [(True, True, True),
3125 (True, True, True),
3126 (True, True, True)]
3127 assert (a.view(bool) == True).all()
3128
3129 def test_flatiter_ops(self):
3130 from numpy import arange, array
3131 a = arange(12).reshape(3,4)
3132 b = a.T.flat
3133 assert (b == [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11]).all()
3134 assert not (b != [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11]).any()
3135 assert ((b >= range(12)) == [True, True, True,False, True, True,
3136 False, False, True, False, False, True]).all()
3137 assert ((b < range(12)) != [True, True, True,False, True, True,
3138 False, False, True, False, False, True]).all()
3139 assert ((b <= range(12)) != [False, True, True,False, True, True,
3140 False, False, True, False, False, False]).all()
3141 assert ((b > range(12)) == [False, True, True,False, True, True,
3142 False, False, True, False, False, False]).all()
3143
3144 def test_flatiter_view(self):
3145 from numpy import arange
3146 a = arange(10).reshape(5, 2)
3147 assert (a[::2].flat == [0, 1, 4, 5, 8, 9]).all()
3148
3149 def test_flatiter_transpose(self):
3150 from numpy import arange
3151 a = arange(10).reshape(2, 5).T
3152 b = a.flat
3153 assert (b[:5] == [0, 5, 1, 6, 2]).all()
3154 b.next()
3155 b.next()
3156 b.next()
3157 assert b.index == 3
3158 assert b.coords == (1, 1)
3159
3160 def test_flatiter_len(self):
3161 from numpy import arange
3162
3163 assert len(arange(10).flat) == 10
3164 assert len(arange(10).reshape(2, 5).flat) == 10
3165 assert len(arange(10)[:2].flat) == 2
3166 assert len((arange(2) + arange(2)).flat) == 2
3167
3168 def test_flatiter_setter(self):
3169 from numpy import arange, array
3170 a = arange(24).reshape(2, 3, 4)
3171 a.flat = [4, 5]
3172 assert (a.flatten() == [4, 5]*12).all()
3173 a.flat = [[4, 5, 6, 7, 8], [4, 5, 6, 7, 8]]
3174 assert (a.flatten() == ([4, 5, 6, 7, 8]*5)[:24]).all()
3175 exc = raises(ValueError, 'a.flat = [[4, 5, 6, 7, 8], [4, 5, 6]]')
3176 assert str(exc.value).find("sequence") > 0
3177 b = a[::-1, :, ::-1]
3178 b.flat = range(24)
3179 assert (a.flatten() == [15, 14 ,13, 12, 19, 18, 17, 16, 23, 22,
3180 21, 20, 3, 2, 1, 0, 7, 6, 5, 4,
3181 11, 10, 9, 8]).all()
3182 c = array(['abc'] * 10).reshape(2, 5)
3183 c.flat = ['defgh', 'ijklmnop']
3184 assert (c.flatten() == ['def', 'ijk']*5).all()
3185
3186 def test_flatiter_subtype(self):
3187 from numpy import array
3188 x = array([[1, 2], [3, 4]]).T
3189 y = array(x.flat)
3190 assert (x == [[1, 3], [2, 4]]).all()
3191
3192
3193 def test_slice_copy(self):
3194 from numpy import zeros
3195 a = zeros((10, 10))
3196 b = a[0].copy()
3197 assert (b == zeros(10)).all()
3198
3199 def test_array_interface(self):
3200 from numpy import array
3201 import numpy as np
3202 a = array(2.5)
3203 i = a.__array_interface__
3204 assert isinstance(i['data'][0], int)
3205 assert i['shape'] == ()
3206 assert i['strides'] is None
3207 a = array([1, 2, 3])
3208 i = a.__array_interface__
3209 assert isinstance(i['data'][0], int)
3210 assert i['shape'] == (3,)
3211 assert i['strides'] == None # Because array is in C order
3212 assert i['typestr'] == a.dtype.str
3213 a = a[::2]
3214 i = a.__array_interface__
3215 assert isinstance(i['data'][0], int)
3216 b = array(range(9), dtype=int)
3217 c = b[3:5]
3218 b_data = b.__array_interface__['data'][0]
3219 c_data = c.__array_interface__['data'][0]
3220 assert b_data + 3 * b.dtype.itemsize == c_data
3221
3222 class Dummy(object):
3223 def __init__(self, aif=None, base=None):
3224 if aif is not None:
3225 self.__array_interface__ = aif
3226 self.base = base
3227
3228 a = array(Dummy())
3229 assert a.dtype == object
3230 raises(ValueError, array, Dummy({'xxx': 0}))
3231 raises(ValueError, array, Dummy({'version': 0}))
3232 raises(ValueError, array, Dummy({'version': 'abc'}))
3233 raises(ValueError, array, Dummy({'version': 3}))
3234 raises(TypeError, array, Dummy({'version': 3, 'typestr': 'f8', 'shape': ('a', 3)}))
3235
3236 a = array([1, 2, 3])
3237 d = Dummy(a.__array_interface__)
3238 b = array(d)
3239 assert b.base is None
3240 b[1] = 200
3241 assert a[1] == 2 # upstream compatibility, is this a bug?
3242 interface_a = a.__array_interface__
3243 interface_b = b.__array_interface__
3244 # only the data[0] value should differ
3245 assert interface_a['data'][0] != interface_b['data'][0]
3246 assert interface_b['data'][1] == interface_a['data'][1]
3247 interface_b.pop('data')
3248 interface_a.pop('data')
3249 assert interface_a == interface_b
3250 b = array(d, copy=False)
3251 assert b.base is d
3252
3253 b = array(Dummy({'version':3, 'shape': (50,), 'typestr': 'u1',
3254 'data': 'a'*100}))
3255 assert b.dtype == 'uint8'
3256 assert b.shape == (50,)
3257
3258 a = np.ones((1,), dtype='float16')
3259 b = Dummy(a.__array_interface__)
3260 c = array(b)
3261 assert c.dtype == 'float16'
3262 assert (a == c).all()
3263
3264 t = np.dtype([("a", np.float64), ("b", np.float64)], align=True)
3265 a = np.zeros(10, dtype=t)
3266 a['a'] = range(10, 20)
3267 a['b'] = range(20, 30)
3268 interface = dict(a.__array_interface__)
3269 array = np.array(Dummy(interface))
3270 assert array.dtype.kind == 'V'
3271 array.dtype = a.dtype
3272 assert array[5]['b'] == 25
3273
3274 def test_array_indexing_one_elem(self):
3275 from numpy import array, arange
3276 raises(IndexError, 'arange(3)[array([3.5])]')
3277 a = arange(3)[array([1])]
3278 assert a == 1
3279 assert a[0] == 1
3280 raises(IndexError,'arange(3)[array([15])]')
3281 assert arange(3)[array([-3])] == 0
3282 raises(IndexError,'arange(3)[array([-15])]')
3283 assert arange(3)[array(1)] == 1
3284
3285 def test_fill(self):
3286 from numpy import array, empty, dtype, zeros
3287 a = array([1, 2, 3])
3288 a.fill(10)
3289 assert (a == [10, 10, 10]).all()
3290 a.fill(False)
3291 assert (a == [0, 0, 0]).all()
3292 b = a[:1]
3293 b.fill(4)
3294 assert (b == [4]).all()
3295 assert (a == [4, 0, 0]).all()
3296
3297 c = b + b
3298 c.fill(27)
3299 assert (c == [27]).all()
3300
3301 d = array(10)
3302 d.fill(100)
3303 assert d == 100
3304
3305 e = array(10, dtype=complex)
3306 e.fill(1.5-3j)
3307 assert e == 1.5-3j
3308
3309 a = empty(5, dtype='S3')
3310 a.fill('abc')
3311 for i in a:
3312 assert i == 'abc'
3313
3314 a = empty(10, dtype=[(_, int) for _ in 'abcde'])
3315 a.fill(123)
3316 for i in a:
3317 assert tuple(i) == (123,) * 5
3318
3319 a = zeros(3, dtype=dtype(complex).newbyteorder())
3320 a.fill(1.5+2.5j)
3321 for i in a:
3322 assert i == 1.5+2.5j
3323
3324 def test_array_indexing_bool(self):
3325 from numpy import arange
3326 a = arange(10)
3327 assert (a[a > 3] == [4, 5, 6, 7, 8, 9]).all()
3328 a = arange(10).reshape(5, 2)
3329 assert (a[a > 3] == [4, 5, 6, 7, 8, 9]).all()
3330 assert (a[a & 1 == 1] == [1, 3, 5, 7, 9]).all()
3331
3332 def test_array_indexing_bool_setitem(self):
3333 from numpy import arange, array
3334 a = arange(6)
3335 a[a > 3] = 15
3336 assert (a == [0, 1, 2, 3, 15, 15]).all()
3337 a = arange(6).reshape(3, 2)
3338 a[a & 1 == 1] = array([8, 9, 10])
3339 assert (a == [[0, 8], [2, 9], [4, 10]]).all()
3340
3341 def test_array_indexing_bool_setitem_multidim(self):
3342 from numpy import arange
3343 a = arange(10).reshape(5, 2)
3344 a[a & 1 == 0] = 15
3345 assert (a == [[15, 1], [15, 3], [15, 5], [15, 7], [15, 9]]).all()
3346
3347 def test_array_indexing_bool_setitem_2(self):
3348 from numpy import arange
3349 a = arange(10).reshape(5, 2)
3350 a = a[::2]
3351 a[a & 1 == 0] = 15
3352 assert (a == [[15, 1], [15, 5], [15, 9]]).all()
3353
3354 def test_array_indexing_bool_specialcases(self):
3355 from numpy import arange, array
3356 a = arange(6)
3357 exc = raises(ValueError, 'a[a < 3] = [1, 2]')
3358 assert exc.value[0].find('cannot assign') >= 0
3359 b = arange(4).reshape(2, 2) + 10
3360 a[a < 4] = b
3361 assert (a == [10, 11, 12, 13, 4, 5]).all()
3362 b += 10
3363 c = arange(8).reshape(2, 2, 2)
3364 a[a > 9] = c[:, :, 1]
3365 assert (c[:, :, 1] == [[1, 3], [5, 7]]).all()
3366 assert (a == [1, 3, 5, 7, 4, 5]).all()
3367 a = arange(6)
3368 a[a > 3] = array([15])
3369 assert (a == [0, 1, 2, 3, 15, 15]).all()
3370 a = arange(6).reshape(3, 2)
3371 exc = raises(ValueError, 'a[a & 1 == 1] = []')
3372 assert exc.value[0].find('cannot assign') >= 0
3373 assert (a == [[0, 1], [2, 3], [4, 5]]).all()
3374
3375 def test_copy_kwarg(self):
3376 from numpy import array
3377 x = array([1, 2, 3])
3378 assert (array(x) == x).all()
3379 assert array(x) is not x
3380 assert array(x, copy=False) is x
3381 assert array(x, copy=True) is not x
3382
3383 def test_ravel(self):
3384 from numpy import arange
3385 assert (arange(3).ravel() == arange(3)).all()
3386 assert (arange(6).reshape(2, 3).ravel() == arange(6)).all()
3387 assert (arange(6).reshape(2, 3).T.ravel() == [0, 3, 1, 4, 2, 5]).all()
3388 assert (arange(3).ravel('K') == arange(3)).all()
3389
3390 def test_nonzero(self):
3391 from numpy import array
3392 nz = array(0).nonzero()
3393 assert nz[0].size == 0
3394
3395 nz = array(2).nonzero()
3396 assert (nz[0] == [0]).all()
3397
3398 nz = array([1, 0, 3]).nonzero()
3399 assert (nz[0] == [0, 2]).all()
3400
3401 nz = array([[1, 0, 3], [2, 0, 4]]).nonzero()
3402 assert (nz[0] == [0, 0, 1, 1]).all()
3403 assert (nz[1] == [0, 2, 0, 2]).all()
3404
3405 def test_take(self):
3406 from numpy import arange
3407 assert (arange(10).take([1, 2, 1, 1]) == [1, 2, 1, 1]).all()
3408 raises(IndexError, "arange(3).take([15])")
3409 a = arange(6).reshape(2, 3)
3410 assert a.take(3) == 3
3411 assert a.take(3).shape == ()
3412 assert (a.take([1, 0, 3]) == [1, 0, 3]).all()
3413 assert (a.take([[1, 0], [2, 3]]) == [[1, 0], [2, 3]]).all()
3414 assert (a.take([1], axis=0) == [[3, 4, 5]]).all()
3415 assert (a.take([1], axis=1) == [[1], [4]]).all()
3416 assert ((a + a).take([3]) == [6]).all()
3417 a = arange(12).reshape(2, 6)
3418 assert (a[:,::2].take([3, 2, 1]) == [6, 4, 2]).all()
3419 import sys
3420 if '__pypy__' in sys.builtin_module_names:
3421 exc = raises(NotImplementedError, "a.take([3, 2, 1], mode='clip')")
3422 assert exc.value[0] == "mode != raise not implemented"
3423
3424 def test_ptp(self):
3425 import numpy as np
3426 x = np.arange(4).reshape((2,2))
3427 assert x.ptp() == 3
3428 assert (x.ptp(axis=0) == [2, 2]).all()
3429 assert (x.ptp(axis=1) == [1, 1]).all()
3430
3431 def test_compress(self):
3432 from numpy import arange, array
3433 a = arange(10)
3434 assert (a.compress([True, False, True]) == [0, 2]).all()
3435 assert (a.compress([1, 0, 13]) == [0, 2]).all()
3436 assert (a.compress([1, 0, 13]) == [0, 2]).all()
3437 assert (a.compress([1, 0, 13.5]) == [0, 2]).all()
3438 assert (a.compress(array([1, 0, 13.5], dtype='>f4')) == [0, 2]).all()
3439 assert (a.compress(array([1, 0, 13.5], dtype='<f4')) == [0, 2]).all()
3440 assert (a.compress([1, -0-0j, 1.3+13.5j]) == [0, 2]).all()
3441 a = arange(10).reshape(2, 5)
3442 assert (a.compress([True, False, True]) == [0, 2]).all()
3443 raises((IndexError, ValueError), "a.compress([1] * 100)")
3444
3445 def test_item(self):
3446 import numpy as np
3447 from numpy import array
3448 assert array(3).item() == 3
3449 assert type(array(3).item()) is int
3450 assert type(array(True).item()) is bool
3451 assert type(array(3.5).item()) is float
3452 exc = raises(IndexError, "array(3).item(15)")
3453 assert str(exc.value) == 'index 15 is out of bounds for size 1'
3454 raises(ValueError, "array([1, 2, 3]).item()")
3455 assert array([3]).item(0) == 3
3456 assert type(array([3]).item(0)) is int
3457 assert array([1, 2, 3]).item(-1) == 3
3458 a = array([1, 2, 3])
3459 assert a[::2].item(1) == 3
3460 assert (a + a).item(1) == 4
3461 raises(IndexError, "array(5).item(1)")
3462 assert array([1]).item() == 1
3463 a = array('x')
3464 assert a.item() == 'x'
3465 a = array([(1, 'abc')], dtype=[('a', int), ('b', 'S2')])
3466 b = a.item(0)
3467 assert type(b) is tuple
3468 assert type(b[0]) is int
3469 assert type(b[1]) is str
3470 assert b[0] == 1
3471 assert b[1] == 'ab'
3472 a = np.arange(24).reshape(2, 4, 3)
3473 assert a.item(1, 1, 1) == 16
3474 assert a.item((1, 1, 1)) == 16
3475 exc = raises(ValueError, a.item, 1, 1, 1, 1)
3476 assert str(exc.value) == "incorrect number of indices for array"
3477 raises(TypeError, "array([1]).item(a=1)")
3478
3479 def test_itemset(self):
3480 import numpy as np
3481 a = np.array(range(5))
3482 exc = raises(ValueError, a.itemset)
3483 assert exc.value[0] == 'itemset must have at least one argument'
3484 exc = raises(ValueError, a.itemset, 1, 2, 3)
3485 assert exc.value[0] == 'incorrect number of indices for array'
3486 a.itemset(1, 5)
3487 assert a[1] == 5
3488 a = np.array(range(6)).reshape(2, 3)
3489 a.itemset(1, 2, 100)
3490 assert a[1, 2] == 100
3491
3492 def test_index_int(self):
3493 import numpy as np
3494 a = np.array([10, 20, 30], dtype='int64')
3495 res = a[np.int64(1)]
3496 assert isinstance(res, np.int64)
3497 assert res == 20
3498 res = a[np.int32(0)]
3499 assert isinstance(res, np.int64)
3500 assert res == 10
3501
3502 b = a.astype(float)
3503 res = b[np.int64(1)]
3504 assert res == 20.0
3505 assert isinstance(res, np.float64)
3506
3507 def test_index(self):
3508 import numpy as np
3509 a = np.array([1], np.uint16)
3510 i = a.__index__()
3511 assert type(i) is int
3512 assert i == 1
3513 for a in [np.array('abc'), np.array([1,2]), np.array([True])]:
3514 exc = raises(TypeError, a.__index__)
3515 assert exc.value.message == 'only integer arrays with one element ' \
3516 'can be converted to an index'
3517
3518
3519 def test_int_array_index(self):
3520 from numpy import array
3521 assert (array([])[[]] == []).all()
3522 a = array([[1, 2], [3, 4], [5, 6]])
3523 assert (a[slice(0, 3), [0, 0]] == [[1, 1], [3, 3], [5, 5]]).all()
3524 assert (a[array([0, 2]), slice(0, 2)] == [[1, 2], [5, 6]]).all()
3525 b = a[array([0, 0])]
3526 assert (b == [[1, 2], [1, 2]]).all()
3527 assert (a[[[0, 1], [0, 0]]] == array([1, 3])).all()
3528 assert (a[array([0, 2])] == [[1, 2], [5, 6]]).all()
3529 assert (a[array([0, 2]), 1] == [2, 6]).all()
3530 assert (a[array([0, 2]), array([1])] == [2, 6]).all()
3531
3532 def test_int_array_index_setitem(self):
3533 from numpy import array
3534 a = array([[1, 2], [3, 4], [5, 6]])
3535 a[slice(0, 3), [0, 0]] = [[0, 0], [0, 0], [0, 0]]
3536 assert (a == [[0, 2], [0, 4], [0, 6]]).all()
3537 a = array([[1, 2], [3, 4], [5, 6]])
3538 a[array([0, 2]), slice(0, 2)] = [[10, 11], [12, 13]]
3539 assert (a == [[10, 11], [3, 4], [12, 13]]).all()
3540
3541 def test_slice_vector_index(self):
3542 from numpy import arange
3543 b = arange(145)
3544 a = b[slice(25, 125, None)]
3545 assert (a == range(25, 125)).all()
3546 a = b[[slice(25, 125, None)]]
3547 assert a.shape == (100,)
3548 # a is a view into b
3549 a[10] = 200
3550 assert b[35] == 200
3551 b[[slice(25, 30)]] = range(5)
3552 assert all(a[:5] == range(5))
3553 raises(IndexError, 'b[[[slice(25, 125)]]]')
3554
3555 def test_cumsum(self):
3556 from numpy import arange
3557 a = arange(6).reshape(3, 2)
3558 b = arange(6)
3559 assert (a.cumsum() == [0, 1, 3, 6, 10, 15]).all()
3560 a.cumsum(out=b)
3561 assert (b == [0, 1, 3, 6, 10, 15]).all()
3562 raises(ValueError, "a.cumsum(out=arange(6).reshape(3, 2))")
3563
3564 def test_cumprod(self):
3565 from numpy import array
3566 a = array([[1, 2], [3, 4], [5, 6]])
3567 assert (a.cumprod() == [1, 2, 6, 24, 120, 720]).all()
3568
3569 def test_cumsum_axis(self):
3570 from numpy import arange, array
3571 a = arange(6).reshape(3, 2)
3572 assert (a.cumsum(0) == [[0, 1], [2, 4], [6, 9]]).all()
3573 assert (a.cumsum(1) == [[0, 1], [2, 5], [4, 9]]).all()
3574 a = array([[1, 1], [2, 2], [3, 4]])
3575 assert (a.cumsum(1) == [[1, 2], [2, 4], [3, 7]]).all()
3576 assert (a.cumsum(0) == [[1, 1], [3, 3], [6, 7]]).all()
3577
3578 def test_diagonal(self):
3579 from numpy import array
3580 a = array([[1, 2], [3, 4], [5, 6]])
3581 raises(ValueError, 'array([1, 2]).diagonal()')
3582 raises(ValueError, 'a.diagonal(0, 0, 0)')
3583 raises(ValueError, 'a.diagonal(0, 0, 13)')
3584 assert (a.diagonal() == [1, 4]).all()
3585 assert (a.diagonal(1) == [2]).all()
3586
3587 def test_diagonal_axis(self):
3588 from numpy import arange
3589 a = arange(12).reshape(2, 3, 2)
3590 assert (a.diagonal(0, 0, 1) == [[0, 8], [1, 9]]).all()
3591 assert a.diagonal(3, 0, 1).shape == (2, 0)
3592 assert (a.diagonal(1, 0, 1) == [[2, 10], [3, 11]]).all()
3593 assert (a.diagonal(0, 2, 1) == [[0, 3], [6, 9]]).all()
3594 assert (a.diagonal(2, 2, 1) == [[4], [10]]).all()
3595 assert (a.diagonal(1, 2, 1) == [[2, 5], [8, 11]]).all()
3596
3597 def test_diagonal_axis_neg_ofs(self):
3598 from numpy import arange
3599 a = arange(12).reshape(2, 3, 2)
3600 assert (a.diagonal(-1, 0, 1) == [[6], [7]]).all()
3601 assert a.diagonal(-2, 0, 1).shape == (2, 0)
3602
3603
3604 class AppTestSupport(BaseNumpyAppTest):
3605 spaceconfig = {'usemodules': ['micronumpy', 'array']}
3606
3607 def setup_class(cls):
3608 import struct
3609 BaseNumpyAppTest.setup_class.im_func(cls)
3610 cls.w_data = cls.space.wrap(struct.pack('dddd', 1, 2, 3, 4))
3611 cls.w_fdata = cls.space.wrap(struct.pack('f', 2.3))
3612 import sys
3613 if sys.byteorder == 'big':
3614 cls.w_float16val = cls.space.wrap('E\x00') # 5.0 in float16
3615 else:
3616 cls.w_float16val = cls.space.wrap('\x00E') # 5.0 in float16
3617 cls.w_float32val = cls.space.wrap(struct.pack('f', 5.2))
3618 cls.w_float64val = cls.space.wrap(struct.pack('d', 300.4))
3619 cls.w_ulongval = cls.space.wrap(struct.pack('L', 12))
3620 cls.w_one = cls.space.wrap(struct.pack('i', 1))
3621
3622 def test_frombuffer(self):
3623 import numpy as np
3624 exc = raises(AttributeError, np.frombuffer, None)
3625 assert str(exc.value) == "'NoneType' object has no attribute '__buffer__'"
3626 exc = raises(ValueError, np.frombuffer, self.data, 'S0')
3627 assert str(exc.value) == "itemsize cannot be zero in type"
3628 exc = raises(ValueError, np.frombuffer, self.data, offset=-1)
3629 assert str(exc.value) == "offset must be non-negative and no greater than buffer length (32)"
3630 exc = raises(ValueError, np.frombuffer, self.data, count=100)
3631 assert str(exc.value) == "buffer is smaller than requested size"
3632 for data in [self.data, buffer(self.data)]:
3633 a = np.frombuffer(data)
3634 for i in range(4):
3635 assert a[i] == i + 1
3636
3637 import array
3638 data = array.array('c', 'testing')
3639 a = np.frombuffer(data, 'c')
3640 assert a.base is data
3641 a[2] = 'Z'
3642 assert data.tostring() == 'teZting'
3643
3644 data = buffer(data)
3645 a = np.frombuffer(data, 'c')
3646 assert a.base is data
3647 exc = raises(ValueError, "a[2] = 'Z'")
3648 assert str(exc.value) == "assignment destination is read-only"
3649
3650 class A(object):
3651 def __buffer__(self, flags):
3652 return 'abc'
3653
3654 data = A()
3655 a = np.frombuffer(data, 'c')
3656 #assert a.base is data.__buffer__
3657 assert a.tostring() == 'abc'
3658
3659 def test_memoryview(self):
3660 import numpy as np
3661 import sys
3662 if sys.version_info[:2] > (3, 2):
3663 # In Python 3.3 the representation of empty shape, strides and sub-offsets
3664 # is an empty tuple instead of None.
3665 # http://docs.python.org/dev/whatsnew/3.3.html#api-changes
3666 EMPTY = ()
3667 else:
3668 EMPTY = None
3669 x = np.array([1, 2, 3, 4, 5], dtype='i')
3670 y = memoryview(x)
3671 assert y.format == 'i'
3672 assert y.shape == (5,)
3673 assert y.ndim == 1
3674 assert y.strides == (4,)
3675 assert y.suboffsets == EMPTY
3676 assert y.itemsize == 4
3677 assert isinstance(y, memoryview)
3678 assert y[0] == self.one
3679 assert (np.array(y) == x).all()
3680
3681 x = np.array([0, 0, 0, 0], dtype='O')
3682 y = memoryview(x)
3683 # handles conversion of address to pinned object?
3684 z = np.array(y)
3685 assert z.dtype == 'O'
3686 assert (z == x).all()
3687
3688 dt1 = np.dtype(
3689 [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')],
3690 align=True)
3691 x = np.arange(dt1.itemsize, dtype=np.int8).view(dt1)
3692 y = memoryview(x)
3693 if '__pypy__' in sys.builtin_module_names:
3694 assert y.format == 'T{b:a:xxxi:b:T{b:f0:i:f1:}:sub:xxxi:c:}'
3695 else:
3696 assert y.format == 'T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxx@i:c:}'
3697
3698
3699 dt1 = np.dtype(
3700 [('a', 'b'), ('b', 'i'), ('sub', np.dtype('b,i')), ('c', 'i')],
3701 align=True)
3702 x = np.arange(dt1.itemsize, dtype=np.int8).view(dt1)
3703 y = memoryview(x)
3704 if '__pypy__' in sys.builtin_module_names:
3705 assert y.format == 'T{b:a:xxxi:b:T{b:f0:i:f1:}:sub:xxxi:c:}'
3706 else:
3707 assert y.format == 'T{b:a:xxxi:b:T{b:f0:=i:f1:}:sub:xxx@i:c:}'
3708
3709
3710 def test_fromstring(self):
3711 import sys
3712 from numpy import fromstring, dtype
3713
3714 a = fromstring(self.data)
3715 for i in range(4):
3716 assert a[i] == i + 1
3717 b = fromstring('\x01\x02', dtype='uint8')
3718 assert a[0] == 1
3719 assert a[1] == 2
3720 c = fromstring(self.fdata, dtype='float32')
3721 assert c[0] == dtype('float32').type(2.3)
3722 d = fromstring("1 2", sep=' ', count=2, dtype='uint8')
3723 assert len(d) == 2
3724 assert d[0] == 1
3725 assert d[1] == 2
3726 e = fromstring('3, 4,5', dtype='uint8', sep=',')
3727 assert len(e) == 3
3728 assert e[0] == 3
3729 assert e[1] == 4
3730 assert e[2] == 5
3731 f = fromstring('\x01\x02\x03\x04\x05', dtype='uint8', count=3)
3732 assert len(f) == 3
3733 assert f[0] == 1
3734 assert f[1] == 2
3735 assert f[2] == 3
3736 g = fromstring("1 2 3 ", dtype='uint8', sep=" ")
3737 assert len(g) == 3
3738 assert g[0] == 1
3739 assert g[1] == 2
3740 assert g[2] == 3
3741 h = fromstring("1, , 2, 3", dtype='uint8', sep=",")
3742 assert (h == [1, 0, 2, 3]).all()
3743 i = fromstring("1 2 3", dtype='uint8', sep=" ")
3744 assert (i == [1, 2, 3]).all()
3745 j = fromstring("1\t\t\t\t2\t3", dtype='uint8', sep="\t")
3746 assert (j == [1, 2, 3]).all()
3747 k = fromstring("1,x,2,3", dtype='uint8', sep=",")
3748 assert (k == [1, 0]).all()
3749 l = fromstring("1,x,2,3", dtype='float32', sep=",")
3750 assert (l == [1.0, -1.0]).all()
3751 m = fromstring("1,,2,3", sep=",")
3752 assert (m == [1.0, -1.0, 2.0, 3.0]).all()
3753 n = fromstring("3.4 2.0 3.8 2.2", dtype='int32', sep=" ")
3754 assert (n == [3]).all()
3755 n = fromstring('\x00\x00\x00{', dtype='>i4')
3756 assert n == 123
3757 n = fromstring('W\xb0', dtype='>f2')
3758 assert n == 123.
3759 o = fromstring("1.0 2f.0f 3.8 2.2", dtype='float32', sep=" ")
3760 assert len(o) == 2
3761 assert o[0] == 1.0
3762 assert o[1] == 2.0
3763 p = fromstring("1.0,,2.0,3.0", sep=",")
3764 assert (p == [1.0, -1.0, 2.0, 3.0]).all()
3765 q = fromstring("1.0,,2.0,3.0", sep=" ")
3766 assert (q == [1.0]).all()
3767 r = fromstring("\x01\x00\x02", dtype='bool')
3768 assert (r == [True, False, True]).all()
3769 s = fromstring("1,2,3,,5", dtype=bool, sep=",")
3770 assert (s == [True, True, True, True, True]).all()
3771 t = fromstring("", bool)
3772 assert (t == []).all()
3773 u = fromstring("\x01\x00\x00\x00\x00\x00\x00\x00", dtype=int)
3774 if sys.maxint > 2 ** 31 - 1:
3775 if sys.byteorder == 'big':
3776 assert (u == [0x0100000000000000]).all()
3777 else:
3778 assert (u == [1]).all()
3779 else:
3780 if sys.byteorder == 'big':
3781 assert (u == [0x01000000, 0]).all()
3782 else:
3783 assert (u == [1, 0]).all()
3784 v = fromstring("abcd", dtype="|S2")
3785 assert v[0] == "ab"
3786 assert v[1] == "cd"
3787
3788 v = fromstring('@\x01\x99\x99\x99\x99\x99\x9a\xbf\xf1\x99\x99\x99\x99\x99\x9a',
3789 dtype=dtype('>c16'))
3790 assert v.tostring() == \
3791 '@\x01\x99\x99\x99\x99\x99\x9a\xbf\xf1\x99\x99\x99\x99\x99\x9a'
3792 assert v[0] == 2.2-1.1j
3793 assert v.real == 2.2
3794 assert v.imag == -1.1
3795 v = fromstring('\x9a\x99\x99\x99\x99\x99\x01@\x9a\x99\x99\x99\x99\x99\xf1\xbf',
3796 dtype=dtype('<c16'))
3797 assert v.tostring() == \
3798 '\x9a\x99\x99\x99\x99\x99\x01@\x9a\x99\x99\x99\x99\x99\xf1\xbf'
3799 assert v[0] == 2.2-1.1j
3800 assert v.real == 2.2
3801 assert v.imag == -1.1
3802
3803 d = [('f0', 'i4'), ('f1', 'u2', (2, 3))]
3804 if '__pypy__' not in sys.builtin_module_names:
3805 r = fromstring('abcdefghijklmnop'*4*3, dtype=d)
3806 assert (r[0:3:2]['f1'] == r['f1'][0:3:2]).all()
3807 assert (r[0:3:2]['f1'][0] == r[0:3:2][0]['f1']).all()
3808 assert (r[0:3:2]['f1'][0][()] == r[0:3:2][0]['f1'][()]).all()
3809 assert r[0:3:2]['f1'][0].strides == r[0:3:2][0]['f1'].strides
3810 else:
3811 exc = raises(NotImplementedError, fromstring,
3812 'abcdefghijklmnop'*4*3, dtype=d)
3813 assert exc.value[0] == "fromstring not implemented for record types"
3814
3815 def test_fromstring_types(self):
3816 from numpy import fromstring, array, dtype
3817 a = fromstring('\xFF', dtype='int8')
3818 assert a[0] == -1
3819 b = fromstring('\xFF', dtype='uint8')
3820 assert b[0] == 255
3821 c = fromstring('\xFF\xFF', dtype='int16')
3822 assert c[0] == -1
3823 d = fromstring('\xFF\xFF', dtype='uint16')
3824 assert d[0] == 65535
3825 e = fromstring('\xFF\xFF\xFF\xFF', dtype='int32')
3826 assert e[0] == -1
3827 f = fromstring('\xFF\xFF\xFF\xFF', dtype='uint32')
3828 assert repr(f[0]) == '4294967295'
3829 g = fromstring('\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF', dtype='int64')
3830 assert g[0] == -1
3831 h = fromstring(self.float32val, dtype='float32')
3832 assert h[0] == dtype('float32').type(5.2)
3833 i = fromstring(self.float64val, dtype='float64')
3834 assert i[0] == dtype('float64').type(300.4)
3835 j = fromstring(self.ulongval, dtype='L')
3836 assert j[0] == 12
3837 k = fromstring(self.float16val, dtype='float16')
3838 assert k[0] == dtype('float16').type(5.)
3839 dt = array([5], dtype='longfloat').dtype
3840 print(dt.itemsize)
3841 if dt.itemsize == 8:
3842 import sys
3843 if sys.byteorder == 'big':
3844 m = fromstring('@\x14\x00\x00\x00\x00\x00\x00',
3845 dtype='float64')
3846 else:
3847 m = fromstring('\x00\x00\x00\x00\x00\x00\x14@',
3848 dtype='float64')
3849 elif dt.itemsize == 12:
3850 m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00',
3851 dtype='float96')
3852 elif dt.itemsize == 16:
3853 m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00' \
3854 '\x00\x00\x00\x00', dtype='float128')
3855 else:
3856 assert False, 'unknown itemsize for longfloat'
3857 assert m[0] == dtype('longfloat').type(5.)
3858
3859 def test_fromstring_invalid(self):
3860 from numpy import fromstring
3861 #default dtype is 64-bit float, so 3 bytes should fail
3862 raises(ValueError, fromstring, "\x01\x02\x03")
3863 #3 bytes is not modulo 2 bytes (int16)
3864 raises(ValueError, fromstring, "\x01\x03\x03", dtype='uint16')
3865 #5 bytes is larger than 3 bytes
3866 raises(ValueError, fromstring, "\x01\x02\x03", count=5, dtype='uint8')
3867
3868 def test_tostring(self):
3869 from numpy import array
3870 import sys
3871 if sys.byteorder == 'big':
3872 assert array([1, 2, 3], 'i2').tostring() == '\x00\x01\x00\x02\x00\x03'
3873 assert array([1, 2, 3], 'i2')[::2].tostring() == '\x00\x01\x00\x03'
3874 else:
3875 assert array([1, 2, 3], 'i2').tostring() == '\x01\x00\x02\x00\x03\x00'
3876 assert array([1, 2, 3], 'i2')[::2].tostring() == '\x01\x00\x03\x00'
3877 assert array([1, 2, 3], '<i2')[::2].tostring() == '\x01\x00\x03\x00'
3878 assert array([1, 2, 3], '>i2')[::2].tostring() == '\x00\x01\x00\x03'
3879 assert array(0, dtype='i2').tostring() == '\x00\x00'
3880 a = array([[1, 2], [3, 4]], dtype='i1')
3881 for order in (None, False, 'C', 'K', 'a'):
3882 assert a.tostring(order) == '\x01\x02\x03\x04'
3883 import sys
3884 for order in (True, 'F'):
3885 assert a.tostring(order) == '\x01\x03\x02\x04'
3886 assert array(2.2-1.1j, dtype='>c16').tostring() == \
3887 '@\x01\x99\x99\x99\x99\x99\x9a\xbf\xf1\x99\x99\x99\x99\x99\x9a'
3888 assert array(2.2-1.1j, dtype='<c16').tostring() == \
3889 '\x9a\x99\x99\x99\x99\x99\x01@\x9a\x99\x99\x99\x99\x99\xf1\xbf'
3890 assert a.tostring == a.tobytes
3891
3892 def test_str(self):
3893 from numpy import array
3894 assert str(array([1, 2, 3])) == '[1 2 3]'
3895 assert str(array(['abc'], 'S3')) == "['abc']"
3896 assert str(array('abc')) == 'abc'
3897 assert str(array(1.5)) == '1.5'
3898 assert str(array(1.5).real) == '1.5'
3899 arr = array(['abc', 'abc'])
3900 for a in arr.flat:
3901 assert str(a) == 'abc'
3902
3903 def test_ndarray_buffer_strides(self):
3904 from numpy import ndarray, array
3905 base = array([1, 2, 3, 4], dtype=int)
3906 a = ndarray((4,), buffer=base, dtype=int)
3907 assert a[1] == 2
3908 a = ndarray((4,), buffer=base, dtype=int, strides=[base.strides[0]])
3909 assert a[1] == 2
3910 a = ndarray((2,), buffer=base, dtype=int, strides=[2 * base.strides[0]])
3911 assert a[1] == 3
3912 exc = raises(ValueError, ndarray, (4,), buffer=base, dtype=int, strides=[2 * base.strides[0]])
3913 assert exc.value[0] == 'strides is incompatible with shape of requested array and size of buffer'
3914 exc = raises(ValueError, ndarray, (2, 1), buffer=base, dtype=int, strides=[base.strides[0]])
3915 assert exc.value[0] == 'strides, if given, must be the same length as shape'
3916
3917
3918
3919 class AppTestRepr(BaseNumpyAppTest):
3920 def setup_class(cls):
3921 if option.runappdirect:
3922 py.test.skip("Can't be run directly.")
3923 BaseNumpyAppTest.setup_class.im_func(cls)
3924 cache = get_appbridge_cache(cls.space)
3925 cls.old_array_repr = cache.w_array_repr
3926 cls.old_array_str = cache.w_array_str
3927 cache.w_array_str = None
3928 cache.w_array_repr = None
3929
3930 def test_repr(self):
3931 from numpy import array
3932 assert repr(array([1, 2, 3])) == 'array([1, 2, 3])'
3933 assert repr(array(['abc'], 'S3')) == "array(['abc'])"
3934 assert repr(array(1.5)) == "array(1.5)"
3935 assert repr(array(1.5).real) == "array(1.5)"
3936
3937 def teardown_class(cls):
3938 if option.runappdirect:
3939 return
3940 cache = get_appbridge_cache(cls.space)
3941 cache.w_array_repr = cls.old_array_repr
3942 cache.w_array_str = cls.old_array_str
3943
3944
3945 class AppTestRecordDtype(BaseNumpyAppTest):
3946 spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii"])
3947
3948 def test_zeros(self):
3949 from numpy import zeros, void
3950 a = zeros((), dtype=[('x', int), ('y', float)])
3951 assert type(a[()]) is void
3952 assert type(a.item()) is tuple
3953 assert a[()]['x'] == 0
3954 assert a[()]['y'] == 0
3955 assert a.shape == ()
3956 a = zeros(2, dtype=[('x', int), ('y', float)])
3957 raises(ValueError, 'a[0]["xyz"]')
3958 assert a[0]['x'] == 0
3959 assert a[0]['y'] == 0
3960 exc = raises(ValueError, "a[0] = (1, 2, 3)")
3961 assert exc.value[0] == 'size of tuple must match number of fields.'
3962 a[0]['x'] = 13
3963 assert a[0]['x'] == 13
3964 a[1] = (1, 2)
3965 assert a[1]['y'] == 2
3966 b = zeros(2, dtype=[('x', int), ('y', float)])
3967 b[1] = a[1]
3968 assert a[1]['y'] == 2
3969
3970 def test_views(self):
3971 from numpy import array, zeros, ndarray
3972 a = zeros((), dtype=[('x', int), ('y', float)])
3973 raises(IndexError, 'a[0]')
3974 assert type(a['x']) is ndarray
3975 assert a['x'] == 0
3976 assert a['y'] == 0
3977 a = array([(1, 2), (3, 4)], dtype=[('x', int), ('y', float)])
3978 raises((IndexError, ValueError), 'array([1])["x"]')
3979 raises((IndexError, ValueError), 'a["z"]')
3980 assert a['x'][1] == 3
3981 assert a['y'][1] == 4
3982 a['x'][0] = 15
3983 assert a['x'][0] == 15
3984 b = a['x'] + a['y']
3985 assert (b == [15+2, 3+4]).all()
3986 assert b.dtype == float
3987
3988 def test_assign_tuple(self):
3989 from numpy import zeros
3990 a = zeros((2, 3), dtype=[('x', int), ('y', float)])
3991 a[1, 2] = (1, 2)
3992 assert a['x'][1, 2] == 1
3993 assert a['y'][1, 2] == 2
3994
3995 def test_creation_and_repr(self):
3996 from numpy import array
3997 a = array((1, 2), dtype=[('x', int), ('y', float)])
3998 assert a.shape == ()
3999 assert repr(a[()]) == '(1, 2.0)'
4000 a = array([(1, 2), (3, 4)], dtype=[('x', int), ('y', float)])
4001 assert repr(a[0]) == '(1, 2.0)'
4002
4003 def test_void_copyswap(self):
4004 import numpy as np
4005 dt = np.dtype([('one', '<i4'), ('two', '<i4')])
4006 x = np.array((1, 2), dtype=dt)
4007 x = x.byteswap()
4008 import sys
4009 if '__pypy__' not in sys.builtin_module_names:
4010 assert x['one'] > 0 and x['two'] > 2
4011 else:
4012 assert x['one'] == 1 and x['two'] == 2
4013
4014 def test_nested_dtype(self):
4015 import numpy as np
4016 a = [('x', int), ('y', float)]
4017 b = [('x', int), ('y', a)]
4018 arr = np.zeros((), dtype=b)
4019 assert arr['x'] == 0
4020 arr['x'] = 2
4021 assert arr['x'] == 2
4022 exc = raises(IndexError, "arr[3L]")
4023 assert exc.value.message == "too many indices for array"
4024 exc = raises(ValueError, "arr['xx'] = 2")
4025 assert exc.value.message == "no field of name xx"
4026 assert arr['y'].dtype == a
4027 assert arr['y'].shape == ()
4028 assert arr['y'][()]['x'] == 0
4029 assert arr['y'][()]['y'] == 0
4030 arr['y'][()]['x'] = 2
4031 arr['y'][()]['y'] = 3
4032 assert arr['y'][()]['x'] == 2
4033 assert arr['y'][()]['y'] == 3
4034 arr = np.zeros(3, dtype=b)
4035 arr[1]['x'] = 15
4036 assert arr[1]['x'] == 15
4037 arr[1]['y']['y'] = 3.5
4038 assert arr[1]['y']['y'] == 3.5
4039 assert arr[1]['y']['x'] == 0.0
4040 assert arr[1]['x'] == 15
4041
4042 def test_count_nonzero(self):
4043 import numpy as np
4044 import sys
4045 d = [('f0', 'i4'), ('f1', 'i4', 2)]
4046 arr = np.array([0, 1])
4047 if '__pypy__' not in sys.builtin_module_names:
4048 arr = arr.astype(d)[:1]
4049 assert np.count_nonzero(arr) == 0
4050 else:
4051 raises(NotImplementedError, "arr.astype(d)")
4052
4053 def test_string_record(self):
4054 from numpy import dtype, array
4055
4056 d = dtype([('x', str), ('y', 'int32')])
4057 assert str(d.fields['x'][0]) == '|S0'
4058 assert d.fields['x'][1] == 0
4059 assert str(d.fields['y'][0]) == 'int32'
4060 assert d.fields['y'][1] == 0
4061 assert d.name == 'void32'
4062
4063 a = array([('a', 2), ('cde', 1)], dtype=d)
4064 if 0: # XXX why does numpy allow this?
4065 assert a[0]['x'] == '\x02'
4066 assert a[0]['y'] == 2
4067 if 0: # XXX why does numpy allow this?
4068 assert a[1]['x'] == '\x01'
4069 assert a[1]['y'] == 1
4070
4071 d = dtype([('x', 'S1'), ('y', 'int32')])
4072 assert str(d.fields['x'][0]) == '|S1'
4073 assert d.fields['x'][1] == 0
4074 assert str(d.fields['y'][0]) == 'int32'
4075 assert d.fields['y'][1] == 1
4076 assert d.name == 'void40'
4077
4078 a = array([('a', 2), ('cde', 1)], dtype=d)
4079 assert a[0]['x'] == 'a'
4080 assert a[0]['y'] == 2
4081 assert a[1]['x'] == 'c'
4082 assert a[1]['y'] == 1
4083
4084 def test_string_array(self):
4085 from numpy import array
4086 a = array(['abc'])
4087 assert str(a.dtype) == '|S3'
4088 a = array(['abc'], 'S')
4089 assert str(a.dtype) == '|S3'
4090 a = array(['abc'], 'S3')
4091 assert str(a.dtype) == '|S3'
4092 a = array(['abcde'], 'S3')
4093 assert str(a.dtype) == '|S3'
4094 a = array(['abc', 'defg', 'ab'])
4095 assert str(a.dtype) == '|S4'
4096 assert a[0] == 'abc'
4097 assert a[1] == 'defg'
4098 assert a[2] == 'ab'
4099 a = array(['abc', 'defg', 'ab'], 'S3')
4100 assert str(a.dtype) == '|S3'
4101 assert a[0] == 'abc'
4102 assert a[1] == 'def'
4103 assert a[2] == 'ab'
4104 b = array(["\x00\x01", "\x00\x02\x03"], dtype=str)
4105 assert str(b.dtype) == '|S3'
4106 assert b[0] == "\x00\x01"
4107 assert b[1] == "\x00\x02\x03"
4108 assert b.tostring() == "\x00\x01\x00\x00\x02\x03"
4109 c = b.astype(b.dtype)
4110 assert (b == c).all()
4111 assert c.tostring() == "\x00\x01\x00\x00\x02\x03"
4112 raises(TypeError, a, 'sum')
4113 raises(TypeError, 'a+a')
4114 b = array(['abcdefg', 'ab', 'cd'])
4115 assert a[2] == b[1]
4116 assert bool(a[1])
4117 c = array(['ab','cdefg','hi','jk'])
4118 # not implemented yet
4119 #c[0] += c[3]
4120 #assert c[0] == 'abjk'
4121
4122 def test_to_str(self):
4123 from numpy import array
4124 a = array(['abc','abc', 'def', 'ab'], 'S3')
4125 b = array(['mnopqr','abcdef', 'ab', 'cd'])
4126 assert b[1] != a[1]
4127
4128 def test_string_scalar(self):
4129 from numpy import array
4130 a = array('ffff')
4131 assert a.shape == ()
4132 a = array([], dtype='S')
4133 assert str(a.dtype) == '|S1'
4134 a = array('x', dtype='>S')
4135 assert str(a.dtype) == '|S1'
4136 a = array('x', dtype='c')
4137 assert str(a.dtype) == '|S1'
4138 assert a == 'x'
4139 a = array('abc', 'S2')
4140 assert a.dtype.str == '|S2'
4141 assert a == 'ab'
4142 a = array('abc', 'S5')
4143 assert a.dtype.str == '|S5'
4144 assert a == 'abc'
4145
4146 def test_newbyteorder(self):
4147 import numpy as np
4148 a = np.array([1, 2], dtype=np.int16)
4149 b = a.newbyteorder()
4150 assert (b == [256, 512]).all()
4151 c = b.byteswap()
4152 assert (c == [1, 2]).all()
4153 assert (a == [1, 2]).all()
4154
4155 def test_pickle(self):
4156 from numpy import dtype, array, int32
4157 from cPickle import loads, dumps
4158
4159 d = dtype([('x', str), ('y', 'int32')])
4160 a = array([('a', 2), ('cde', 1)], dtype=d)
4161
4162 a = loads(dumps(a))
4163 d = a.dtype
4164
4165 assert str(d.fields['x'][0]) == '|S0'
4166 assert d.fields['x'][1] == 0
4167 assert str(d.fields['y'][0]) == 'int32'
4168 assert d.fields['y'][1] == 0
4169 assert d.name == 'void32'
4170
4171 assert a[0]['y'] == 2
4172 assert a[1]['y'] == 1
4173
4174 a = array([(1, [])], dtype=[('a', int32), ('b', int32, 0)])
4175 assert a['b'].shape == (1, 0)
4176 b = loads(dumps(a))
4177 assert b['b'].shape == (1, 0)
4178
4179 def test_subarrays(self):
4180 from numpy import dtype, array, zeros
4181 d = dtype([("x", "int", 3), ("y", "float", 5)])
4182
4183 a = zeros((), dtype=d)
4184 #assert a['x'].dtype == int
4185 #assert a['x'].shape == (3,)
4186 #assert (a['x'] == [0, 0, 0]).all()
4187
4188 a = array([([1, 2, 3], [0.5, 1.5, 2.5, 3.5, 4.5]),
4189 ([4, 5, 6], [5.5, 6.5, 7.5, 8.5, 9.5])], dtype=d)
4190 for v in ['x', u'x', 0, -2]:
4191 assert (a[0][v] == [1, 2, 3]).all()
4192 assert (a[1][v] == [4, 5, 6]).all()
4193 for v in ['y', u'y', -1, 1]:
4194 assert (a[0][v] == [0.5, 1.5, 2.5, 3.5, 4.5]).all()
4195 assert (a[1][v] == [5.5, 6.5, 7.5, 8.5, 9.5]).all()
4196 for v in [-3, 2]:
4197 exc = raises(IndexError, "a[0][%d]" % v)
4198 assert exc.value.message == "invalid index (%d)" % \
4199 (v + 2 if v < 0 else v)
4200 exc = raises(ValueError, "a[0]['z']")
4201 assert exc.value.message == "no field of name z"
4202 exc = raises(IndexError, "a[0][None]")
4203 assert exc.value.message == "invalid index"
4204
4205 a[0]["x"][0] = 200
4206 assert a[0]["x"][0] == 200
4207 a[1]["x"][2] = 123
4208 assert (a[1]["x"] == [4, 5, 123]).all()
4209 a[1]['y'][3] = 4
4210 assert a[1]['y'][3] == 4
4211 assert a['y'][1][3] == 4
4212 a['y'][1][4] = 5
4213 assert a[1]['y'][4] == 5
4214
4215 d = dtype([("x", "int64", (2, 3))])
4216 a = array([([[1, 2, 3], [4, 5, 6]],)], dtype=d)
4217
4218 assert a[0]["x"].dtype == dtype("int64")
4219 assert a[0]["x"][0].dtype == dtype("int64")
4220
4221 assert (a[0]["x"][0] == [1, 2, 3]).all()
4222 assert (a[0]["x"] == [[1, 2, 3], [4, 5, 6]]).all()
4223
4224 d = dtype((float, (10, 10)))
4225 a = zeros((3,3), dtype=d)
4226 assert a[0, 0].shape == (10, 10)
4227 assert a.shape == (3, 3, 10, 10)
4228 a[0, 0] = 500
4229 assert (a[0, 0, 0] == 500).all()
4230 assert a[0, 0, 0].shape == (10,)
4231 exc = raises(IndexError, "a[0, 0]['z']")
4232 assert exc.value.message.startswith('only integers, slices')
4233
4234 import sys
4235 a = array(1.5, dtype=float)
4236 assert a.shape == ()
4237 if '__pypy__' not in sys.builtin_module_names:
4238 a = a.astype((float, 2))
4239 repr(a) # check for crash
4240 assert a.shape == (2,)
4241 assert tuple(a) == (1.5, 1.5)
4242 else:
4243 raises(NotImplementedError, "a.astype((float, 2))")
4244
4245 a = array([1.5], dtype=float)
4246 assert a.shape == (1,)
4247 if '__pypy__' not in sys.builtin_module_names:
4248 a = a.astype((float, 2))
4249 repr(a) # check for crash
4250 assert a.shape == (1, 2)
4251 assert tuple(a[0]) == (1.5, 1.5)
4252 else:
4253 raises(NotImplementedError, "a.astype((float, 2))")
4254
4255 def test_subarray_multiple_rows(self):
4256 import numpy as np
4257 descr = [
4258 ('x', 'i4', (2,)),
4259 ('y', 'f8', (2, 2)),
4260 ('z', 'u1')]
4261 buf = [
4262 # x y z
4263 ([3,2], [[6.,4.],[6.,4.]], 8),
4264 ([4,3], [[7.,5.],[7.,5.]], 9),
4265 ]
4266 h = np.array(buf, dtype=descr)
4267 assert len(h) == 2
4268 assert h['x'].shape == (2, 2)
4269 assert h['y'].strides == (41, 16, 8)
4270 assert h['z'].shape == (2,)
4271 for v in (h, h[0], h['x']):
4272 repr(v) # check for crash in repr
4273 assert (h['x'] == np.array([buf[0][0],
4274 buf[1][0]], dtype='i4')).all()
4275 assert (h['y'] == np.array([buf[0][1],
4276 buf[1][1]], dtype='f8')).all()
4277 assert (h['z'] == np.array([buf[0][2],
4278 buf[1][2]], dtype='u1')).all()
4279
4280 def test_multidim_subarray(self):
4281 from numpy import dtype, array
4282
4283 d = dtype([("x", "int64", (2, 3))])
4284 a = array([([[1, 2, 3], [4, 5, 6]],)], dtype=d)
4285
4286 assert a[0]["x"].dtype == dtype("int64")
4287 assert a[0]["x"][0].dtype == dtype("int64")
4288
4289 assert (a[0]["x"][0] == [1, 2, 3]).all()
4290 assert (a[0]["x"] == [[1, 2, 3], [4, 5, 6]]).all()
4291
4292 def test_list_record(self):
4293 from numpy import dtype, array
4294
4295 d = dtype([("x", "int", 3), ("y", "float", 5)])
4296 a = array([([1, 2, 3], [0.5, 1.5, 2.5, 3.5, 4.5]),
4297 ([4, 5, 6], [5.5, 6.5, 7.5, 8.5, 9.5])], dtype=d)
4298
4299 assert len(list(a[0])) == 2
4300
4301 mdtype = dtype([('a', bool), ('b', bool), ('c', bool)])
4302 a = array([0, 0, 0, 1, 1])
4303 # this creates a value of (x, x, x) in b for each x in a
4304 b = array(a, dtype=mdtype)
4305 assert b.shape == a.shape
4306 c = array([(x, x, x) for x in [0, 0, 0, 1, 1]], dtype=mdtype)
4307 assert (b == c).all()
4308
4309 def test_3d_record(self):
4310 from numpy import dtype, array
4311 dt = dtype([('name', 'S4'), ('x', float), ('y', float),
4312 ('block', int, (2, 2, 3))])
4313 a = array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],
4314 [[7, 8, 9], [10, 11, 12]]])],
4315 dtype=dt)
4316 i = a.item()
4317 assert isinstance(i, tuple)
4318 assert len(i) == 4
4319 import sys
4320 if '__pypy__' not in sys.builtin_module_names:
4321 assert str(a) == "[('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]], " \
4322 "[[7, 8, 9], [10, 11, 12]]])]"
4323 else:
4324 assert str(a) == "[('aaaa', 1.0, 8.0, [1, 2, 3, 4, 5, 6, " \
4325 "7, 8, 9, 10, 11, 12])]"
4326
4327 def test_issue_1589(self):
4328 import numpy
4329 c = numpy.array([[(1, 2, 'a'), (3, 4, 'b')], [(5, 6, 'c'), (7, 8, 'd')]],
4330 dtype=[('bg', 'i8'), ('fg', 'i8'), ('char', 'S1')])
4331 assert c[0][0]["char"] == 'a'
4332
4333 def test_scalar_coercion(self):
4334 import numpy as np
4335 a = np.array([1,2,3], dtype='int16')
4336 assert (a * 2).dtype == np.dtype('int16')
4337
4338 def test_coerce_record(self):
4339 import numpy as np
4340 dt = np.dtype([('a', '?'), ('b', '?')])
4341 b = np.array([True, True])
4342 a = np.array([b, b, b], dtype=dt)
4343 assert a.shape == (3, 2)
4344 for i in a.flat:
4345 assert tuple(i) == (True, True)
4346
4347 dt = np.dtype([('A', '<i8'), ('B', '<f8'), ('C', '<c16')])
4348 b = np.array((999999, 1e+20, 1e+20+0j), dtype=dt)
4349 a = np.array(b, copy=False, dtype=dt.descr)
4350 assert tuple(a[()]) == (999999, 1e+20, 1e+20+0j)
4351
4352 def test_reduce_record(self):
4353 import numpy as np
4354 dt = np.dtype([('a', float), ('b', float)])
4355 a = np.array(list(zip(range(10), reversed(range(10)))), dtype=dt)
4356 exc = raises(TypeError, np.maximum.reduce, a)
4357 assert exc.value[0] == 'cannot perform reduce with flexible type'
4358 v = a.view((float, 2))
4359 assert v.dtype == np.dtype(float)
4360 assert v.shape == (10, 2)
4361 m = np.maximum.reduce(v)
4362 assert (m == [9, 9]).all()
4363 m = np.maximum.reduce(v, axis=None)
4364 assert (m == [9, 9]).all()
4365 m = np.maximum.reduce(v, axis=-1)
4366 assert (m == [9, 8, 7, 6, 5, 5, 6, 7, 8, 9]).all()
4367 m = v.argmax()
4368 assert m == 1
4369 v = a.view(('float32', 4))
4370 assert v.dtype == np.dtype('float32')
4371 assert v.shape == (10, 4)
4372 import sys
4373 if sys.byteorder == 'big':
4374 assert v[0][-2] == 2.53125
4375 else:
4376 assert v[0][-1] == 2.53125
4377 exc = raises(ValueError, "a.view(('float32', 2))")
4378 assert exc.value[0] == 'new type not compatible with array.'
4379
4380 def test_record_ufuncs(self):
4381 import numpy as np
4382 a = np.zeros(3, dtype=[('a', 'i8'), ('b', 'i8')])
4383 b = np.zeros(3, dtype=[('a', 'i8'), ('b', 'i8')])
4384 c = np.zeros(3, dtype=[('a', 'f8'), ('b', 'f8')])
4385 d = np.ones(3, dtype=[('a', 'i8'), ('b', 'i8')])
4386 e = np.ones(3, dtype=[('a', 'i8'), ('b', 'i8'), ('c', 'i8')])
4387 exc = raises(TypeError, abs, a)
4388 assert exc.value[0].startswith("ufunc 'absolute' did not contain a loop")
4389 assert (a == a).all()
4390 assert not (a != a).any()
4391 assert (a == b).all()
4392 assert not (a != b).any()
4393 assert a != c
4394 assert not a == c
4395 assert (a != d).all()
4396 assert not (a == d).any()
4397 assert a != e
4398 assert not a == e
4399 assert np.greater(a, a) is NotImplemented
4400 assert np.less_equal(a, a) is NotImplemented
4401
4402 def test_create_from_memory(self):
4403 import numpy as np
4404 import sys
4405 builtins = getattr(__builtins__, '__dict__', __builtins__)
4406 _buffer = builtins.get('buffer')
4407 dat = np.array(_buffer('1.0'))
4408 assert (dat == [49, 46, 48]).all()
4409 assert dat.dtype == np.dtype('uint8')
4410
4411
4412 class AppTestPyPy(BaseNumpyAppTest):
4413 def setup_class(cls):
4414 if option.runappdirect and '__pypy__' not in sys.builtin_module_names:
4415 py.test.skip("pypy only test")
4416 BaseNumpyAppTest.setup_class.im_func(cls)
4417
4418 def test_init_2(self):
4419 # this test is pypy only since in numpy it becomes an object dtype
4420 import numpy
4421 raises(ValueError, numpy.array, [[1], 2])
4422 raises(ValueError, numpy.array, [[1, 2], [3]])
4423 raises(ValueError, numpy.array, [[[1, 2], [3, 4], 5]])
4424 raises(ValueError, numpy.array, [[[1, 2], [3, 4], [5]]])
4425 a = numpy.array([[1, 2], [4, 5]])
4426 assert a[0, 1] == 2
4427 assert a[0][1] == 2
4428 a = numpy.array(([[[1, 2], [3, 4], [5, 6]]]))
4429 assert (a[0, 1] == [3, 4]).all()
4430
4431 def test_from_shape_and_storage(self):
4432 from numpy import array, ndarray
4433 x = array([1, 2, 3, 4])
4434 addr, _ = x.__array_interface__['data']
4435 sz = x.size * x.dtype.itemsize
4436 y = ndarray._from_shape_and_storage([2, 2], addr, x.dtype, sz)
4437 assert y[0, 1] == 2
4438 y[0, 1] = 42
4439 assert x[1] == 42
4440 class C(ndarray):
4441 pass
4442 z = ndarray._from_shape_and_storage([4, 1], addr, x.dtype, sz, C)
4443 assert isinstance(z, C)
4444 assert z.shape == (4, 1)
4445 assert z[1, 0] == 42
4446
4447 def test___pypy_data__(self):
4448 from numpy import array
4449 x = array([1, 2, 3, 4])
4450 x.__pypy_data__ is None
4451 obj = object()
4452 x.__pypy_data__ = obj
4453 assert x.__pypy_data__ is obj
4454 del x.__pypy_data__
4455 assert x.__pypy_data__ is None
4456
4457 def test_from_shape_and_storage_strides(self):
4458 from numpy import ndarray, array
4459 base = array([1, 2, 3, 4], dtype=int)
4460 addr, _ = base.__array_interface__['data']
4461 sz = base.size * base.dtype.itemsize
4462 a = ndarray._from_shape_and_storage((4,), addr, int, sz)
4463 assert a[1] == 2
4464 a = ndarray._from_shape_and_storage((4,), addr, int, sz,
4465 strides=[base.strides[0]])
4466 assert a[1] == 2
4467 a = ndarray._from_shape_and_storage((2,), addr, int, sz,
4468 strides=[2 * base.strides[0]])
4469 assert a[1] == 3