Debian Codegraph @

pypy/module/micronumpy/test/test_dtypes.py

raw symbols SCIP
1 from pypy.conftest import option
2 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
3 from pypy.interpreter.gateway import interp2app
4
5 class BaseAppTestDtypes(BaseNumpyAppTest):
6 def setup_class(cls):
7 BaseNumpyAppTest.setup_class.im_func(cls)
8 if option.runappdirect:
9 import platform
10 bits, linkage = platform.architecture()
11 ptr_size = int(bits[:-3]) // 8
12 else:
13 from rpython.rtyper.lltypesystem import rffi
14 ptr_size = rffi.sizeof(rffi.CCHARP)
15 cls.w_ptr_size = cls.space.wrap(ptr_size)
16
17 class AppTestDtypes(BaseAppTestDtypes):
18 spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii"])
19
20 def test_typeinfo(self):
21 import numpy as np
22 try:
23 from numpy.core.multiarray import typeinfo
24 except ImportError:
25 # running on dummy module
26 from numpy import typeinfo
27 assert typeinfo['Number'] == np.number
28 assert typeinfo['LONGLONG'] == ('q', 9, 64, 8, 9223372036854775807L,
29 -9223372036854775808L, np.longlong)
30 assert typeinfo['VOID'] == ('V', 20, 0, 1, np.void)
31 assert typeinfo['BOOL'] == ('?', 0, 8, 1, 1, 0, np.bool_)
32 assert typeinfo['CFLOAT'] == ('F', 14, 64, 8, np.complex64)
33 assert typeinfo['CDOUBLE'] == ('D', 15, 128, 16, np.complex128)
34 assert typeinfo['HALF'] == ('e', 23, 16, 2, np.float16)
35 assert typeinfo['INTP'] == ('p', np.dtype('int').num,
36 self.ptr_size*8, self.ptr_size,
37 2**(self.ptr_size*8 - 1) - 1,
38 -2**(self.ptr_size*8 - 1),
39 np.dtype('int').type)
40
41 def test_dtype_basic(self):
42 from numpy import dtype
43 import sys
44
45 d = dtype('?')
46 assert d.num == 0
47 assert d.kind == 'b'
48 assert dtype(d) is d
49 assert dtype('bool') is d
50 assert dtype('bool_') is d
51 assert dtype('|b1') is d
52 b = '>' if sys.byteorder == 'little' else '<'
53 assert dtype(b + 'i4') is not dtype(b + 'i4')
54 assert repr(type(d)) == "<type 'numpy.dtype'>"
55 exc = raises(ValueError, "d.names = []")
56 assert exc.value[0] == "there are no fields defined"
57 exc = raises(ValueError, "d.names = None")
58 assert exc.value[0] == "there are no fields defined"
59
60 assert dtype('int8').num == 1
61 assert dtype(u'int8').num == 1
62 assert dtype('int8').name == 'int8'
63 assert dtype('void').name == 'void'
64 assert dtype(int).fields is None
65 assert dtype(int).names is None
66 assert dtype(int).hasobject is False
67 assert dtype(int).subdtype is None
68 assert dtype(str) is dtype('string') is dtype('string_')
69 assert dtype(unicode) is dtype('unicode') is dtype('unicode_')
70
71 assert dtype(None) is dtype(float)
72
73 for d in [dtype('<c8'), dtype('>i4'), dtype('bool')]:
74 for key in ["d[2]", "d['z']", "d[None]"]:
75 exc = raises(KeyError, key)
76 assert exc.value[0] == "There are no fields in dtype %s." % str(d)
77
78 exc = raises(TypeError, dtype, (1, 2))
79 assert exc.value[0] == 'data type not understood'
80 exc = raises(TypeError, dtype, lambda: 42)
81 assert exc.value[0] == 'data type not understood'
82 exc = raises(TypeError, dtype, 'oooo')
83 assert exc.value[0] == 'data type "oooo" not understood'
84 raises(KeyError, 'dtype(int)["asdasd"]')
85
86 def test_dtype_from_tuple(self):
87 import numpy as np
88 d = np.dtype((np.int64, 0))
89 assert d == np.dtype(('i8', 0,))
90 assert d.shape == (0,)
91 d = np.dtype((np.int64, 1))
92 assert d == np.dtype('i8')
93 assert d.shape == ()
94 d = np.dtype((np.int64, 1,))
95 assert d.shape == ()
96 assert d == np.dtype('i8')
97 assert d.shape == ()
98 d = np.dtype((np.int64, 4))
99 assert d == np.dtype(('i8', (4,)))
100 assert d.shape == (4,)
101 d = np.dtype((np.string_, 4))
102 assert d == np.dtype('S4')
103 assert d.shape == ()
104 d = np.dtype(('S', 4))
105 assert d == np.dtype('S4')
106 assert d.shape == ()
107
108 def test_dtype_eq(self):
109 from numpy import dtype
110
111 assert dtype("int8") == "int8"
112 assert "int8" == dtype("int8")
113 raises(TypeError, lambda: dtype("int8") == 3)
114 assert dtype(bool) == bool
115 assert dtype('f8') != dtype(('f8', (1,)))
116
117 def test_dtype_cmp(self):
118 from numpy import dtype
119 assert dtype('int8') <= dtype('int8')
120 assert not (dtype('int8') < dtype('int8'))
121
122 def test_dtype_aliases(self):
123 from numpy import dtype
124 assert dtype('bool8') is dtype('bool')
125 assert dtype('byte') is dtype('int8')
126 assert dtype('ubyte') is dtype('uint8')
127 assert dtype('short') is dtype('int16')
128 assert dtype('ushort') is dtype('uint16')
129 assert dtype('longlong') is dtype('q')
130 assert dtype('ulonglong') is dtype('Q')
131 assert dtype("float") is dtype(float)
132 assert dtype('single') is dtype('float32')
133 assert dtype('double') is dtype('float64')
134 assert dtype('longfloat').num in (12, 13)
135 assert dtype('longdouble').num in (12, 13)
136 assert dtype('csingle') is dtype('complex64')
137 assert dtype('cfloat') is dtype('complex128')
138 assert dtype('cdouble') is dtype('complex128')
139 assert dtype('clongfloat').num in (15, 16)
140 assert dtype('clongdouble').num in (15, 16)
141
142 def test_dtype_with_types(self):
143 from numpy import dtype
144
145 assert dtype(bool).num == 0
146 if self.ptr_size == 4:
147 assert dtype('int32').num == 7
148 assert dtype('uint32').num == 8
149 assert dtype('int64').num == 9
150 assert dtype('uint64').num == 10
151 assert dtype('intp').num == 5
152 assert dtype('uintp').num == 6
153 else:
154 assert dtype('int32').num == 5
155 assert dtype('uint32').num == 6
156 assert dtype('int64').num == 7
157 assert dtype('uint64').num == 8
158 assert dtype('intp').num == 7
159 assert dtype('uintp').num == 8
160 assert dtype(int).num == 7
161 assert dtype('int').num == 7
162 assert dtype('uint').num == 8
163 assert dtype('intp').num == 7
164 assert dtype('uintp').num == 8
165 assert dtype(long).num == 9
166 assert dtype(float).num == 12
167 assert dtype('float').num == 12
168 assert dtype('complex').num == 15
169
170 def test_array_dtype_attr(self):
171 from numpy import array, dtype
172
173 a = array(list(range(5)), int)
174 assert a.dtype is dtype(int)
175
176 def test_isbuiltin(self):
177 import numpy as np
178 import sys
179 assert np.dtype('?').isbuiltin == 1
180 assert np.dtype(int).newbyteorder().isbuiltin == 0
181 assert np.dtype(np.dtype(int)).isbuiltin == 1
182 assert np.dtype('=i4').isbuiltin == 1
183 b = '>' if sys.byteorder == 'little' else '<'
184 assert np.dtype(b + 'i4').isbuiltin == 0
185 assert np.dtype(b + 'i4').newbyteorder().isbuiltin == 0
186 b = '<' if sys.byteorder == 'little' else '>'
187 assert np.dtype(b + 'i4').isbuiltin == 1
188 assert np.dtype(b + 'i4').newbyteorder().isbuiltin == 0
189 assert np.dtype((int, 2)).isbuiltin == 0
190 assert np.dtype([('', int), ('', float)]).isbuiltin == 0
191 assert np.dtype('void').isbuiltin == 1
192 assert np.dtype(str).isbuiltin == 1
193 assert np.dtype('S0').isbuiltin == 1
194 assert np.dtype('S5').isbuiltin == 0
195
196 def test_repr_str(self):
197 from numpy import dtype
198 b = dtype(int).newbyteorder().newbyteorder().byteorder
199 assert '.dtype' in repr(dtype)
200 d = dtype('?')
201 assert repr(d) == "dtype('bool')"
202 assert str(d) == "bool"
203 d = dtype([('', '<f8')])
204 assert repr(d) == "dtype([('f0', '<f8')])"
205 assert str(d) == "[('f0', '<f8')]"
206 d = dtype('S5')
207 assert repr(d) == "dtype('S5')"
208 assert str(d) == "|S5"
209 d = dtype('a5')
210 assert repr(d) == "dtype('S5')"
211 assert str(d) == "|S5"
212 d = dtype('U5')
213 assert repr(d) == "dtype('%sU5')" % b
214 assert str(d) == "%sU5" % b
215 d = dtype(('<f8', 2))
216 assert repr(d) == "dtype(('<f8', (2,)))"
217 assert str(d) == "('<f8', (2,))"
218 d = dtype('V16')
219 assert repr(d) == "dtype('V16')"
220 assert str(d) == "|V16"
221
222 def test_bool_array(self):
223 from numpy import array, False_, True_
224
225 a = array([0, 1, 2, 2.5], dtype='?')
226 assert a[0] is False_
227 for i in range(1, 4):
228 assert a[i] is True_
229
230 def test_copy_array_with_dtype(self):
231 from numpy import array, longlong, False_
232
233 a = array([0, 1, 2, 3], dtype=int)
234 # int on 64-bit, long in 32-bit
235 assert isinstance(a[0], longlong)
236 b = a.copy()
237 assert isinstance(b[0], longlong)
238
239 a = array([0, 1, 2, 3], dtype=bool)
240 assert a[0] is False_
241 b = a.copy()
242 assert b[0] is False_
243
244 def test_zeros_bool(self):
245 from numpy import zeros, False_
246
247 a = zeros(10, dtype=bool)
248 for i in range(10):
249 assert a[i] is False_
250
251 def test_ones_bool(self):
252 from numpy import ones, True_
253
254 a = ones(10, dtype=bool)
255 for i in range(10):
256 assert a[i] is True_
257
258 def test_zeros_long(self):
259 from numpy import zeros, longlong
260 a = zeros(10, dtype=int)
261 for i in range(10):
262 assert isinstance(a[i], longlong)
263 assert a[1] == 0
264
265 def test_ones_long(self):
266 from numpy import ones, longlong
267 a = ones(10, dtype=int)
268 for i in range(10):
269 assert isinstance(a[i], longlong)
270 assert a[1] == 1
271
272 def test_overflow(self):
273 from numpy import array, dtype
274 assert array([128], 'b')[0] == -128
275 assert array([256], 'B')[0] == 0
276 assert array([32768], 'h')[0] == -32768
277 assert array([65536], 'H')[0] == 0
278 a = array([65520], dtype='float64')
279 b = array(a, dtype='float16')
280 assert b == float('inf')
281 if dtype('l').itemsize == 4: # 32-bit
282 raises(OverflowError, "array([2**32/2], 'i')")
283 raises(OverflowError, "array([2**32], 'I')")
284 raises(OverflowError, "array([2**64/2], 'q')")
285 raises(OverflowError, "array([2**64], 'Q')")
286
287 def test_bool_binop_types(self):
288 from numpy import array, dtype
289 types = [
290 '?', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'f', 'd',
291 'e'
292 ]
293 if array([0], dtype='longdouble').itemsize > 8:
294 types += ['g', 'G']
295 a = array([True], '?')
296 for t in types:
297 assert (a + array([0], t)).dtype == dtype(t)
298
299 def test_binop_types(self):
300 from numpy import array, dtype
301 tests = [('b','B','h'), ('b','h','h'), ('b','H','i'), ('b','i','i'),
302 ('b','l','l'), ('b','q','q'), ('b','Q','d'), ('B','h','h'),
303 ('B','H','H'), ('B','i','i'), ('B','I','I'), ('B','l','l'),
304 ('B','L','L'), ('B','q','q'), ('B','Q','Q'), ('h','H','i'),
305 ('h','i','i'), ('h','l','l'), ('h','q','q'), ('h','Q','d'),
306 ('H','i','i'), ('H','I','I'), ('H','l','l'), ('H','L','L'),
307 ('H','q','q'), ('H','Q','Q'), ('i','l','l'), ('i','q','q'),
308 ('i','Q','d'), ('I','L','L'), ('I','q','q'), ('I','Q','Q'),
309 ('q','Q','d'), ('b','f','f'), ('B','f','f'), ('h','f','f'),
310 ('H','f','f'), ('i','f','d'), ('I','f','d'), ('l','f','d'),
311 ('L','f','d'), ('q','f','d'), ('Q','f','d'), ('q','d','d')]
312 if dtype('i').itemsize == dtype('l').itemsize: # 32-bit
313 tests.extend([('b','I','q'), ('b','L','q'), ('h','I','q'),
314 ('h','L','q'), ('i','I','q'), ('i','L','q')])
315 else:
316 tests.extend([('b','I','l'), ('b','L','d'), ('h','I','l'),
317 ('h','L','d'), ('i','I','l'), ('i','L','d')])
318 for d1, d2, dout in tests:
319 # make a failed test print helpful info
320 d3 = (array([1], d1) + array([1], d2)).dtype
321 assert (d1, d2) == (d1, d2) and d3 == dtype(dout)
322
323 def test_add(self):
324 import numpy as np
325 for dtype in ["int8", "int16", "I"]:
326 a = np.array(list(range(5)), dtype=dtype)
327 b = a + a
328 assert b.dtype is np.dtype(dtype)
329 for i in range(5):
330 assert b[i] == i * 2
331
332 def test_len(self):
333 import numpy as np
334 d = np.dtype('int32')
335 assert len(d) == 0
336 d = np.dtype([('x', 'i4'), ('y', 'i4')])
337 assert len(d) == 2
338
339 def test_shape(self):
340 from numpy import dtype
341 assert dtype(int).shape == ()
342
343 def test_cant_subclass(self):
344 from numpy import dtype
345 # You can't subclass dtype
346 raises(TypeError, type, "Foo", (dtype,), {})
347
348 def test_can_subclass(self):
349 import numpy as np
350 import sys, pickle
351 class xyz(np.void):
352 pass
353 assert np.dtype(xyz).name == 'xyz'
354 # another obscure API, used in numpy record.py
355 a = np.dtype((xyz, [('x', 'int32'), ('y', 'float32')]))
356 if sys.byteorder == 'big':
357 assert "[('x', '>i4'), ('y', '>f4')]" in repr(a)
358 else:
359 assert "[('x', '<i4'), ('y', '<f4')]" in repr(a)
360 assert 'xyz' in repr(a)
361 data = [(1, 'a'), (2, 'bbb')]
362 b = np.dtype((xyz, [('a', int), ('b', object)]))
363 if '__pypy__' in sys.builtin_module_names:
364 raises(NotImplementedError, np.array, data, dtype=b)
365 else:
366 arr = np.array(data, dtype=b)
367 assert arr[0][0] == 1
368 assert arr[0][1] == 'a'
369 # NOTE if micronumpy is completed, we might extend this test to check both
370 # "<i4" and ">i4"
371 E = '<' if sys.byteorder == 'little' else '>'
372 b = np.dtype((xyz, [("col1", E+"i4"), ("col2", E+"i4"), ("col3", E+"i4")]))
373 data = [(1, 2,3), (4, 5, 6)]
374 a = np.array(data, dtype=b)
375 x = pickle.loads(pickle.dumps(a))
376 assert (x == a).all()
377 assert x.dtype == a.dtype
378
379 def test_index(self):
380 import numpy as np
381 for dtype in [np.int8, np.int16, np.int32, np.int64]:
382 a = np.array(range(10), dtype=dtype)
383 b = np.array([0] * 10, dtype=dtype)
384 for idx in b:
385 a[idx] += 1
386
387 def test_hash(self):
388 import numpy
389 for tp, value in [
390 (numpy.int8, 4),
391 (numpy.int16, 5),
392 (numpy.uint32, 7),
393 (numpy.int64, 3),
394 (numpy.float16, 10.),
395 (numpy.float32, 2.0),
396 (numpy.float64, 4.32),
397 (numpy.longdouble, 4.32),
398 ]:
399 assert hash(tp(value)) == hash(value)
400
401 d1 = numpy.dtype([('f0', 'i4'), ('f1', 'i4')])
402 d2 = numpy.dtype([('f0', 'i4'), ('f1', 'i4')])
403 d3 = numpy.dtype([('f0', 'i4'), ('f2', 'i4')])
404 d4 = numpy.dtype([('f0', 'i4'), ('f1', d1)])
405 d5 = numpy.dtype([('f0', 'i4'), ('f1', d2)])
406 d6 = numpy.dtype([('f0', 'i4'), ('f1', d3)])
407 import sys
408 assert hash(d1) == hash(d2)
409 assert hash(d1) != hash(d3)
410 assert hash(d4) == hash(d5)
411 assert hash(d4) != hash(d6)
412
413 def test_record_hash(self):
414 from numpy import dtype
415 # make sure the fields hash return different value
416 # for different order of field in a structure
417
418 # swap names
419 t1 = dtype([('x', '<f4'), ('y', '<i4')])
420 t2 = dtype([('y', '<f4'), ('x', '<i4')])
421 assert hash(t1) != hash(t2)
422
423 # swap types
424 t3 = dtype([('x', '<f4'), ('y', '<i4')])
425 t4 = dtype([('x', '<i4'), ('y', '<f4')])
426 assert hash(t3) != hash(t4)
427
428 # swap offsets
429 t5 = dtype([('x', '<f4'), ('y', '<i4')])
430 t6 = dtype([('y', '<i4'), ('x', '<f4')])
431 assert hash(t5) != hash(t6)
432
433 def test_pickle(self):
434 import sys
435 import numpy as np
436 from numpy import array, dtype
437 from cPickle import loads, dumps
438 a = array([1,2,3])
439 E = '<' if sys.byteorder == 'little' else '>'
440 if self.ptr_size == 8:
441 assert a.dtype.__reduce__() == (dtype, ('i8', 0, 1), (3, E, None, None, None, -1, -1, 0))
442 else:
443 assert a.dtype.__reduce__() == (dtype, ('i4', 0, 1), (3, E, None, None, None, -1, -1, 0))
444 assert loads(dumps(a.dtype)) == a.dtype
445 assert np.dtype('bool').__reduce__() == (dtype, ('b1', 0, 1), (3, '|', None, None, None, -1, -1, 0))
446 assert np.dtype('|V16').__reduce__() == (dtype, ('V16', 0, 1), (3, '|', None, None, None, 16, 1, 0))
447 assert np.dtype((E+'f8', 2)).__reduce__() == (dtype, ('V16', 0, 1), (3, '|', (dtype('float64'), (2,)), None, None, 16, 8, 0))
448
449 def test_newbyteorder(self):
450 import numpy as np
451 import sys
452 sys_is_le = sys.byteorder == 'little'
453 native_code = sys_is_le and '<' or '>'
454 swapped_code = sys_is_le and '>' or '<'
455 native_dt = np.dtype(native_code+'i2')
456 swapped_dt = np.dtype(swapped_code+'i2')
457 assert native_dt.newbyteorder('S') == swapped_dt
458 assert native_dt.newbyteorder() == swapped_dt
459 assert native_dt == swapped_dt.newbyteorder('S')
460 assert native_dt == swapped_dt.newbyteorder('=')
461 assert native_dt == swapped_dt.newbyteorder('N')
462 assert native_dt == native_dt.newbyteorder('|')
463 assert np.dtype('<i2') == native_dt.newbyteorder('<')
464 assert np.dtype('<i2') == native_dt.newbyteorder('L')
465 assert np.dtype('>i2') == native_dt.newbyteorder('>')
466 assert np.dtype('>i2') == native_dt.newbyteorder('B')
467
468 for t in [np.int_, np.float_]:
469 dt = np.dtype(t)
470 dt1 = dt.newbyteorder().newbyteorder()
471 assert dt.isbuiltin
472 assert not dt1.isbuiltin
473 dt2 = dt.newbyteorder("<")
474 dt3 = dt.newbyteorder(">")
475 assert dt.byteorder != dt1.byteorder
476 assert hash(dt) == hash(dt1)
477 if dt == dt2:
478 assert dt.byteorder != dt2.byteorder
479 assert hash(dt) == hash(dt2)
480 else:
481 assert dt.byteorder != dt3.byteorder
482 assert hash(dt) == hash(dt3)
483
484 exc = raises(ValueError, dt.newbyteorder, 'XX')
485 assert exc.value[0] == 'XX is an unrecognized byteorder'
486
487 for t in [np.int_, np.float_]:
488 dt1 = np.dtype(t)
489 dt2 = dt1.newbyteorder()
490 s1 = np.array(123, dtype=dt1).tostring()
491 s2 = np.array(123, dtype=dt2).byteswap().tostring()
492 assert s1 == s2
493
494 d = np.dtype([('', '<i8')]).newbyteorder()
495 assert d.shape == ()
496 assert d.names == ('f0',)
497 #assert d.fields['f0'] == ('>i8', 0)
498 assert d.subdtype is None
499 #assert d.descr == [('f0', '>i8')]
500 #assert str(d) == "[('f0', '>i8')]"
501 d = np.dtype(('<i8', 2)).newbyteorder()
502 assert d.shape == (2,)
503 assert d.names is None
504 assert d.fields is None
505 assert d.descr == [('', '|V16')]
506 #assert str(d) == "('>i8', (2,))"
507
508 def test_object(self):
509 import numpy as np
510 import sys
511 class O(object):
512 pass
513 for o in [object, O]:
514 assert np.dtype(o).str == '|O'
515 # Issue gh-2798
516 a = np.array(['a'], dtype="O").astype(("O", [("name", "O")]))
517 assert a[0] == 'a'
518 assert a != 'a'
519 assert a['name'].dtype == a.dtype
520
521 class AppTestTypes(BaseAppTestDtypes):
522 def test_abstract_types(self):
523 import numpy
524
525 raises(TypeError, numpy.generic, 0)
526 raises(TypeError, numpy.number, 0)
527 raises(TypeError, numpy.integer, 0)
528 exc = raises(TypeError, numpy.signedinteger, 0)
529 assert 'cannot create' in str(exc.value)
530 assert 'signedinteger' in str(exc.value)
531 exc = raises(TypeError, numpy.unsignedinteger, 0)
532 assert 'cannot create' in str(exc.value)
533 assert 'unsignedinteger' in str(exc.value)
534 raises(TypeError, numpy.floating, 0)
535 raises(TypeError, numpy.inexact, 0)
536
537 # numpy allows abstract types in array creation
538 a_n = numpy.array([4,4], numpy.number)
539 a_f = numpy.array([4,4], numpy.floating)
540 a_c = numpy.array([4,4], numpy.complexfloating)
541 a_i = numpy.array([4,4], numpy.integer)
542 a_s = numpy.array([4,4], numpy.signedinteger)
543 a_u = numpy.array([4,4], numpy.unsignedinteger)
544
545 assert a_n.dtype.num == 12
546 assert a_f.dtype.num == 12
547 assert a_c.dtype.num == 15
548 assert a_i.dtype.num == 7
549 assert a_s.dtype.num == 7
550 assert a_u.dtype.num == 8
551
552 assert a_n.dtype is numpy.dtype('float64')
553 assert a_f.dtype is numpy.dtype('float64')
554 assert a_c.dtype is numpy.dtype('complex128')
555 if self.ptr_size == 4:
556 assert a_i.dtype is numpy.dtype('int32')
557 assert a_s.dtype is numpy.dtype('int32')
558 assert a_u.dtype is numpy.dtype('uint32')
559 else:
560 assert a_i.dtype is numpy.dtype('int64')
561 assert a_s.dtype is numpy.dtype('int64')
562 assert a_u.dtype is numpy.dtype('uint64')
563
564 # too ambitious for now
565 #a = numpy.array('xxxx', numpy.generic)
566 #assert a.dtype is numpy.dtype('|V4')
567
568 def test_new(self):
569 import numpy as np
570 assert np.int_(4) == 4
571 assert np.float_(3.4) == 3.4
572
573 def test_pow(self):
574 from numpy import int_
575 assert int_(4) ** 2 == 16
576
577 def test_bool(self):
578 import numpy
579
580 assert numpy.bool_.mro() == [numpy.bool_, numpy.generic, object]
581 assert numpy.bool_(3) is numpy.True_
582 assert numpy.bool_("") is numpy.False_
583 assert type(numpy.True_) is type(numpy.False_) is numpy.bool_
584
585 class X(numpy.bool_):
586 pass
587
588 assert type(X(True)) is numpy.bool_
589 assert X(True) is numpy.True_
590 assert numpy.bool_("False") is numpy.True_
591
592 def test_int8(self):
593 import numpy
594
595 assert numpy.int8.mro() == [numpy.int8, numpy.signedinteger,
596 numpy.integer, numpy.number,
597 numpy.generic, object]
598
599 a = numpy.array([1, 2, 3], numpy.int8)
600 assert type(a[1]) is numpy.int8
601 assert numpy.dtype("int8").type is numpy.int8
602
603 x = numpy.int8(128)
604 assert x == -128
605 assert x != 128
606 assert type(x) is numpy.int8
607 assert repr(x) == "-128"
608
609 assert type(int(x)) is int
610 assert int(x) == -128
611 assert numpy.int8('50') == numpy.int8(50)
612 raises(ValueError, numpy.int8, '50.2')
613 assert numpy.int8('127') == 127
614 assert numpy.int8('128') == -128
615
616 def test_uint8(self):
617 import numpy
618
619 assert numpy.uint8.mro() == [numpy.uint8, numpy.unsignedinteger,
620 numpy.integer, numpy.number,
621 numpy.generic, object]
622
623 a = numpy.array([1, 2, 3], numpy.uint8)
624 assert type(a[1]) is numpy.uint8
625 assert numpy.dtype("uint8").type is numpy.uint8
626
627 x = numpy.uint8(128)
628 assert x == 128
629 assert x != -128
630 assert type(x) is numpy.uint8
631 assert repr(x) == "128"
632
633 assert type(int(x)) is int
634 assert int(x) == 128
635
636 assert numpy.uint8(255) == 255
637 assert numpy.uint8(256) == 0
638 assert numpy.uint8('255') == 255
639 assert numpy.uint8('256') == 0
640
641 def test_int16(self):
642 import numpy
643
644 x = numpy.int16(3)
645 assert x == 3
646 assert numpy.int16(32767) == 32767
647 assert numpy.int16(32768) == -32768
648 assert numpy.int16('32767') == 32767
649 assert numpy.int16('32768') == -32768
650
651 def test_uint16(self):
652 import numpy
653 assert numpy.uint16(65535) == 65535
654 assert numpy.uint16(65536) == 0
655 assert numpy.uint16('65535') == 65535
656 assert numpy.uint16('65536') == 0
657
658 def test_int32(self):
659 import sys
660 import numpy
661 x = numpy.int32(23)
662 assert x == 23
663 assert numpy.int32(2147483647) == 2147483647
664 assert numpy.int32('2147483647') == 2147483647
665 if sys.maxsize > 2 ** 31 - 1:
666 assert numpy.int32(2147483648) == -2147483648
667 assert numpy.int32('2147483648') == -2147483648
668 else:
669 raises(OverflowError, numpy.int32, 2147483648)
670 raises(OverflowError, numpy.int32, '2147483648')
671 assert numpy.dtype('int32') is numpy.dtype(numpy.int32)
672
673 def test_uint32(self):
674 import sys
675 import numpy
676 assert numpy.uint32(10) == 10
677 if sys.maxsize > 2 ** 31 - 1:
678 assert numpy.uint32(4294967295) == 4294967295
679 assert numpy.uint32(4294967296) == 0
680 assert numpy.uint32('4294967295') == 4294967295
681 assert numpy.uint32('4294967296') == 0
682
683 def test_int_(self):
684 import numpy
685
686 assert numpy.int_ is numpy.dtype(int).type
687 assert numpy.int_.mro() == [numpy.int_, numpy.signedinteger,
688 numpy.integer, numpy.number,
689 numpy.generic, int, object]
690
691 def test_int64(self):
692 import sys
693 import numpy
694 if sys.maxsize == 2 ** 63 -1:
695 assert numpy.int64.mro() == [numpy.int64, numpy.signedinteger,
696 numpy.integer, numpy.number,
697 numpy.generic, int, object]
698 else:
699 assert numpy.int64.mro() == [numpy.int64, numpy.signedinteger,
700 numpy.integer, numpy.number,
701 numpy.generic, object]
702
703 assert numpy.dtype(numpy.int64).type is numpy.int64
704 assert numpy.int64(3) == 3
705
706 assert numpy.int64(9223372036854775807) == 9223372036854775807
707 assert numpy.int64(9223372036854775807) == 9223372036854775807
708 assert numpy.int64(-9223372036854775807) == -9223372036854775807
709 raises(OverflowError, numpy.int64, 9223372036854775808)
710 raises(OverflowError, numpy.int64, 9223372036854775808L)
711
712 def test_uint64(self):
713 import numpy
714 assert numpy.dtype(numpy.uint64).type is numpy.uint64
715 assert numpy.uint64.mro() == [numpy.uint64, numpy.unsignedinteger,
716 numpy.integer, numpy.number,
717 numpy.generic, object]
718 import sys
719 raises(OverflowError, numpy.int64, 9223372036854775808)
720 raises(OverflowError, numpy.int64, 18446744073709551615)
721 raises(OverflowError, numpy.uint64, 18446744073709551616)
722 assert numpy.uint64((2<<63) - 1) == (2<<63) - 1
723
724 def test_float16(self):
725 import numpy
726 assert numpy.float16.mro() == [numpy.float16, numpy.floating,
727 numpy.inexact, numpy.number,
728 numpy.generic, object]
729
730 assert numpy.float16(12) == numpy.float64(12)
731 assert numpy.float16('23.4') == numpy.float16(23.4)
732 raises(ValueError, numpy.float16, '23.2df')
733
734
735 def test_float32(self):
736 import numpy
737 assert numpy.float32.mro() == [numpy.float32, numpy.floating,
738 numpy.inexact, numpy.number,
739 numpy.generic, object]
740
741 assert numpy.float32(12) == numpy.float64(12)
742 assert numpy.float32('23.4') == numpy.float32(23.4)
743 raises(ValueError, numpy.float32, '23.2df')
744
745 def test_float64(self):
746 import numpy
747 assert numpy.float64.mro() == [numpy.float64, numpy.floating,
748 numpy.inexact, numpy.number,
749 numpy.generic, float, object]
750
751 a = numpy.array([1, 2, 3], numpy.float64)
752 assert type(a[1]) is numpy.float64
753 assert numpy.dtype(float).type is numpy.float64
754
755 assert "{:3f}".format(numpy.float64(3)) == "3.000000"
756
757 assert numpy.float64(2.0) == 2.0
758 assert numpy.float64('23.4') == numpy.float64(23.4)
759 raises(ValueError, numpy.float64, '23.2df')
760
761 def test_float_None(self):
762 import numpy
763 from math import isnan
764 assert isnan(numpy.float32(None))
765 assert isnan(numpy.float64(None))
766 assert isnan(numpy.longdouble(None))
767
768 def test_longfloat(self):
769 import numpy
770 # it can be float96 or float128
771 if numpy.longfloat != numpy.float64:
772 assert numpy.longfloat.mro()[1:] == [numpy.floating,
773 numpy.inexact, numpy.number,
774 numpy.generic, object]
775 a = numpy.array([1, 2, 3], numpy.longdouble)
776 assert type(a[1]) is numpy.longdouble
777 assert numpy.float64(12) == numpy.longdouble(12)
778 assert numpy.float64(12) == numpy.longfloat(12)
779 raises(ValueError, numpy.longfloat, '23.2df')
780
781 def test_complex_floating(self):
782 import numpy
783 assert numpy.complexfloating.__mro__ == (numpy.complexfloating,
784 numpy.inexact, numpy.number, numpy.generic, object)
785
786 def test_complex_format(self):
787 import sys
788 import numpy
789
790 for complex_ in (numpy.complex128, numpy.complex64,):
791 for real, imag, should in [
792 (1, 2, '(1+2j)'),
793 (0, 1, '1j'),
794 (1, 0, '(1+0j)'),
795 (-1, -2, '(-1-2j)'),
796 (0.5, -0.75, '(0.5-0.75j)'),
797 #xxx
798 #(numpy.inf, numpy.inf, '(inf+inf*j)'),
799 ]:
800
801 c = complex_(complex(real, imag))
802 assert c == complex(real, imag)
803 assert c.real == real
804 assert c.imag == imag
805 assert repr(c) == should
806
807 real, imag, should = (1e100, 3e66, '(1e+100+3e+66j)')
808 c128 = numpy.complex128(complex(real, imag))
809 assert type(c128.real) is type(c128.imag) is numpy.float64
810 assert c128.real == real
811 assert c128.imag == imag
812 assert repr(c128) == should
813
814 c64 = numpy.complex64(complex(real, imag))
815 assert repr(c64.real) == 'inf'
816 assert type(c64.real) is type(c64.imag) is numpy.float32
817 assert repr(c64.imag).startswith('inf')
818 assert repr(c64) in ('(inf+inf*j)', '(inf+infj)')
819
820
821 assert numpy.complex128(1.2) == numpy.complex128(complex(1.2, 0))
822 assert numpy.complex64(1.2) == numpy.complex64(complex(1.2, 0))
823 raises((ValueError, TypeError), numpy.array, [3+4j], dtype=float)
824 if sys.version_info >= (2, 7):
825 assert "{:g}".format(numpy.complex_(0.5+1.5j)) == '{:g}'.format(0.5+1.5j)
826
827 def test_complex(self):
828 import numpy
829
830 assert numpy.complex_ is numpy.complex128
831 assert numpy.csingle is numpy.complex64
832 assert numpy.cfloat is numpy.complex128
833 assert numpy.complex64.__mro__ == (numpy.complex64,
834 numpy.complexfloating, numpy.inexact, numpy.number, numpy.generic,
835 object)
836 assert numpy.complex128.__mro__ == (numpy.complex128,
837 numpy.complexfloating, numpy.inexact, numpy.number, numpy.generic,
838 complex, object)
839
840 assert numpy.dtype(complex).type is numpy.complex128
841 assert numpy.dtype("complex").type is numpy.complex128
842 d = numpy.dtype('complex64')
843 assert d.kind == 'c'
844 assert d.num == 14
845 assert d.char == 'F'
846
847 def test_subclass_type(self):
848 import numpy
849
850 class X(numpy.float64):
851 def m(self):
852 return self + 2
853
854 b = X(10)
855 assert type(b) is X
856 assert b.m() == 12
857 b = X(numpy.array([1, 2, 3]))
858 assert type(b) is numpy.ndarray
859 assert b.dtype.type is numpy.float64
860
861 def test_long_as_index(self):
862 from numpy import int_, float64
863 assert (1, 2, 3)[int_(1)] == 2
864 raises(TypeError, lambda: (1, 2, 3)[float64(1)])
865
866 def test_int(self):
867 from numpy import int32, int64, int_
868 import sys
869 assert issubclass(int_, int)
870 if sys.maxsize == (1<<31) - 1:
871 assert issubclass(int32, int)
872 assert int_ is int32
873 else:
874 assert issubclass(int64, int)
875 assert int_ is int64
876
877 def test_operators(self):
878 from operator import truediv
879 from numpy import float64, int_, True_, False_
880 assert 5 / int_(2) == int_(2)
881 assert truediv(int_(3), int_(2)) == float64(1.5)
882 assert truediv(3, int_(2)) == float64(1.5)
883 assert int_(8) % int_(3) == int_(2)
884 assert 8 % int_(3) == int_(2)
885 assert divmod(int_(8), int_(3)) == (int_(2), int_(2))
886 assert divmod(8, int_(3)) == (int_(2), int_(2))
887 assert 2 ** int_(3) == int_(8)
888 assert int_(3) << int_(2) == int_(12)
889 assert 3 << int_(2) == int_(12)
890 assert int_(8) >> int_(2) == int_(2)
891 assert 8 >> int_(2) == int_(2)
892 assert int_(3) & int_(1) == int_(1)
893 assert 2 & int_(3) == int_(2)
894 assert int_(2) | int_(1) == int_(3)
895 assert 2 | int_(1) == int_(3)
896 assert int_(3) ^ int_(5) == int_(6)
897 assert True_ ^ False_ is True_
898 assert 5 ^ int_(3) == int_(6)
899 assert +int_(3) == int_(3)
900 assert ~int_(3) == int_(-4)
901 raises(TypeError, lambda: float64(3) & 1)
902
903 def test_alternate_constructs(self):
904 import numpy as np
905 from numpy import dtype
906 nnp = self.non_native_prefix
907 byteorder = self.native_prefix
908 assert dtype('i8') == dtype(byteorder + 'i8') == dtype('=i8') == dtype(long)
909 assert dtype(nnp + 'i8') != dtype('i8')
910 assert dtype(nnp + 'i8').byteorder == nnp
911 assert dtype('=i8').byteorder == '='
912 assert dtype(byteorder + 'i8').byteorder == '='
913 assert dtype(str).byteorder == '|'
914 assert dtype('S5').byteorder == '|'
915 assert dtype('>S5').byteorder == '|'
916 assert dtype('<S5').byteorder == '|'
917 assert dtype('<S5').newbyteorder('=').byteorder == '|'
918 assert dtype('void').byteorder == '|'
919 assert dtype((int, 2)).byteorder == '|'
920 assert dtype(np.generic).str == '|V0'
921 d = dtype(np.character)
922 assert d.num == 18
923 assert d.char == 'S'
924 assert d.kind == 'S'
925 assert d.str == '|S0'
926
927 def test_dtype_str(self):
928 from numpy import dtype
929 import sys
930 byteorder = self.native_prefix
931 assert dtype('i8').str == byteorder + 'i8'
932 assert dtype('<i8').str == '<i8'
933 assert dtype('>i8').str == '>i8'
934 assert dtype('int8').str == '|i1'
935 assert dtype('float').str == byteorder + 'f8'
936 assert dtype('f').str == byteorder + 'f4'
937 assert dtype('=f').str == byteorder + 'f4'
938 assert dtype('|f').str == byteorder + 'f4'
939 assert dtype('>f').str == '>f4'
940 assert dtype('<f').str == '<f4'
941 assert dtype('d').str == byteorder + 'f8'
942 assert dtype('=d').str == byteorder + 'f8'
943 assert dtype('|d').str == byteorder + 'f8'
944 assert dtype('>d').str == '>f8'
945 assert dtype('<d').str == '<f8'
946 # strange
947 assert dtype('string').str == '|S0'
948 assert dtype('unicode').str == byteorder + 'U0'
949 assert dtype(('string', 7)).str == '|S7'
950 assert dtype('=S5').str == '|S5'
951 assert dtype(('unicode', 7)).str == \
952 ('<' if sys.byteorder == 'little' else '>')+'U7'
953 assert dtype([('', 'f8')]).str == "|V8"
954 assert dtype(('f8', 2)).str == "|V16"
955
956 def test_intp(self):
957 from numpy import dtype
958 assert dtype('p') is dtype('intp')
959 assert dtype('P') is dtype('uintp')
960 assert dtype('p').kind == 'i'
961 assert dtype('P').kind == 'u'
962 if self.ptr_size == 4:
963 assert dtype('p').num == 5
964 assert dtype('P').num == 6
965 assert dtype('p').char == 'i'
966 assert dtype('P').char == 'I'
967 assert dtype('p').name == 'int32'
968 assert dtype('P').name == 'uint32'
969 else:
970 assert dtype('p').num == 7
971 assert dtype('P').num == 8
972 assert dtype('p').char == 'l'
973 assert dtype('P').char == 'L'
974 assert dtype('p').name == 'int64'
975 assert dtype('P').name == 'uint64'
976
977 def test_alignment(self):
978 from numpy import dtype
979 assert dtype('i4').alignment == 4
980
981 def test_isnative(self):
982 from numpy import dtype
983 import sys
984 assert dtype('i4').isnative == True
985 if sys.byteorder == 'big':
986 assert dtype('<i8').isnative == False
987 else:
988 assert dtype('>i8').isnative == False
989
990 def test_any_all_nonzero(self):
991 import numpy
992 x = numpy.bool_(True)
993 assert x.any() is numpy.True_
994 assert x.all() is numpy.True_
995 assert x.__nonzero__() is True
996 x = numpy.bool_(False)
997 assert x.any() is numpy.False_
998 assert x.all() is numpy.False_
999 assert x.__nonzero__() is False
1000 x = numpy.float64(0)
1001 assert x.any() is numpy.False_
1002 assert x.all() is numpy.False_
1003 assert x.__nonzero__() is False
1004 x = numpy.complex128(0)
1005 assert x.any() is numpy.False_
1006 assert x.all() is numpy.False_
1007 assert x.__nonzero__() is False
1008 x = numpy.complex128(0+1j)
1009 assert x.any() is numpy.True_
1010 assert x.all() is numpy.True_
1011 assert x.__nonzero__() is True
1012
1013 def test_ravel(self):
1014 from numpy import float64, int8, array
1015 x = float64(42.5).ravel()
1016 assert x.dtype == float64
1017 assert (x == array([42.5])).all()
1018 #
1019 x = int8(42).ravel()
1020 assert x.dtype == int8
1021 assert (x == array(42)).all()
1022
1023 def test_descr(self):
1024 import numpy as np
1025 assert np.dtype('<i8').descr == [('', '<i8')]
1026 assert np.dtype('|S4').descr == [('', '|S4')]
1027 assert np.dtype(('<i8', (5,))).descr == [('', '|V40')]
1028 d = [('test', '<i8'), ('blah', '<i2', (2, 3))]
1029 assert np.dtype(d).descr == d
1030 a = [('x', '<i8'), ('y', '<f8')]
1031 b = [('x', '<i4'), ('y', a)]
1032 assert np.dtype(b).descr == b
1033 assert np.dtype(('<f8', 2)).descr == [('', '|V16')]
1034
1035 class AppTestStrUnicodeDtypes(BaseNumpyAppTest):
1036 def test_mro(self):
1037 from numpy import str_, unicode_, character, flexible, generic
1038 import sys
1039 if '__pypy__' in sys.builtin_module_names:
1040 assert str_.mro() == [str_, character, flexible, generic,
1041 str, object]
1042 assert unicode_.mro() == [unicode_, character, flexible, generic,
1043 unicode, object]
1044 else:
1045 assert str_.mro() == [str_, str, character, flexible,
1046 generic, object]
1047 assert unicode_.mro() == [unicode_, unicode, character,
1048 flexible, generic, object]
1049
1050 def test_str_dtype(self):
1051 from numpy import dtype, str_
1052
1053 raises(TypeError, "dtype('Sx')")
1054 for t in ['S8', '|S8', '=S8']:
1055 d = dtype(t)
1056 assert d.itemsize == 8
1057 assert dtype(str) == dtype('S')
1058 assert d.kind == 'S'
1059 assert d.type is str_
1060 assert d.name == "string64"
1061 assert d.num == 18
1062 for i in [1, 2, 3]:
1063 raises(TypeError, dtype, 'c%d' % i)
1064
1065 def test_unicode_dtype(self):
1066 from numpy import dtype, unicode_
1067
1068 raises(TypeError, "dtype('Ux')")
1069 d = dtype('U8')
1070 assert d.itemsize == 8 * 4
1071 assert dtype(str) == dtype('U')
1072 assert d.kind == 'U'
1073 assert d.type is unicode_
1074 assert d.name == "unicode256"
1075 assert d.num == 19
1076
1077 def test_character_dtype(self):
1078 import numpy as np
1079 from numpy import array, character
1080 x = array([["A", "B"], ["C", "D"]], character)
1081 assert (x == [["A", "B"], ["C", "D"]]).all()
1082 d = np.dtype('c')
1083 assert d.num == 18
1084 assert d.char == 'c'
1085 assert d.kind == 'S'
1086 assert d.str == '|S1'
1087 assert repr(d) == "dtype('S1')"
1088
1089 class AppTestRecordDtypes(BaseNumpyAppTest):
1090 spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii"])
1091 def setup_class(cls):
1092 BaseNumpyAppTest.setup_class.im_func(cls)
1093 if option.runappdirect:
1094 cls.w_test_for_core_internal = cls.space.wrap(True)
1095 else:
1096 cls.w_test_for_core_internal = cls.space.wrap(False)
1097
1098 def test_create(self):
1099 from numpy import dtype, void
1100
1101 d = dtype([('x', 'i4'), ('y', 'i1')], align=True)
1102 assert d.itemsize == 8
1103 raises(ValueError, "dtype([('x', int), ('x', float)])")
1104 d = dtype([("x", "<i4"), ("y", "<f4"), ("z", "<u2"), ("v", "<f8")])
1105 assert d.fields['x'] == (dtype('<i4'), 0)
1106 assert d.fields['v'] == (dtype('<f8'), 10)
1107 assert d['x'] == dtype('<i4')
1108 assert d.name == "void144"
1109 assert d.num == 20
1110 assert d.itemsize == 18
1111 assert d.kind == 'V'
1112 assert d.base == d
1113 assert d.type is void
1114 assert d.char == 'V'
1115 exc = raises(ValueError, "d.names = None")
1116 assert exc.value[0] == 'must replace all names at once with a sequence of length 4'
1117 exc = raises(ValueError, "d.names = (a for a in 'xyzv')")
1118 assert exc.value[0] == 'must replace all names at once with a sequence of length 4'
1119 exc = raises(ValueError, "d.names = ('a', 'b', 'c', 4)")
1120 assert exc.value[0] == 'item #3 of names is of type int and not string'
1121 exc = raises(ValueError, "d.names = ('a', 'b', 'c', u'd')")
1122 assert exc.value[0] == 'item #3 of names is of type unicode and not string'
1123 assert d.names == ("x", "y", "z", "v")
1124 d.names = ('x', '', 'v', 'z')
1125 assert d.names == ('x', '', 'v', 'z')
1126 assert d.fields['v'] == (dtype('<u2'), 8)
1127 assert d.fields['z'] == (dtype('<f8'), 10)
1128 assert [a[0] for a in d.descr] == ['x', '', 'v', 'z']
1129 exc = raises(ValueError, "d.names = ('a', 'b', 'c')")
1130 assert exc.value[0] == 'must replace all names at once with a sequence of length 4'
1131 d.names = ['a', 'b', 'c', 'd']
1132 assert d.names == ('a', 'b', 'c', 'd')
1133 exc = raises(ValueError, "d.names = ('a', 'b', 'c', 'c')")
1134 assert exc.value[0] == "Duplicate field names given."
1135 exc = raises(AttributeError, 'del d.names')
1136 assert exc.value[0] == "Cannot delete dtype names attribute"
1137 assert d.names == ('a', 'b', 'c', 'd')
1138 raises(KeyError, 'd["xyz"]')
1139 raises(KeyError, 'd.fields["xyz"]')
1140 d = dtype([('', '<i8'), ('', '<f8')])
1141 assert d.descr == [('f0', '<i8'), ('f1', '<f8')]
1142 d = dtype([('', '<i8'), ('b', '<f8')])
1143 assert d.descr == [('f0', '<i8'), ('b', '<f8')]
1144 d = dtype([('a', '<i8'), ('', '<f8')])
1145 assert d.descr == [('a', '<i8'), ('f1', '<f8')]
1146 exc = raises(ValueError, "dtype([('a', '<i8'), ('a', '<f8')])")
1147 assert exc.value[0] == 'two fields with the same name'
1148
1149 def test_array_from_record(self):
1150 import numpy as np
1151 a = np.array(('???', -999, -12345678.9),
1152 dtype=[('c', '|S3'), ('a', '<i8'), ('b', '<f8')])
1153 # Change the order of the keys
1154 b = np.array(a, dtype=[('a', '<i8'), ('b', '<f8'), ('c', '|S3')])
1155 assert b.base is None
1156 assert b.dtype.fields['a'][1] == 0
1157 assert b['a'] == -999
1158 a = np.array(('N/A', 1e+20, 1e+20, 999999),
1159 dtype=[('name', '|S4'), ('x', '<f8'),
1160 ('y', '<f8'), ('block', '<i8', (2, 3))])
1161 assert (a['block'] == 999999).all()
1162
1163 def test_create_from_dict(self):
1164 import numpy as np
1165 import sys
1166 d = {'names': ['r','g','b','a'],
1167 'formats': [np.uint8, np.uint8, np.uint8, np.uint8]}
1168 dt = np.dtype(d)
1169
1170 def test_create_subarrays(self):
1171 from numpy import dtype
1172 d = dtype([("x", "float", (2,)), ("y", "int64", (2,))])
1173 assert d.itemsize == 32
1174 assert d.name == "void256"
1175 keys = d.fields.keys()
1176 assert "x" in keys
1177 assert "y" in keys
1178 assert d["x"].shape == (2,)
1179 assert d["x"].itemsize == 16
1180 e = dtype([("x", "float", 2), ("y", "int", 2)])
1181 assert e.fields.keys() == keys
1182 for v in ['x', u'x', 0, -2]:
1183 assert e[v] == (dtype('float'), (2,))
1184 for v in ['y', u'y', 1, -1]:
1185 assert e[v] == (dtype('int'), (2,))
1186 for v in [-3, 2]:
1187 exc = raises(IndexError, "e[%d]" % v)
1188 assert exc.value.message == "Field index %d out of range." % v
1189 exc = raises(KeyError, "e['z']")
1190 assert exc.value.message == "Field named 'z' not found."
1191 exc = raises(ValueError, "e[None]")
1192 assert exc.value.message == 'Field key must be an integer, string, or unicode.'
1193
1194 dt = dtype((float, 10))
1195 assert dt.shape == (10,)
1196 assert dt.kind == 'V'
1197 assert dt.fields == None
1198 assert dt.subdtype == (dtype(float), (10,))
1199 assert dt.base == dtype(float)
1200
1201 def test_setstate(self):
1202 import numpy as np
1203 import sys
1204 E = '<' if sys.byteorder == 'little' else '>'
1205 d = np.dtype('f8')
1206 d.__setstate__((3, '|', (np.dtype('float64'), (2,)), None, None, 20, 1, 0))
1207 assert d.str == ('<' if sys.byteorder == 'little' else '>') + 'f8'
1208 assert d.fields is None
1209 assert d.shape == ()
1210 assert d.itemsize == 8
1211 assert d.subdtype is None
1212 assert repr(d) == "dtype('float64')"
1213
1214 d = np.dtype(('>' if sys.byteorder == 'little' else '<') + 'f8')
1215 d.__setstate__((3, '|', (np.dtype('float64'), (2,)), None, None, 20, 1, 0))
1216 assert d.str == '|f8'
1217 assert d.fields is None
1218 assert d.shape == (2,)
1219 assert d.itemsize == 8
1220 assert d.subdtype is not None
1221 assert repr(d) == "dtype(('{E}f8', (2,)))".format(E=E)
1222
1223 d = np.dtype(('<f8', 2))
1224 assert d.fields is None
1225 assert d.shape == (2,)
1226 assert d.itemsize == 16
1227 assert d.subdtype is not None
1228 assert repr(d) == "dtype(('<f8', (2,)))"
1229
1230 d = np.dtype(('<f8', 2))
1231 d.__setstate__((3, '|', (np.dtype('float64'), (2,)), None, None, 20, 1, 0))
1232 assert d.fields is None
1233 assert d.shape == (2,)
1234 assert d.itemsize == 20
1235 assert d.subdtype is not None
1236 assert repr(d) == "dtype(('{E}f8', (2,)))".format(E=E)
1237
1238 d = np.dtype(('<f8', 2))
1239 d.__setstate__((3, '|', (np.dtype('float64'), 2), None, None, 20, 1, 0))
1240 assert d.fields is None
1241 assert d.shape == (2,)
1242 assert d.itemsize == 20
1243 assert d.subdtype is not None
1244 assert repr(d) == "dtype(('{E}f8', (2,)))".format(E=E)
1245
1246 d = np.dtype(('<f8', 2))
1247 exc = raises(ValueError, "d.__setstate__((3, '|', None, ('f0', 'f1'), None, 16, 1, 0))")
1248 inconsistent = 'inconsistent fields and names in Numpy dtype unpickling'
1249 assert exc.value[0] == inconsistent
1250 assert d.fields is None
1251 assert d.shape == (2,)
1252 assert d.subdtype is not None
1253 assert repr(d) == "dtype(('<f8', (2,)))"
1254
1255 d = np.dtype(('<f8', 2))
1256 exc = raises(ValueError, "d.__setstate__((3, '|', None, None, {'f0': (np.dtype('float64'), 0), 'f1': (np.dtype('float64'), 8)}, 16, 1, 0))")
1257 assert exc.value[0] == inconsistent
1258 assert d.fields is None
1259 assert d.shape == (2,)
1260 assert d.subdtype is not None
1261 assert repr(d) == "dtype(('<f8', (2,)))"
1262
1263 d = np.dtype(('<f8', 2))
1264 exc = raises(ValueError, "d.__setstate__((3, '|', (np.dtype('float64'), (2,), 3), ('f0', 'f1'), {'f0': (np.dtype('float64'), 0), 'f1': (np.dtype('float64'), 8)}, 16, 1, 0))")
1265 assert exc.value[0] == 'incorrect subarray in __setstate__'
1266 assert d.fields is None
1267 assert d.shape == ()
1268 assert d.subdtype is None
1269 assert repr(d) == "dtype('V16')"
1270
1271 d = np.dtype(('<f8', 2))
1272 d.__setstate__((3, '|', (np.dtype('float64'), (2,)), ('f0', 'f1'), {'f0': (np.dtype('float64'), 0), 'f1': (np.dtype('float64'), 8)}, 16, 1, 0))
1273 assert d.fields is not None
1274 assert d.shape == (2,)
1275 assert d.subdtype is not None
1276 assert repr(d) == "dtype([('f0', '{E}f8'), ('f1', '{E}f8')])".format(E=E)
1277
1278 d = np.dtype(('<f8', 2))
1279 d.__setstate__((3, '|', None, ('f0', 'f1'), {'f0': (np.dtype('float64'), 0), 'f1': (np.dtype('float64'), 8)}, 16, 1, 0))
1280 assert d.fields is not None
1281 assert d.shape == ()
1282 assert d.subdtype is None
1283 assert repr(d) == "dtype([('f0', '{E}f8'), ('f1', '{E}f8')])".format(E=E)
1284
1285 d = np.dtype(('<f8', 2))
1286 d.__setstate__((3, '|', None, ('f0', 'f1'), {'f0': (np.dtype('float64'), 0), 'f1': (np.dtype('float64'), 8)}, 16, 1, 0))
1287 d.__setstate__((3, '|', (np.dtype('float64'), (2,)), None, None, 16, 1, 0))
1288 assert d.fields is not None
1289 assert d.shape == (2,)
1290 assert d.subdtype is not None
1291 assert repr(d) == "dtype([('f0', '{E}f8'), ('f1', '{E}f8')])".format(E=E)
1292
1293 def test_pickle_record(self):
1294 from numpy import array, dtype
1295 from cPickle import loads, dumps
1296
1297 d = dtype([("x", "int32"), ("y", "int32"), ("z", "int32"), ("value", float)])
1298 assert d.__reduce__() == (dtype, ('V20', 0, 1), (3, '|', None,
1299 ('x', 'y', 'z', 'value'),
1300 {'y': (dtype('int32'), 4), 'x': (dtype('int32'), 0),
1301 'z': (dtype('int32'), 8), 'value': (dtype('float64'), 12),
1302 }, 20, 1, 16))
1303
1304 new_d = loads(dumps(d))
1305
1306 assert new_d.__reduce__() == d.__reduce__()
1307
1308 def test_pickle_record_subarrays(self):
1309 from numpy import array, dtype
1310 from cPickle import loads, dumps
1311
1312 d = dtype([("x", "int32", (3,)), ("y", "int32", (2,)), ("z", "int32", (4,)), ("value", float, (5,))])
1313 new_d = loads(dumps(d))
1314
1315 keys = d.fields.keys()
1316 keys.sort()
1317 assert keys == ["value", "x", "y", "z"]
1318
1319 assert new_d.itemsize == d.itemsize == 76
1320
1321 def test_shape_invalid(self):
1322 import numpy as np
1323 # Check that the shape is valid.
1324 max_int = 2 ** (8 * 4 - 1)
1325 max_intp = 2 ** (8 * np.dtype('intp').itemsize - 1) - 1
1326 # Too large values (the datatype is part of this)
1327 raises(ValueError, np.dtype, [('a', 'f4', max_int // 4 + 1)])
1328 raises(ValueError, np.dtype, [('a', 'f4', max_int + 1)])
1329 raises(ValueError, np.dtype, [('a', 'f4', (max_int, 2))])
1330 # Takes a different code path (fails earlier:
1331 raises(ValueError, np.dtype, [('a', 'f4', max_intp + 1)])
1332 # Negative values
1333 raises(ValueError, np.dtype, [('a', 'f4', -1)])
1334 raises(ValueError, np.dtype, [('a', 'f4', (-1, -1))])
1335
1336 def test_aligned_size(self):
1337 import sys
1338 import numpy as np
1339 if self.test_for_core_internal:
1340 try:
1341 from numpy.core import _internal
1342 except ImportError:
1343 skip ('no numpy.core._internal available')
1344 # Check that structured dtypes get padded to an aligned size
1345 dt = np.dtype('i4, i1', align=True)
1346 assert dt.itemsize == 8
1347 dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True)
1348 assert dt.itemsize == 8
1349 dt = np.dtype({'names':['f0', 'f1'],
1350 'formats':['i4', 'u1'],
1351 'offsets':[0, 4]}, align=True)
1352 assert dt.itemsize == 8
1353 dt = np.dtype({'f0': ('i4', 0), 'f1':('u1', 4)}, align=True)
1354 assert dt.itemsize == 8
1355 assert dt.alignment == 4
1356 E = '<' if sys.byteorder == 'little' else '>'
1357 assert str(dt) == "{'names':['f0','f1'], 'formats':['%si4','u1'], 'offsets':[0,4], 'itemsize':8, 'aligned':True}" % E
1358 dt = np.dtype([('f1', 'u1'), ('f0', 'i4')], align=True)
1359 assert str(dt) == "{'names':['f1','f0'], 'formats':['u1','%si4'], 'offsets':[0,4], 'itemsize':8, 'aligned':True}" % E
1360 # Nesting should preserve that alignment
1361 dt1 = np.dtype([('f0', 'i4'),
1362 ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),
1363 ('f2', 'i1')], align=True)
1364 assert dt1.alignment == 4
1365 assert dt1['f1'].itemsize == 12
1366 assert dt1.itemsize == 20
1367 dt2 = np.dtype({'names':['f0', 'f1', 'f2'],
1368 'formats':['i4',
1369 [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],
1370 'i1'],
1371 'offsets':[0, 4, 16]}, align=True)
1372 assert dt2.itemsize == 20
1373 dt3 = np.dtype({'f0': ('i4', 0),
1374 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),
1375 'f2': ('i1', 16)}, align=True)
1376 assert dt3.itemsize == 20
1377 assert dt1 == dt2
1378 answer = "{'names':['f0','f1','f2'], " + \
1379 "'formats':['%si4',{'names':['f1','f2','f3'], " + \
1380 "'formats':['i1','%si4','i1'], " + \
1381 "'offsets':[0,4,8], 'itemsize':12}," + \
1382 "'i1'], " + \
1383 "'offsets':[0,4,16], 'itemsize':20, 'aligned':True}"
1384 assert str(dt3) == answer % (E,E)
1385 assert dt2 == dt3
1386 # Nesting should preserve packing
1387 dt1 = np.dtype([('f0', 'i4'),
1388 ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),
1389 ('f2', 'i1')], align=False)
1390 assert dt1.itemsize == 11
1391 dt2 = np.dtype({'names':['f0', 'f1', 'f2'],
1392 'formats':['i4',
1393 [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],
1394 'i1'],
1395 'offsets':[0, 4, 10]}, align=False)
1396 assert dt2.itemsize == 11
1397 dt3 = np.dtype({'f0': ('i4', 0),
1398 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),
1399 'f2': ('i1', 10)}, align=False)
1400 assert dt3.itemsize == 11
1401 assert dt1 == dt2
1402 assert dt2 == dt3
1403
1404 def test_bad_param(self):
1405 import numpy as np
1406 # Can't give a size that's too small
1407 raises(ValueError, np.dtype,
1408 {'names':['f0', 'f1'],
1409 'formats':['i4', 'i1'],
1410 'offsets':[0, 4],
1411 'itemsize':4})
1412 # If alignment is enabled, the alignment (4) must divide the itemsize
1413 raises(ValueError, np.dtype,
1414 {'names':['f0', 'f1'],
1415 'formats':['i4', 'i1'],
1416 'offsets':[0, 4],
1417 'itemsize':9}, align=True)
1418 # If alignment is enabled, the individual fields must be aligned
1419 raises(ValueError, np.dtype,
1420 {'names':['f0', 'f1'],
1421 'formats':['i1', 'f4'],
1422 'offsets':[0, 2]}, align=True)
1423 dt = np.dtype(np.double)
1424 attr = ["subdtype", "descr", "str", "name", "base", "shape",
1425 "isbuiltin", "isnative", "isalignedstruct", "fields",
1426 "metadata", "hasobject"]
1427 for s in attr:
1428 raises(AttributeError, delattr, dt, s)
1429
1430 raises(TypeError, np.dtype,
1431 dict(names=set(['A', 'B']), formats=['f8', 'i4']))
1432 raises(TypeError, np.dtype,
1433 dict(names=['A', 'B'], formats=set(['f8', 'i4'])))
1434
1435 def test_complex_dtype_repr(self):
1436 import numpy as np
1437 dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
1438 ('rtile', '>f4', (64, 36))], (3,)),
1439 ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
1440 ('bright', '>f4', (8, 36))])])
1441 assert repr(dt) == (
1442 "dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), "
1443 "('rtile', '>f4', (64, 36))], (3,)), "
1444 "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), "
1445 "('bright', '>f4', (8, 36))])])")
1446
1447 # If the sticky aligned flag is set to True, it makes the
1448 # str() function use a dict representation with an 'aligned' flag
1449 dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
1450 ('rtile', '>f4', (64, 36))],
1451 (3,)),
1452 ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
1453 ('bright', '>f4', (8, 36))])],
1454 align=True)
1455 assert str(dt) == (
1456 "{'names':['top','bottom'], "
1457 "'formats':[([('tiles', ('>f4', (64, 64)), (1,)), "
1458 "('rtile', '>f4', (64, 36))], (3,)),"
1459 "[('bleft', ('>f4', (8, 64)), (1,)), "
1460 "('bright', '>f4', (8, 36))]], "
1461 "'offsets':[0,76800], "
1462 "'itemsize':80000, "
1463 "'aligned':True}")
1464
1465 assert dt == np.dtype(eval(str(dt)))
1466
1467 dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'],
1468 'offsets': [0, 1, 2],
1469 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']},
1470 align=True)
1471 assert repr(dt) == (
1472 "dtype([(('Red pixel', 'r'), 'u1'), "
1473 "(('Green pixel', 'g'), 'u1'), "
1474 "(('Blue pixel', 'b'), 'u1')], align=True)")
1475
1476 dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'],
1477 'formats': ['<u4', 'u1', 'u1', 'u1'],
1478 'offsets': [0, 0, 1, 2],
1479 'titles': ['Color', 'Red pixel',
1480 'Green pixel', 'Blue pixel']}, align=True)
1481 assert repr(dt) == (
1482 "dtype({'names':['rgba','r','g','b'],"
1483 " 'formats':['<u4','u1','u1','u1'],"
1484 " 'offsets':[0,0,1,2],"
1485 " 'titles':['Color','Red pixel',"
1486 "'Green pixel','Blue pixel'],"
1487 " 'itemsize':4}, align=True)")
1488
1489 dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],
1490 'offsets': [0, 2],
1491 'titles': ['Red pixel', 'Blue pixel'],
1492 'itemsize': 4})
1493 assert repr(dt) == (
1494 "dtype({'names':['r','b'], "
1495 "'formats':['u1','u1'], "
1496 "'offsets':[0,2], "
1497 "'titles':['Red pixel','Blue pixel'], "
1498 "'itemsize':4})")
1499 if 'datetime64' not in dir(np):
1500 skip('datetime dtype not available')
1501 dt = np.dtype([('a', '<M8[D]'), ('b', '<m8[us]')])
1502 assert repr(dt) == (
1503 "dtype([('a', '<M8[D]'), ('b', '<m8[us]')])")
1504
1505
1506 class AppTestNotDirect(BaseNumpyAppTest):
1507 def setup_class(cls):
1508 BaseNumpyAppTest.setup_class.__func__(cls)
1509 def check_non_native(w_obj, w_obj2):
1510 stor1 = w_obj.implementation.storage
1511 stor2 = w_obj2.implementation.storage
1512 assert stor1[0] == stor2[1]
1513 assert stor1[1] == stor2[0]
1514 if stor1[0] == '\x00':
1515 assert stor2[1] == '\x00'
1516 assert stor2[0] == '\x01'
1517 else:
1518 assert stor2[1] == '\x01'
1519 assert stor2[0] == '\x00'
1520 if option.runappdirect:
1521 cls.w_check_non_native = lambda *args : None
1522 else:
1523 cls.w_check_non_native = cls.space.wrap(interp2app(check_non_native))
1524
1525 def test_non_native(self):
1526 from numpy import array
1527 a = array([1, 2, 3], dtype=self.non_native_prefix + 'i2')
1528 assert a[0] == 1
1529 assert (a + a)[1] == 4
1530 self.check_non_native(a, array([1, 2, 3], 'i2'))
1531 a = array([1, 2, 3], dtype=self.non_native_prefix + 'f8')
1532 assert a[0] == 1
1533 assert (a + a)[1] == 4
1534 a = array([1, 2, 3], dtype=self.non_native_prefix + 'f4')
1535 assert a[0] == 1
1536 assert (a + a)[1] == 4
1537 a = array([1, 2, 3], dtype=self.non_native_prefix + 'f2')
1538 assert a[0] == 1
1539 assert (a + a)[1] == 4
1540 a = array([1, 2, 3], dtype=self.non_native_prefix + 'g') # longdouble
1541 assert a[0] == 1
1542 assert (a + a)[1] == 4
1543 a = array([1, 2, 3], dtype=self.non_native_prefix + 'G') # clongdouble
1544 assert a[0] == 1
1545 assert (a + a)[1] == 4
1546
1547 class AppTestMonsterType(BaseNumpyAppTest):
1548 """Test deeply nested subtypes."""
1549 def test1(self):
1550 import numpy as np
1551 simple1 = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],
1552 'titles': ['Red pixel', 'Blue pixel']})
1553 a = np.dtype([('yo', int), ('ye', simple1),
1554 ('yi', np.dtype((int, (3, 2))))])
1555 b = np.dtype([('yo', int), ('ye', simple1),
1556 ('yi', np.dtype((int, (3, 2))))])
1557 assert a == b
1558
1559 c = np.dtype([('yo', int), ('ye', simple1),
1560 ('yi', np.dtype((a, (3, 2))))])
1561 d = np.dtype([('yo', int), ('ye', simple1),
1562 ('yi', np.dtype((a, (3, 2))))])
1563 assert c == d
1564
1565
1566 class AppTestMetadata(BaseNumpyAppTest):
1567 def test_no_metadata(self):
1568 import numpy as np
1569 d = np.dtype(int)
1570 assert d.metadata is None
1571
1572 def test_metadata_takes_dict(self):
1573 import numpy as np
1574 d = np.dtype(int, metadata={'datum': 1})
1575 assert d.metadata == {'datum': 1}
1576
1577 def test_metadata_rejects_nondict(self):
1578 import numpy as np
1579 raises(TypeError, np.dtype, int, metadata='datum')
1580 raises(TypeError, np.dtype, int, metadata=1)
1581 raises(TypeError, np.dtype, int, metadata=None)
1582
1583 def test_nested_metadata(self):
1584 import numpy as np
1585 d = np.dtype([('a', np.dtype(int, metadata={'datum': 1}))])
1586 assert d['a'].metadata == {'datum': 1}
1587
1588