Debian Codegraph @

pypy/module/micronumpy/test/test_scalar.py

raw symbols SCIP
1 # -*- encoding:utf-8 -*-
2 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
3
4 class AppTestScalar(BaseNumpyAppTest):
5 spaceconfig = dict(usemodules=["micronumpy", "binascii", "struct"])
6
7 def test_integer_types(self):
8 import numpy as np
9 _32BIT = np.dtype('int').itemsize == 4
10 if _32BIT:
11 assert np.int32 is np.dtype('l').type
12 assert np.uint32 is np.dtype('L').type
13 assert np.intp is np.dtype('i').type
14 assert np.uintp is np.dtype('I').type
15 assert np.int64 is np.dtype('q').type
16 assert np.uint64 is np.dtype('Q').type
17 else:
18 assert np.int32 is np.dtype('i').type
19 assert np.uint32 is np.dtype('I').type
20 assert np.intp is np.dtype('l').type
21 assert np.uintp is np.dtype('L').type
22 assert np.int64 is np.dtype('l').type
23 assert np.uint64 is np.dtype('L').type
24 assert np.int16 is np.short is np.dtype('h').type
25 assert np.int_ is np.dtype('l').type
26 assert np.uint is np.dtype('L').type
27 assert np.dtype('intp') == np.dtype('int')
28 assert np.dtype('uintp') == np.dtype('uint')
29 assert np.dtype('i') is not np.dtype('l') is not np.dtype('q')
30 assert np.dtype('I') is not np.dtype('L') is not np.dtype('Q')
31
32 def test_hierarchy(self):
33 import numpy
34 assert issubclass(numpy.float64, numpy.floating)
35 assert issubclass(numpy.longfloat, numpy.floating)
36 assert not issubclass(numpy.float64, numpy.longfloat)
37 assert not issubclass(numpy.longfloat, numpy.float64)
38
39 def test_mro(self):
40 import numpy
41 assert numpy.int16.__mro__ == (numpy.int16, numpy.signedinteger,
42 numpy.integer, numpy.number,
43 numpy.generic, object)
44 assert numpy.bool_.__mro__ == (numpy.bool_, numpy.generic, object)
45
46 def test_init(self):
47 import numpy as np
48 import math
49 import sys
50 assert np.intp() == np.intp(0)
51 assert np.intp('123') == np.intp(123)
52 raises(TypeError, np.intp, None)
53 assert np.float64() == np.float64(0)
54 assert math.isnan(np.float64(None))
55 assert np.bool_() == np.bool_(False)
56 assert np.bool_('abc') == np.bool_(True)
57 assert np.bool_(None) == np.bool_(False)
58 assert np.complex_() == np.complex_(0)
59 #raises(TypeError, np.complex_, '1+2j')
60 assert math.isnan(np.complex_(None))
61 for c in ['i', 'I', 'l', 'L', 'q', 'Q']:
62 assert np.dtype(c).type().dtype.char == c
63 for c in ['l', 'q']:
64 assert np.dtype(c).type(sys.maxint) == sys.maxint
65 for c in ['L', 'Q']:
66 assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
67 assert np.float32(np.array([True, False])).dtype == np.float32
68 assert type(np.float32(np.array([True]))) is np.ndarray
69 assert type(np.float32(1.0)) is np.float32
70 a = np.array([True, False])
71 assert np.bool_(a) is a
72
73 def test_builtin(self):
74 import numpy as np
75 assert int(np.str_('12')) == 12
76 exc = raises(ValueError, "int(np.str_('abc'))")
77 assert str(exc.value).startswith('invalid literal for int()')
78 assert int(np.uint64((2<<63) - 1)) == (2<<63) - 1
79 exc = raises(ValueError, "int(np.float64(np.nan))")
80 assert str(exc.value) == "cannot convert float NaN to integer"
81 exc = raises(OverflowError, "int(np.float64(np.inf))")
82 assert str(exc.value) == "cannot convert float infinity to integer"
83 assert int(np.float64(1e100)) == int(1e100)
84 assert long(np.float64(1e100)) == int(1e100)
85 assert int(np.complex128(1e100+2j)) == int(1e100)
86 exc = raises(OverflowError, "int(np.complex64(1e100+2j))")
87 assert str(exc.value) == "cannot convert float infinity to integer"
88 assert int(np.str_('100000000000000000000')) == 100000000000000000000
89 assert long(np.str_('100000000000000000000')) == 100000000000000000000
90
91 assert float(np.float64(1e100)) == 1e100
92 assert float(np.complex128(1e100+2j)) == 1e100
93 assert float(np.str_('1e100')) == 1e100
94 assert float(np.str_('inf')) == np.inf
95 assert str(float(np.float64(np.nan))) == 'nan'
96
97 assert oct(np.int32(11)) == '0o13'
98 assert oct(np.float32(11.6)) == '0o13'
99 assert oct(np.complex64(11-12j)) == '0o13'
100 assert hex(np.int32(11)) == '0xb'
101 assert hex(np.float32(11.6)) == '0xb'
102 assert hex(np.complex64(11-12j)) == '0xb'
103 assert bin(np.int32(11)) == '0b1011'
104 exc = raises(TypeError, "bin(np.float32(11.6))")
105 assert "index" in exc.value.message
106 exc = raises(TypeError, "len(np.int32(11))")
107 assert "has no len" in exc.value.message
108 assert len(np.string_('123')) == 3
109
110 def test_pickle(self):
111 from numpy import dtype, zeros
112 import sys
113 try:
114 from numpy.core.multiarray import scalar
115 except ImportError:
116 # running on dummy module
117 from numpy import scalar
118 from pickle import loads, dumps
119 i = dtype('int32').type(1337)
120 f = dtype('float64').type(13.37)
121 c = dtype('complex128').type(13 + 37.j)
122
123 swap = lambda s: (''.join(reversed(s))) if sys.byteorder == 'big' else s
124 assert i.__reduce__() == (scalar, (dtype('int32'), swap('9\x05\x00\x00')))
125 assert f.__reduce__() == (scalar, (dtype('float64'), swap('=\n\xd7\xa3p\xbd*@')))
126 assert c.__reduce__() == (scalar, (dtype('complex128'), swap('\x00\x00\x00\x00\x00\x00*@') + \
127 swap('\x00\x00\x00\x00\x00\x80B@')))
128
129 assert loads(dumps(i)) == i
130 assert loads(dumps(f)) == f
131 assert loads(dumps(c)) == c
132
133 a = zeros(3)
134 assert loads(dumps(a.sum())) == a.sum()
135
136 def test_round(self):
137 import numpy as np
138 i = np.dtype('int32').type(1337)
139 f = np.dtype('float64').type(13.37)
140 c = np.dtype('complex128').type(13 + 37.j)
141 b = np.dtype('bool').type(1)
142 assert i.round(decimals=-2) == 1300
143 assert i.round(decimals=1) == 1337
144 assert c.round() == c
145 assert f.round() == 13.
146 assert f.round(decimals=-1) == 10.
147 assert f.round(decimals=1) == 13.4
148 raises(TypeError, b.round, decimals=5)
149 assert f.round(decimals=1, out=None) == 13.4
150 assert b.round() == 1.0
151
152 def test_astype(self):
153 import numpy as np
154 a = np.bool_(True).astype(np.float32)
155 assert type(a) is np.float32
156 assert a == 1.0
157 a = np.bool_(True).astype('int32')
158 assert type(a) is np.int32
159 assert a == 1
160 a = np.str_('123').astype('int32')
161 assert type(a) is np.int32
162 assert a == 123
163
164 def test_copy(self):
165 import numpy as np
166 a = np.int32(2)
167 b = a.copy()
168 assert type(b) is type(a)
169 assert b == a
170 assert b is not a
171
172 def test_methods(self):
173 import numpy as np
174 for a in [np.int32(2), np.float64(2.0), np.complex64(42)]:
175 for op in ['min', 'max', 'sum', 'prod']:
176 assert getattr(a, op)() == a
177 for op in ['argmin', 'argmax']:
178 b = getattr(a, op)()
179 assert type(b) is np.int_
180 assert b == 0
181
182 def test_buffer(self):
183 import numpy as np
184 a = np.int32(123)
185 b = memoryview(a)
186 assert type(b) is memoryview
187 a = np.string_('abc')
188 b = memoryview(a)
189 assert str(b) == a
190
191 def test_byteswap(self):
192 import numpy as np
193 assert np.int64(123).byteswap() == 8863084066665136128
194 a = np.complex64(1+2j).byteswap()
195 assert repr(a.real).startswith('4.60060')
196 assert repr(a.imag).startswith('8.96831')
197
198 def test_squeeze(self):
199 import numpy as np
200 assert np.True_.squeeze() is np.True_
201 a = np.float32(1.0)
202 assert a.squeeze() is a
203 raises(TypeError, a.squeeze, 2)
204
205 def test_bitshift(self):
206 import numpy as np
207 assert np.int32(123) >> 1 == 61
208 assert type(np.int32(123) >> 1) is np.int_
209 assert np.int64(123) << 1 == 246
210 assert type(np.int64(123) << 1) is np.int64
211 exc = raises(TypeError, "np.uint64(123) >> 1")
212 assert 'not supported for the input types' in exc.value.message
213
214 def test_attributes(self):
215 import numpy as np
216 value = np.dtype('int64').type(12345)
217 assert value.dtype == np.dtype('int64')
218 assert value.size == 1
219 assert value.itemsize == 8
220 assert value.nbytes == 8
221 assert value.shape == ()
222 assert value.strides == ()
223 assert value.ndim == 0
224 assert value.T is value
225
226 def test_indexing(self):
227 import numpy as np
228 v = np.int32(2)
229 b = v[()]
230 assert isinstance(b, np.int32)
231 assert b.shape == ()
232 assert b == v
233 b = v[...]
234 assert isinstance(b, np.ndarray)
235 assert b.shape == ()
236 assert b == v
237 raises(IndexError, "v['blah']")
238
239 def test_realimag(self):
240 import numpy as np
241 a = np.int64(2)
242 assert a.real == 2
243 assert a.imag == 0
244 a = np.float64(2.5)
245 assert a.real == 2.5
246 assert a.imag == 0.0
247 a = np.complex64(2.5-1.5j)
248 assert a.real == 2.5
249 assert a.imag == -1.5
250
251 def test_view(self):
252 import numpy as np
253 import sys
254 s = np.dtype('int64').type(12)
255 exc = raises(ValueError, s.view, 'int8')
256 assert str(exc.value) == "new type not compatible with array."
257 t = s.view('double')
258 assert type(t) is np.double
259 assert t < 7e-323
260 t = s.view('complex64')
261 assert type(t) is np.complex64
262 if sys.byteorder == 'big':
263 assert 0 < t.imag < 1
264 assert t.real == 0
265 else:
266 assert 0 < t.real < 1
267 assert t.imag == 0
268 exc = raises(TypeError, s.view, 'string')
269 assert str(exc.value) == "data-type must not be 0-sized"
270 t = s.view('S8')
271 assert type(t) is np.string_
272 if sys.byteorder == 'big':
273 assert t == '\x00' * 7 + '\x0c'
274 else:
275 assert t == '\x0c'
276 s = np.dtype('string').type('abc1')
277 assert s.view('S4') == 'abc1'
278 if '__pypy__' in sys.builtin_module_names:
279 raises(NotImplementedError, s.view, [('a', 'i2'), ('b', 'i2')])
280 else:
281 b = s.view([('a', 'i2'), ('b', 'i2')])
282 assert b.shape == ()
283 assert b[0] == 25185
284 assert b[1] == 12643
285 if '__pypy__' in sys.builtin_module_names:
286 raises(TypeError, "np.dtype([('a', 'int64'), ('b', 'int64')]).type('a' * 16)")
287 else:
288 s = np.dtype([('a', 'int64'), ('b', 'int64')]).type('a' * 16)
289 assert s.view('S16') == 'a' * 16
290
291 def test_as_integer_ratio(self):
292 import numpy as np
293 raises(AttributeError, 'np.float32(1.5).as_integer_ratio()')
294 assert np.float64(1.5).as_integer_ratio() == (3, 2)
295
296 def test_tostring(self):
297 import numpy as np
298 assert np.int64(123).tostring() == np.array(123, dtype='i8').tostring()
299 assert np.int64(123).tostring('C') == np.array(123, dtype='i8').tostring()
300 assert np.float64(1.5).tostring() == np.array(1.5, dtype=float).tostring()
301 exc = raises(TypeError, 'np.int64(123).tostring("Z")')
302 assert exc.value[0] == 'order not understood'
303
304 def test_reshape(self):
305 import numpy as np
306 assert np.int64(123).reshape((1,)) == 123
307 assert np.int64(123).reshape(1).shape == (1,)
308 assert np.int64(123).reshape((1,)).shape == (1,)
309 exc = raises(ValueError, "np.int64(123).reshape((2,))")
310 assert exc.value[0] == 'total size of new array must be unchanged'
311 assert type(np.int64(123).reshape(())) == np.int64
312
313 def test_complex_scalar_complex_cast(self):
314 import numpy as np
315 for tp in [np.csingle, np.cdouble, np.clongdouble]:
316 x = tp(1+2j)
317 assert hasattr(x, '__complex__') == (tp != np.cdouble)
318 assert complex(x) == 1+2j
319
320 def test_complex_str_format(self):
321 import numpy as np
322 for t in [np.complex64, np.complex128]:
323 assert str(t(complex(1, float('nan')))) == '(1+nan*j)'
324 assert str(t(complex(1, float('-nan')))) == '(1+nan*j)'
325 assert str(t(complex(1, float('inf')))) == '(1+inf*j)'
326 assert str(t(complex(1, float('-inf')))) == '(1-inf*j)'
327 for x in [0, 1, -1]:
328 assert str(t(complex(x))) == str(complex(x))
329 assert str(t(x*1j)) == str(complex(x*1j))
330 assert str(t(x + x*1j)) == str(complex(x + x*1j))
331
332 def test_complex_zero_division(self):
333 import numpy as np
334 for t in [np.complex64, np.complex128]:
335 a = t(0.0)
336 b = t(1.0)
337 assert np.isinf(b/a)
338 b = t(complex(np.inf, np.inf))
339 assert np.isinf(b/a)
340 b = t(complex(np.inf, np.nan))
341 assert np.isinf(b/a)
342 b = t(complex(np.nan, np.inf))
343 assert np.isinf(b/a)
344 b = t(complex(np.nan, np.nan))
345 assert np.isnan(b/a)
346 b = t(0.)
347 assert np.isnan(b/a)
348
349 def test_scalar_iter(self):
350 from numpy import int8, int16, int32, int64, float32, float64
351 from numpy import complex64, complex128
352 for t in (int8, int16, int32, int64, float32, float64,
353 complex64, complex128):
354 raises(TypeError, iter, t(17))
355
356 def test_item_tolist(self):
357 from numpy import int8, int16, int32, int64, float32, float64
358 from numpy import complex64, complex128, dtype
359
360 def _do_test(np_type, py_type, orig_val, exp_val):
361 val = np_type(orig_val)
362 assert val == orig_val
363 assert val.item() == exp_val
364 assert val.tolist() == exp_val
365 assert type(val.item()) is py_type
366 assert type(val.tolist()) is py_type
367 val.item(0)
368 val.item(())
369 val.item((0,))
370 raises(ValueError, val.item, 0, 1)
371 raises(ValueError, val.item, 0, '')
372 raises(TypeError, val.item, '')
373 raises(IndexError, val.item, 2)
374
375 for t in int8, int16, int32:
376 _do_test(t, int, 17, 17)
377
378 py_type = int if dtype('int').itemsize == 8 else long
379 _do_test(int64, py_type, 17, 17)
380
381 for t in float32, float64:
382 _do_test(t, float, 17, 17)
383
384 for t in complex64, complex128:
385 _do_test(t, complex, 17j, 17j)
386
387 def test_transpose(self):
388 from numpy import int8, int16, int32, int64, float32, float64
389 from numpy import complex64, complex128
390
391 def _do_test(np_type, orig_val, exp_val):
392 val = np_type(orig_val)
393 assert val == orig_val
394 assert val.transpose() == exp_val
395 assert type(val.transpose()) is np_type
396 val.transpose(())
397 raises(ValueError, val.transpose, 0, 1)
398 raises(TypeError, val.transpose, 0, '')
399 raises(ValueError, val.transpose, 0)
400
401 for t in int8, int16, int32, int64:
402 _do_test(t, 17, 17)
403
404 for t in float32, float64:
405 _do_test(t, 17, 17)
406
407 for t in complex64, complex128:
408 _do_test(t, 17j, 17j)
409
410 def test_swapaxes(self):
411 from numpy import int8, int16, int32, int64, float32, float64
412 from numpy import complex64, complex128
413
414 def _do_test(np_type, orig_val, exp_val):
415 val = np_type(orig_val)
416 assert val == orig_val
417 raises(ValueError, val.swapaxes, 10, 20)
418 raises(ValueError, val.swapaxes, 0, 1)
419 raises(TypeError, val.swapaxes, 0, ())
420
421 for t in int8, int16, int32, int64:
422 _do_test(t, 17, 17)
423
424 for t in float32, float64:
425 _do_test(t, 17, 17)
426
427 for t in complex64, complex128:
428 _do_test(t, 17j, 17j)
429
430 def test_nonzero(self):
431 from numpy import int8, int16, int32, int64, float32, float64
432 from numpy import complex64, complex128
433
434 for t in (int8, int16, int32, int64, float32, float64,
435 complex64, complex128):
436 res, = t(17).nonzero()
437 assert len(res) == 1
438 assert res[0] == 0
439 res, = t(0).nonzero()
440 assert len(res) == 0
441
442 def test_fill(self):
443 import sys
444 from numpy import int8, int16, int32, int64, float32, float64
445 from numpy import complex64, complex128
446
447 for t in (int8, int16, int32, int64, float32, float64,
448 complex64, complex128):
449 t(17).fill(2)
450 exc = (TypeError if t in (complex64, complex128)
451 and '__pypy__' not in sys.builtin_module_names
452 else ValueError)
453 raises(exc, t(17).fill, '')
454
455 def test_conj(self):
456 from numpy import int8, int16, int32, int64, float32, float64
457 from numpy import complex64, complex128
458
459 def _do_test(np_type, orig_val, exp_val):
460 val = np_type(orig_val)
461 assert val == orig_val
462 assert val.conj() == exp_val
463 assert val.conjugate() == exp_val
464
465 for t in (int8, int16, int32, int64, float32, float64,
466 complex64, complex128):
467 _do_test(t, 17, 17)
468
469 for t in complex64, complex128:
470 _do_test(t, 17j, -17j)
471
472 def test_string_boxes(self):
473 from numpy import str_
474 assert isinstance(str_(3), str_)
475 assert str_(3) == '3'
476 assert str(str_(3)) == '3'
477 assert repr(str_(3)) == "'3'"
478
479 def test_unicode_boxes(self):
480 from numpy import unicode_
481 u = unicode_(3)
482 assert isinstance(u, unicode)
483 assert u == u'3'
484
485 def test_unicode_repr(self):
486 from numpy import unicode_
487 u = unicode_(3)
488 assert str(u) == '3'
489 assert repr(u) == "u'3'"
490 u = unicode_(u'Aÿ')
491 # raises(UnicodeEncodeError, "str(u)") # XXX
492 assert repr(u) == repr(u'Aÿ')
493
494 def test_binop_with_sequence(self):
495 import numpy as np
496 c = np.float64(1.) + [1.]
497 assert isinstance(c, np.ndarray)
498 assert (c == [2.]).all()