Debian Codegraph @

pypy/module/micronumpy/test/test_ufuncs.py

raw symbols SCIP
1 import platform
2 import py
3
4 from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
5 from pypy.module.micronumpy.ufuncs import W_UfuncGeneric, unary_ufunc
6 from pypy.module.micronumpy.support import _parse_signature
7 from pypy.module.micronumpy.descriptor import get_dtype_cache
8 from pypy.module.micronumpy.base import W_NDimArray
9 from pypy.module.micronumpy.concrete import VoidBoxStorage
10 from pypy.interpreter.error import OperationError
11
12
13 class TestGenericUfuncOperation(object):
14 def test_signature_parser(self, space):
15 class Ufunc(object):
16 def __init__(self, nin, nout):
17 self.nin = nin
18 self.nout = nout
19 self.nargs = nin + nout
20 self.core_enabled = True
21 self.core_num_dim_ix = 0
22 self.core_num_dims = [0] * self.nargs
23 self.core_offsets = [0] * self.nargs
24 self.core_dim_ixs = []
25
26 u = Ufunc(2, 1)
27 _parse_signature(space, u, '(m,n), (n,r)->(m,r)')
28 assert u.core_dim_ixs == [0, 1, 1, 2, 0, 2]
29 assert u.core_num_dims == [2, 2, 2]
30 assert u.core_offsets == [0, 2, 4]
31
32 def test_type_resolver(self, space):
33 c128_dtype = get_dtype_cache(space).w_complex128dtype
34 c64_dtype = get_dtype_cache(space).w_complex64dtype
35 f64_dtype = get_dtype_cache(space).w_float64dtype
36 f32_dtype = get_dtype_cache(space).w_float32dtype
37 u32_dtype = get_dtype_cache(space).w_uint32dtype
38 b_dtype = get_dtype_cache(space).w_booldtype
39
40 ufunc = W_UfuncGeneric(space, [None, None, None], 'eigenvals', None, 1, 1,
41 [f32_dtype, c64_dtype,
42 f64_dtype, c128_dtype,
43 c128_dtype, c128_dtype],
44 '')
45 f32_array = W_NDimArray(VoidBoxStorage(0, f32_dtype))
46 index, dtypes = ufunc.type_resolver(space, [f32_array], [None],
47 'd->D', ufunc.dtypes)
48 #needs to cast input type, create output type
49 assert index == 1
50 assert dtypes == [f64_dtype, c128_dtype]
51 index, dtypes = ufunc.type_resolver(space, [f32_array], [None],
52 '', ufunc.dtypes)
53 assert index == 0
54 assert dtypes == [f32_dtype, c64_dtype]
55 raises(OperationError, ufunc.type_resolver, space, [f32_array], [None],
56 'u->u', ufunc.dtypes)
57 exc = raises(OperationError, ufunc.type_resolver, space, [f32_array], [None],
58 'i->i', ufunc.dtypes)
59
60 def test_allowed_types(self, space):
61 dt_bool = get_dtype_cache(space).w_booldtype
62 dt_float16 = get_dtype_cache(space).w_float16dtype
63 dt_int32 = get_dtype_cache(space).w_int32dtype
64 ufunc = unary_ufunc(space, None, 'x', int_only=True)
65 assert ufunc._calc_dtype(space, dt_bool, out=None) == (dt_bool, dt_bool)
66 assert ufunc.dtypes # XXX: shouldn't contain too much stuff
67
68 ufunc = unary_ufunc(space, None, 'x', promote_to_float=True)
69 assert ufunc._calc_dtype(space, dt_bool, out=None) == (dt_float16, dt_float16)
70 assert ufunc._calc_dtype(space, dt_bool, casting='same_kind') == (dt_float16, dt_float16)
71 raises(OperationError, ufunc._calc_dtype, space, dt_bool, casting='no')
72
73 ufunc = unary_ufunc(space, None, 'x')
74 assert ufunc._calc_dtype(space, dt_int32, out=None) == (dt_int32, dt_int32)
75
76 class AppTestUfuncs(BaseNumpyAppTest):
77 def test_constants(self):
78 import numpy as np
79 assert np.FLOATING_POINT_SUPPORT == 1
80
81 def test_ufunc_instance(self):
82 from numpy import add, ufunc
83
84 assert isinstance(add, ufunc)
85 assert repr(add) == "<ufunc 'add'>"
86 assert repr(ufunc) == "<type 'numpy.ufunc'>"
87 assert add.__name__ == 'add'
88 raises(TypeError, ufunc)
89
90 def test_frompyfunc_innerloop(self):
91 from numpy import ufunc, frompyfunc, arange, dtype
92 import sys
93 def adder(a, b):
94 return a+b
95 def sumdiff(a, b):
96 return a+b, a-b
97 try:
98 adder_ufunc0 = frompyfunc(adder, 2, 1)
99 adder_ufunc1 = frompyfunc(adder, 2, 1)
100 int_func22 = frompyfunc(int, 2, 2)
101 int_func12 = frompyfunc(int, 1, 2)
102 sumdiff = frompyfunc(sumdiff, 2, 2)
103 retype = dtype(object)
104 except NotImplementedError as e:
105 # dtype of returned value is object, which is not supported yet
106 assert 'object' in str(e)
107 # Use pypy specific extension for out_dtype
108 adder_ufunc0 = frompyfunc(adder, 2, 1, dtypes=['match'])
109 sumdiff = frompyfunc(sumdiff, 2, 2, dtypes=['match'],
110 signature='(i),(i)->(i),(i)')
111 adder_ufunc1 = frompyfunc([adder, adder], 2, 1,
112 dtypes=[int, int, int, float, float, float])
113 int_func22 = frompyfunc([int, int], 2, 2, signature='(i),(i)->(i),(i)',
114 dtypes=['match'])
115 int_func12 = frompyfunc([int], 1, 2, dtypes=['match'])
116 retype = dtype(int)
117 a = arange(10)
118 assert isinstance(adder_ufunc1, ufunc)
119 res = adder_ufunc0(a, a)
120 assert res.dtype == retype
121 assert all(res == a + a)
122 res = adder_ufunc1(a, a)
123 assert res.dtype == retype
124 assert all(res == a + a)
125 raises(TypeError, frompyfunc, 1, 2, 3)
126 raises (ValueError, int_func22, a)
127 res = int_func12(a)
128 assert len(res) == 2
129 assert isinstance(res, tuple)
130 if '__pypy__' in sys.builtin_module_names:
131 assert (res[0] == a).all()
132 else:
133 assert all([r is None for r in res[0]]) # ??? no warning or error, just a fail?
134 res = sumdiff(2 * a, a)
135 assert (res[0] == 3 * a).all()
136 assert (res[1] == a).all()
137
138 def test_frompyfunc_outerloop(self):
139 import sys
140 from numpy import frompyfunc, dtype, arange
141 if '__pypy__' not in sys.builtin_module_names:
142 skip('PyPy only frompyfunc extension')
143 def int_times2(in_array, out_array):
144 assert in_array.dtype == int
145 in_flat = in_array.flat
146 out_flat = out_array.flat
147 for i in range(in_array.size):
148 out_flat[i] = in_flat[i] * 2
149 def double_times2(in_array, out_array):
150 assert in_array.dtype == float
151 in_flat = in_array.flat
152 out_flat = out_array.flat
153 for i in range(in_array.size):
154 out_flat[i] = in_flat[i] * 2
155 ufunc = frompyfunc([int_times2, double_times2], 1, 1,
156 signature='()->()',
157 dtypes=[dtype(int), dtype(int),
158 dtype(float), dtype(float)
159 ],
160 stack_inputs=True,
161 )
162 ai = arange(10, dtype=int)
163 ai2 = ufunc(ai)
164 assert all(ai2 == ai * 2)
165 af = arange(10, dtype=float)
166 af2 = ufunc(af)
167 assert all(af2 == af * 2)
168 ac = arange(10, dtype=complex)
169 raises(TypeError, ufunc, ac)
170
171 def test_frompyfunc_2d_sig(self):
172 import sys
173 from numpy import frompyfunc, dtype, arange
174 if '__pypy__' not in sys.builtin_module_names:
175 skip('PyPy only frompyfunc extension')
176 def times_2(in_array, out_array):
177 assert len(in_array.shape) == 2
178 assert in_array.shape == out_array.shape
179 out_array[:] = in_array * 2
180
181 ufunc = frompyfunc([times_2], 1, 1,
182 signature='(m,n)->(n,m)',
183 dtypes=[dtype(int), dtype(int)],
184 stack_inputs=True,
185 )
186 ai = arange(18, dtype=int).reshape(2,3,3)
187 ai3 = ufunc(ai[0,:,:])
188 ai2 = ufunc(ai)
189 assert (ai2 == ai * 2).all()
190
191 ufunc = frompyfunc([times_2], 1, 1,
192 signature='(m,m)->(m,m)',
193 dtypes=[dtype(int), dtype(int)],
194 stack_inputs=True,
195 )
196 ai = arange(12*3*3, dtype='int32').reshape(12,3,3)
197 exc = raises(ValueError, ufunc, ai[:,:,0])
198 assert "perand 0 has a mismatch in its core dimension 1" in exc.value.message
199 ai3 = ufunc(ai[0,:,:])
200 ai2 = ufunc(ai)
201 assert (ai2 == ai * 2).all()
202 # view
203 aiV = ai[::-2, :, :]
204 assert aiV.strides == (-72, 12, 4)
205 ai2 = ufunc(aiV)
206 assert (ai2 == aiV * 2).all()
207
208 ai = arange(0).reshape(0, 1, 1)
209 ao = ufunc(ai)
210 assert ao.shape == (0, 1, 1)
211
212 def test_frompyfunc_not_contiguous(self):
213 import sys
214 from numpy import frompyfunc, dtype, arange, dot
215 if '__pypy__' not in sys.builtin_module_names:
216 skip('PyPy only frompyfunc extension')
217 def _dot(in0, in1, out):
218 print in0, '\nin1',in1,'\nin1.shape', in1.shape, 'in1.strides', in1.strides
219 out[...] = dot(in0, in1)
220
221 ufunc_dot = frompyfunc(_dot, 2, 1,
222 signature='(m,m),(m,n)->(m,n)',
223 dtypes=[dtype(float), dtype(float), dtype(float)],
224 stack_inputs=True,
225 )
226 a1 = arange(4, dtype=float).reshape(2,2)
227 # create a non-c-contiguous argument
228 a2 = arange(2, dtype=float).reshape(2,1)
229 a3 = arange(2, dtype=float).reshape(1,2).T
230 b1 = ufunc_dot(a1, a2, sig='dd->d')
231 b2 = dot(a1, a2)
232 assert (b1==b2).all()
233 print 'xxxxxxxxxxxx'
234 b1 = ufunc_dot(a1, a3, sig='dd->d')
235 b2 = dot(a1, a3)
236 assert (b1==b2).all()
237
238 def test_frompyfunc_needs_nditer(self):
239 import sys
240 from numpy import frompyfunc, dtype, arange
241 if '__pypy__' not in sys.builtin_module_names:
242 skip('PyPy only frompyfunc extension')
243 def summer(in0):
244 return in0.sum()
245
246 ufunc = frompyfunc([summer], 1, 1,
247 signature='(m,m)->()',
248 dtypes=[dtype(int), dtype(int)],
249 stack_inputs=False,
250 )
251 ai = arange(12, dtype=int).reshape(3, 2, 2)
252 ao = ufunc(ai)
253 assert ao.size == 3
254
255 def test_frompyfunc_sig_broadcast(self):
256 import sys
257 from numpy import frompyfunc, dtype, arange
258 if '__pypy__' not in sys.builtin_module_names:
259 skip('PyPy only frompyfunc extension')
260 def sum_along_0(in_array, out_array):
261 out_array[...] = in_array.sum(axis=0)
262
263 def add_two(in0, in1, out):
264 out[...] = in0 + in1
265
266 ufunc_add = frompyfunc(add_two, 2, 1,
267 signature='(m,n),(m,n)->(m,n)',
268 dtypes=[dtype(int), dtype(int), dtype(int)],
269 stack_inputs=True,
270 )
271 ufunc_sum = frompyfunc([sum_along_0], 1, 1,
272 signature='(m,n)->(n)',
273 dtypes=[dtype(int), dtype(int)],
274 stack_inputs=True,
275 )
276 ai = arange(18, dtype=int).reshape(3,2,3)
277 aout1 = ufunc_add(ai, ai[0,:,:])
278 assert aout1.shape == (3, 2, 3)
279 aout2 = ufunc_add(ai, ai[0,:,:])
280 aout3 = ufunc_sum(ai)
281 assert aout3.shape == (3, 3)
282 aout4 = ufunc_add(ai, ai[0,:,:][None, :,:])
283 assert (aout1 == aout4).all()
284
285 def test_frompyfunc_fortran(self):
286 import sys
287 import numpy as np
288 if '__pypy__' not in sys.builtin_module_names:
289 skip('PyPy only frompyfunc extension')
290 def tofrom_fortran(in0, out0):
291 out0[:] = in0.T
292
293 def lapack_like_times2(in0, out0):
294 a = np.empty(in0.T.shape, in0.dtype)
295 tofrom_fortran(in0, a)
296 a *= 2
297 tofrom_fortran(a, out0)
298
299 times2 = np.frompyfunc([lapack_like_times2], 1, 1,
300 signature='(m,n)->(m,n)',
301 dtypes=[np.dtype(float), np.dtype(float)],
302 stack_inputs=True,
303 )
304 in0 = np.arange(3300, dtype=float).reshape(100, 33)
305 out0 = times2(in0)
306 assert out0.shape == in0.shape
307 assert (out0 == in0 * 2).all()
308
309 def test_frompyfunc_casting(self):
310 import sys
311 import numpy as np
312 if '__pypy__' not in sys.builtin_module_names:
313 skip('PyPy only frompyfunc extension')
314
315 def times2_int(in0, out0):
316 assert in0.dtype == int
317 assert out0.dtype == int
318 # hack to assigning to a 0-dim array
319 out0.real = in0 * 2
320
321 def times2_complex(in0, out0):
322 assert in0.dtype == complex
323 assert out0.dtype == complex
324 out0.real = in0.real * 2
325 out0.imag = in0.imag
326
327 def times2_complex0(in0):
328 assert in0.dtype == complex
329 return in0 * 2
330
331 def times2_int0(in0):
332 assert in0.dtype == int
333 return in0 * 2
334
335 times2stacked = np.frompyfunc([times2_int, times2_complex], 1, 1,
336 dtypes=[np.dtype(int), np.dtype(int),
337 np.dtype(complex), np.dtype(complex)],
338 stack_inputs=True, signature='()->()',
339 )
340 times2 = np.frompyfunc([times2_int0, times2_complex0], 1, 1,
341 dtypes=[np.dtype(int), np.dtype(int),
342 np.dtype(complex), np.dtype(complex)],
343 stack_inputs=False,
344 )
345 for d in [np.dtype(float), np.dtype('uint8'), np.dtype('complex64')]:
346 in0 = np.arange(4, dtype=d)
347 out0 = times2stacked(in0)
348 assert out0.shape == in0.shape
349 assert out0.dtype in (int, complex)
350 assert (out0 == in0 * 2).all()
351
352 out0 = times2(in0)
353 assert out0.shape == in0.shape
354 assert out0.dtype in (int, complex)
355 assert (out0 == in0 * 2).all()
356
357 in0 = np.arange(4, dtype=int)
358 out0 = times2(in0, sig='D->D')
359 assert out0.dtype == complex
360
361 def test_frompyfunc_scalar(self):
362 import sys
363 import numpy as np
364 if '__pypy__' not in sys.builtin_module_names:
365 skip('PyPy only frompyfunc extension')
366
367 def summer(in0):
368 out = np.empty(1, in0.dtype)
369 out[0] = in0.sum()
370 return out
371
372 pysummer = np.frompyfunc([summer, summer], 1, 1,
373 dtypes=[np.dtype(int), np.dtype(int),
374 np.dtype(complex), np.dtype(complex)],
375 stack_inputs=False, signature='(m,m)->()',
376 )
377 for d in [np.dtype(float), np.dtype('uint8'), np.dtype('complex64')]:
378 in0 = np.arange(4, dtype=d).reshape(1, 2, 2)
379 out0 = pysummer(in0)
380 assert out0 == in0.sum()
381 assert out0.dtype in (int, complex)
382
383 def test_ufunc_kwargs(self):
384 from numpy import ufunc, frompyfunc, arange, dtype
385 def adder(a, b):
386 return a+b
387 adder_ufunc = frompyfunc(adder, 2, 1, dtypes=['match'])
388 args = [arange(10), arange(10)]
389 res = adder_ufunc(*args, dtype=int)
390 assert all(res == args[0] + args[1])
391 # extobj support needed for linalg ufuncs
392 res = adder_ufunc(*args, extobj=[8192, 0, None])
393 assert all(res == args[0] + args[1])
394 raises(TypeError, adder_ufunc, *args, blah=True)
395 raises(TypeError, adder_ufunc, *args, extobj=True)
396 raises(RuntimeError, adder_ufunc, *args, sig='dd->d', dtype=int)
397
398 def test_unary_ufunc_kwargs(self):
399 from numpy import array, sin, float16
400 bool_array = array([True])
401 raises(TypeError, sin, bool_array, casting='no')
402 assert sin(bool_array, casting='same_kind').dtype == float16
403 raises(TypeError, sin, bool_array, out=bool_array, casting='same_kind')
404 assert sin(bool_array).dtype == float16
405
406 def test_ufunc_attrs(self):
407 from numpy import add, multiply, sin
408
409 assert add.identity == 0
410 assert multiply.identity == 1
411 assert sin.identity is None
412
413 assert add.nin == 2
414 assert add.nout == 1
415 assert add.nargs == 3
416 assert add.signature == None
417 assert multiply.nin == 2
418 assert multiply.nout == 1
419 assert multiply.nargs == 3
420 assert multiply.signature == None
421 assert sin.nin == 1
422 assert sin.nout == 1
423 assert sin.nargs == 2
424 assert sin.signature == None
425
426 def test_wrong_arguments(self):
427 from numpy import add, sin
428
429 raises(ValueError, add, 1)
430 raises(TypeError, add, 1, 2, 3)
431 raises(TypeError, sin, 1, 2)
432 raises(ValueError, sin)
433
434 def test_single_item(self):
435 from numpy import negative, sign, minimum
436
437 assert negative(5.0) == -5.0
438 assert sign(-0.0) == 0.0
439 assert minimum(2.0, 3.0) == 2.0
440
441 def test_sequence(self):
442 from numpy import array, ndarray, negative, minimum
443 a = array(range(3))
444 b = [2.0, 1.0, 0.0]
445 c = 1.0
446 b_neg = negative(b)
447 assert isinstance(b_neg, ndarray)
448 for i in range(3):
449 assert b_neg[i] == -b[i]
450 min_a_b = minimum(a, b)
451 assert isinstance(min_a_b, ndarray)
452 for i in range(3):
453 assert min_a_b[i] == min(a[i], b[i])
454 min_b_a = minimum(b, a)
455 assert isinstance(min_b_a, ndarray)
456 for i in range(3):
457 assert min_b_a[i] == min(a[i], b[i])
458 min_a_c = minimum(a, c)
459 assert isinstance(min_a_c, ndarray)
460 for i in range(3):
461 assert min_a_c[i] == min(a[i], c)
462 min_c_a = minimum(c, a)
463 assert isinstance(min_c_a, ndarray)
464 for i in range(3):
465 assert min_c_a[i] == min(a[i], c)
466 min_b_c = minimum(b, c)
467 assert isinstance(min_b_c, ndarray)
468 for i in range(3):
469 assert min_b_c[i] == min(b[i], c)
470 min_c_b = minimum(c, b)
471 assert isinstance(min_c_b, ndarray)
472 for i in range(3):
473 assert min_c_b[i] == min(b[i], c)
474
475 def test_all_available(self):
476 # tests that by calling all available ufuncs on scalars, none will
477 # raise uncaught interp-level exceptions, (and crash the test)
478 # and those that are uncallable can be accounted for.
479 # test on the base-class dtypes: int, bool, float, complex, object
480 # We need this test since they have no common base class.
481 import numpy as np
482 not_implemented = set(['ldexp', 'frexp', 'cbrt', 'spacing',
483 'hypot', 'modf', 'remainder', 'nextafter'])
484 def find_uncallable_ufuncs(dtype):
485 uncallable = set()
486 array = np.array(1, dtype)
487 for s in dir(np):
488 u = getattr(np, s)
489 if isinstance(u, np.ufunc):
490 try:
491 u(* [array] * u.nin)
492 except AttributeError:
493 pass
494 except NotImplementedError:
495 #print s
496 uncallable.add(s)
497 except TypeError:
498 assert s not in uncallable
499 uncallable.add(s)
500 return uncallable
501 assert find_uncallable_ufuncs('int') == set()
502 assert find_uncallable_ufuncs('bool') == set(['sign'])
503 uncallable = find_uncallable_ufuncs('float')
504 uncallable = uncallable.difference(not_implemented)
505 assert uncallable == set(
506 ['bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor',
507 'left_shift', 'right_shift', 'invert'])
508 uncallable = find_uncallable_ufuncs('complex')
509 uncallable = uncallable.difference(not_implemented)
510 assert uncallable == set(
511 ['bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor',
512 'arctan2', 'deg2rad', 'degrees', 'rad2deg', 'radians',
513 'fabs', 'fmod', 'invert', 'mod',
514 'logaddexp', 'logaddexp2', 'left_shift', 'right_shift',
515 'copysign', 'signbit', 'ceil', 'floor', 'trunc'])
516 uncallable = find_uncallable_ufuncs('object')
517 uncallable = uncallable.difference(not_implemented)
518 assert uncallable == set(
519 ['isnan', 'logaddexp2', 'copysign', 'isfinite', 'signbit',
520 'isinf', 'logaddexp'])
521
522 def test_int_only(self):
523 from numpy import bitwise_and, array
524 a = array(1.0)
525 raises(TypeError, bitwise_and, a, a)
526
527 def test_negative(self):
528 from numpy import array, negative
529
530 a = array([-5.0, 0.0, 1.0])
531 b = negative(a)
532 for i in range(3):
533 assert b[i] == -a[i]
534
535 a = array([-5.0, 1.0])
536 b = negative(a)
537 a[0] = 5.0
538 assert b[0] == 5.0
539 a = array(range(30))
540 assert negative(a + a)[3] == -6
541
542 a = array([[1, 2], [3, 4]])
543 b = negative(a + a)
544 assert (b == [[-2, -4], [-6, -8]]).all()
545
546 class Obj(object):
547 def __neg__(self):
548 return 'neg'
549 x = Obj()
550 assert type(negative(x)) is str
551
552 def test_abs(self):
553 from numpy import array, absolute
554
555 a = array([-5.0, -0.0, 1.0])
556 b = absolute(a)
557 for i in range(3):
558 assert b[i] == abs(a[i])
559
560 def test_add(self):
561 from numpy import array, add
562
563 a = array([-5.0, -0.0, 1.0])
564 b = array([ 3.0, -2.0,-3.0])
565 c = add(a, b)
566 for i in range(3):
567 assert c[i] == a[i] + b[i]
568 class Obj(object):
569 def __add__(self, other):
570 return 'add'
571 x = Obj()
572 assert type(add(x, 0)) is str
573
574 def test_divide(self):
575 from numpy import array, divide
576
577 a = array([-5.0, -0.0, 1.0])
578 b = array([ 3.0, -2.0,-3.0])
579 c = divide(a, b)
580 for i in range(3):
581 assert c[i] == a[i] / b[i]
582
583 assert (divide(array([-10]), array([2])) == array([-5])).all()
584
585 def test_true_divide(self):
586 import math
587 from numpy import array, true_divide
588
589 a = array([0, 1, 2, 3, 4, 1, -1])
590 b = array([4, 4, 4, 4, 4, 0, 0])
591 c = true_divide(a, b)
592 assert (c == [0.0, 0.25, 0.5, 0.75, 1.0, float('inf'), float('-inf')]).all()
593
594 assert math.isnan(true_divide(0, 0))
595
596 def test_fabs(self):
597 from numpy import array, fabs
598 from math import fabs as math_fabs, isnan
599
600 a = array([-5.0, -0.0, 1.0])
601 b = fabs(a)
602 for i in range(3):
603 assert b[i] == math_fabs(a[i])
604 assert fabs(float('inf')) == float('inf')
605 assert fabs(float('-inf')) == float('inf')
606 assert isnan(fabs(float('nan')))
607
608 def test_fmax(self):
609 from numpy import fmax, array
610 import math
611
612 nnan, nan, inf, ninf = float('-nan'), float('nan'), float('inf'), float('-inf')
613
614 a = [ninf, -5, 0, 5, inf]
615 assert (fmax(a, [ninf]*5) == a).all()
616 assert (fmax(a, [inf]*5) == [inf]*5).all()
617 assert (fmax(a, [1]*5) == [1, 1, 1, 5, inf]).all()
618 assert fmax(nan, 0) == 0
619 assert fmax(0, nan) == 0
620 assert math.isnan(fmax(nan, nan))
621 # The numpy docs specify that the FIRST NaN should be used if both are NaN
622 # Since comparisons with nnan and nan all return false,
623 # use copysign on both sides to sidestep bug in nan representaion
624 # on Microsoft win32
625 assert math.copysign(1., fmax(nnan, nan)) == math.copysign(1., nnan)
626
627 def test_fmin(self):
628 from numpy import fmin
629 import math
630
631 nnan, nan, inf, ninf = float('-nan'), float('nan'), float('inf'), float('-inf')
632
633 a = [ninf, -5, 0, 5, inf]
634 assert (fmin(a, [ninf]*5) == [ninf]*5).all()
635 assert (fmin(a, [inf]*5) == a).all()
636 assert (fmin(a, [1]*5) == [ninf, -5, 0, 1, 1]).all()
637 assert fmin(nan, 0) == 0
638 assert fmin(0, nan) == 0
639 assert math.isnan(fmin(nan, nan))
640 # The numpy docs specify that the FIRST NaN should be used if both are NaN
641 # use copysign on both sides to sidestep bug in nan representaion
642 # on Microsoft win32
643 assert math.copysign(1., fmin(nnan, nan)) == math.copysign(1., nnan)
644
645 def test_fmod(self):
646 from numpy import fmod
647 import math
648
649 assert fmod(-1e-100, 1e100) == -1e-100
650 assert fmod(3, float('inf')) == 3
651 assert (fmod([-3, -2, -1, 1, 2, 3], 2) == [-1, 0, -1, 1, 0, 1]).all()
652 for v in [float('inf'), float('-inf'), float('nan'), float('-nan')]:
653 assert math.isnan(fmod(v, 2))
654
655 def test_mod(self):
656 from numpy import mod
657 assert mod(5, 3) == 2
658 assert mod(5, -3) == -1
659 assert mod(-5, 3) == 1
660 assert mod(-5, -3) == -2
661 assert mod(2.5, 1) == 0.5
662 assert mod(-1.5, 2) == 0.5
663
664 def test_minimum(self):
665 from numpy import array, minimum, nan, isnan
666
667 a = array([-5.0, -0.0, 1.0])
668 b = array([ 3.0, -2.0,-3.0])
669 c = minimum(a, b)
670 for i in range(3):
671 assert c[i] == min(a[i], b[i])
672
673 arg1 = array([0, nan, nan])
674 arg2 = array([nan, 0, nan])
675 assert isnan(minimum(arg1, arg2)).all()
676
677 def test_maximum(self):
678 from numpy import array, maximum, nan, isnan
679
680 a = array([-5.0, -0.0, 1.0])
681 b = array([ 3.0, -2.0,-3.0])
682 c = maximum(a, b)
683 for i in range(3):
684 assert c[i] == max(a[i], b[i])
685
686 arg1 = array([0, nan, nan])
687 arg2 = array([nan, 0, nan])
688 assert isnan(maximum(arg1, arg2)).all()
689
690 x = maximum(2, 3)
691 assert x == 3
692 assert isinstance(x, (int, long))
693
694 def test_complex_nan_extrema(self):
695 import math
696 import numpy as np
697 cnan = complex(0, np.nan)
698
699 b = np.minimum(1, cnan)
700 assert b.real == 0
701 assert math.isnan(b.imag)
702
703 b = np.maximum(1, cnan)
704 assert b.real == 0
705 assert math.isnan(b.imag)
706
707 b = np.fmin(1, cnan)
708 assert b.real == 1
709 assert b.imag == 0
710
711 b = np.fmax(1, cnan)
712 assert b.real == 1
713 assert b.imag == 0
714
715 def test_multiply(self):
716 from numpy import array, multiply, arange
717
718 a = array([-5.0, -0.0, 1.0])
719 b = array([ 3.0, -2.0,-3.0])
720 c = multiply(a, b)
721 for i in range(3):
722 assert c[i] == a[i] * b[i]
723
724 a = arange(15).reshape(5, 3)
725 assert(multiply.reduce(a) == array([0, 3640, 12320])).all()
726
727 def test_rint(self):
728 from numpy import array, dtype, rint, isnan
729 import sys
730
731 nnan, nan, inf, ninf = float('-nan'), float('nan'), float('inf'), float('-inf')
732
733 reference = array([ninf, -2., -1., -0., 0., 0., 0., 1., 2., inf])
734 a = array([ninf, -1.5, -1., -0.5, -0., 0., 0.5, 1., 1.5, inf])
735 b = rint(a)
736 for i in range(len(a)):
737 assert b[i] == reference[i]
738 assert isnan(rint(nan))
739 assert isnan(rint(nnan))
740
741 assert rint(complex(inf, 1.5)) == complex(inf, 2.)
742 assert rint(complex(0.5, inf)) == complex(0., inf)
743
744 assert rint(sys.maxint) > 0.0
745
746 def test_sign(self):
747 from numpy import array, sign, dtype
748
749 reference = [-1.0, 0.0, 0.0, 1.0]
750 a = array([-5.0, -0.0, 0.0, 6.0])
751 b = sign(a)
752 for i in range(4):
753 assert b[i] == reference[i]
754
755 a = sign(array(range(-5, 5)))
756 ref = [-1, -1, -1, -1, -1, 0, 1, 1, 1, 1]
757 for i in range(10):
758 assert a[i] == ref[i]
759
760 a = sign(array([10+10j, -10+10j, 0+10j, 0-10j, 0+0j, 0-0j], dtype=complex))
761 ref = [1, -1, 1, -1, 0, 0]
762 assert (a == ref).all()
763
764 def test_signbit(self):
765 from numpy import signbit, add, copysign, nan
766 assert signbit(add.identity) == False
767 assert (signbit([0, 0.0, 1, 1.0, float('inf')]) ==
768 [False, False, False, False, False]).all()
769 assert (signbit([-0, -0.0, -1, -1.0, float('-inf')]) ==
770 [False, True, True, True, True]).all()
771 assert (signbit([copysign(nan, 1), copysign(nan, -1)]) ==
772 [False, True]).all()
773
774 def test_reciprocal(self):
775 from numpy import array, reciprocal
776 inf = float('inf')
777 nan = float('nan')
778 reference = [-0.2, inf, -inf, 2.0, nan]
779 a = array([-5.0, 0.0, -0.0, 0.5, nan])
780 b = reciprocal(a)
781 for i in range(4):
782 assert b[i] == reference[i]
783
784 for dtype in 'bBhHiIlLqQ':
785 a = array([-2, -1, 0, 1, 2], dtype)
786 reference = [0, -1, 0, 1, 0]
787 dtype = a.dtype.name
788 if dtype[0] == 'u':
789 reference[1] = 0
790 elif dtype == 'int32':
791 reference[2] = -2147483648
792 elif dtype == 'int64':
793 reference[2] = -9223372036854775808
794 b = reciprocal(a)
795 assert (b == reference).all()
796
797 def test_subtract(self):
798 from numpy import array, subtract
799
800 a = array([-5.0, -0.0, 1.0])
801 b = array([ 3.0, -2.0,-3.0])
802 c = subtract(a, b)
803 for i in range(3):
804 assert c[i] == a[i] - b[i]
805
806 def test_floorceiltrunc(self):
807 from numpy import array, floor, ceil, trunc
808 import math
809 ninf, inf = float("-inf"), float("inf")
810 a = array([ninf, -1.4, -1.5, -1.0, 0.0, 1.0, 1.4, 0.5, inf])
811 assert ([ninf, -2.0, -2.0, -1.0, 0.0, 1.0, 1.0, 0.0, inf] == floor(a)).all()
812 assert ([ninf, -1.0, -1.0, -1.0, 0.0, 1.0, 2.0, 1.0, inf] == ceil(a)).all()
813 assert ([ninf, -1.0, -1.0, -1.0, 0.0, 1.0, 1.0, 0.0, inf] == trunc(a)).all()
814
815 def test_floorceiltrunc_nan(self):
816 from numpy import floor, ceil, trunc
817 import math
818 assert all([math.isnan(f(float("nan"))) for f in floor, ceil, trunc])
819 assert all([math.copysign(1, f(abs(float("nan")))) == 1 for f in floor, ceil, trunc])
820
821 def test_floorceiltrunc_nan_negative(self):
822 # self.machine comes from test_base.py
823 if self.machine.startswith('riscv'):
824 py.test.skip('riscv floor/ceil/trunc canonicalizes nan to '
825 'positive nan')
826 from numpy import floor, ceil, trunc
827 import math
828 assert all([math.copysign(1, f(-abs(float("nan")))) == -1 for f in floor, ceil, trunc])
829
830 def test_round(self):
831 from numpy import array, dtype
832 ninf, inf = float("-inf"), float("inf")
833 a = array([ninf, -1.4, -1.5, -1.0, 0.0, 1.0, 1.4, 0.5, inf])
834 assert ([ninf, -1.0, -2.0, -1.0, 0.0, 1.0, 1.0, 0.0, inf] == a.round()).all()
835 i = array([-1000, -100, -1, 0, 1, 111, 1111, 11111], dtype=int)
836 assert (i == i.round()).all()
837 assert (i.round(decimals=4) == i).all()
838 assert (i.round(decimals=-4) == [0, 0, 0, 0, 0, 0, 0, 10000]).all()
839 b = array([True, False], dtype=bool)
840 bround = b.round()
841 assert (bround == [1., 0.]).all()
842 assert bround.dtype is dtype('float16')
843 c = array([10.5+11.5j, -15.2-100.3456j, 0.2343+11.123456j])
844 assert (c.round(0) == [10.+12.j, -15-100j, 0+11j]).all()
845
846 def test_copysign(self):
847 from numpy import array, copysign
848
849 reference = [5.0, -0.0, 0.0, -6.0]
850 a = array([-5.0, 0.0, 0.0, 6.0])
851 b = array([5.0, -0.0, 3.0, -6.0])
852 c = copysign(a, b)
853 for i in range(4):
854 assert c[i] == reference[i]
855
856 b = array([True, True, True, True], dtype=bool)
857 c = copysign(a, b)
858 for i in range(4):
859 assert c[i] == abs(a[i])
860
861 def test_exp(self):
862 import math
863 from numpy import array, exp
864
865 a = array([-5.0, -0.0, 0.0, 12345678.0, float("inf"),
866 -float('inf'), -12343424.0])
867 b = exp(a)
868 for i in range(len(a)):
869 try:
870 res = math.exp(a[i])
871 except OverflowError:
872 res = float('inf')
873 assert b[i] == res
874
875 def test_exp2(self):
876 import math
877 from numpy import array, exp2
878 inf = float('inf')
879 ninf = -float('inf')
880 nan = float('nan')
881
882 a = array([-5.0, -0.0, 0.0, 2, 12345678.0, inf, ninf, -12343424.0])
883 b = exp2(a)
884 for i in range(len(a)):
885 try:
886 res = 2 ** a[i]
887 except OverflowError:
888 res = float('inf')
889 assert b[i] == res
890
891 assert exp2(3) == 8
892 assert math.isnan(exp2(nan))
893
894 def test_expm1(self):
895 import math, cmath
896 from numpy import array, expm1
897 inf = float('inf')
898 ninf = -float('inf')
899 nan = float('nan')
900
901 a = array([-5.0, -0.0, 0.0, 12345678.0, float("inf"),
902 -float('inf'), -12343424.0])
903 b = expm1(a)
904 for i in range(4):
905 try:
906 res = math.exp(a[i]) - 1
907 except OverflowError:
908 res = float('inf')
909 assert b[i] == res
910
911 assert expm1(1e-50) == 1e-50
912
913 def test_sin(self):
914 import math
915 from numpy import array, sin
916
917 a = array([0, 1, 2, 3, math.pi, math.pi*1.5, math.pi*2])
918 b = sin(a)
919 for i in range(len(a)):
920 assert b[i] == math.sin(a[i])
921
922 a = sin(array([True, False], dtype=bool))
923 assert abs(a[0] - sin(1)) < 1e-3 # a[0] will be very imprecise
924 assert a[1] == 0.0
925
926 def test_cos(self):
927 import math
928 from numpy import array, cos
929
930 a = array([0, 1, 2, 3, math.pi, math.pi*1.5, math.pi*2])
931 b = cos(a)
932 for i in range(len(a)):
933 assert b[i] == math.cos(a[i])
934
935 def test_tan(self):
936 import math
937 from numpy import array, tan
938
939 a = array([0, 1, 2, 3, math.pi, math.pi*1.5, math.pi*2])
940 b = tan(a)
941 for i in range(len(a)):
942 assert b[i] == math.tan(a[i])
943
944 def test_arcsin(self):
945 import math
946 from numpy import array, arcsin
947
948 a = array([-1, -0.5, -0.33, 0, 0.33, 0.5, 1])
949 b = arcsin(a)
950 for i in range(len(a)):
951 assert b[i] == math.asin(a[i])
952
953 a = array([-10, -1.5, -1.01, 1.01, 1.5, 10, float('nan'), float('inf'), float('-inf')])
954 b = arcsin(a)
955 for f in b:
956 assert math.isnan(f)
957
958 def test_arccos(self):
959 import math
960 from numpy import array, arccos
961
962 a = array([-1, -0.5, -0.33, 0, 0.33, 0.5, 1])
963 b = arccos(a)
964 for i in range(len(a)):
965 assert b[i] == math.acos(a[i])
966
967 a = array([-10, -1.5, -1.01, 1.01, 1.5, 10, float('nan'), float('inf'), float('-inf')])
968 b = arccos(a)
969 for f in b:
970 assert math.isnan(f)
971
972 def test_arctan(self):
973 import math
974 from numpy import array, arctan
975
976 a = array([-3, -2, -1, 0, 1, 2, 3, float('inf'), float('-inf')])
977 b = arctan(a)
978 for i in range(len(a)):
979 assert b[i] == math.atan(a[i])
980
981 a = array([float('nan')])
982 b = arctan(a)
983 assert math.isnan(b[0])
984
985 def test_arctan2(self):
986 import math
987 from numpy import array, arctan2
988
989 # From the numpy documentation
990 assert (
991 arctan2(
992 [0., 0., 1., -1., float('inf'), float('inf')],
993 [0., -0., float('inf'), float('inf'), float('inf'), float('-inf')]) ==
994 [0., math.pi, 0., -0., math.pi/4, 3*math.pi/4]).all()
995
996 a = array([float('nan')])
997 b = arctan2(a, 0)
998 assert math.isnan(b[0])
999
1000 def test_sinh(self):
1001 import math
1002 from numpy import array, sinh
1003
1004 a = array([-1, 0, 1, float('inf'), float('-inf')])
1005 b = sinh(a)
1006 for i in range(len(a)):
1007 assert b[i] == math.sinh(a[i])
1008
1009 def test_cosh(self):
1010 import math
1011 from numpy import array, cosh
1012
1013 a = array([-1, 0, 1, float('inf'), float('-inf')])
1014 b = cosh(a)
1015 for i in range(len(a)):
1016 assert b[i] == math.cosh(a[i])
1017
1018 def test_tanh(self):
1019 import math
1020 from numpy import array, tanh
1021
1022 a = array([-1, 0, 1, float('inf'), float('-inf')])
1023 b = tanh(a)
1024 for i in range(len(a)):
1025 assert b[i] == math.tanh(a[i])
1026
1027 def test_arcsinh(self):
1028 import math
1029 from numpy import arcsinh
1030
1031 for v in [float('inf'), float('-inf'), 1.0, math.e]:
1032 assert math.asinh(v) == arcsinh(v)
1033 assert math.isnan(arcsinh(float("nan")))
1034
1035 def test_arccosh(self):
1036 import math
1037 from numpy import arccosh
1038
1039 for v in [1.0, 1.1, 2]:
1040 assert math.acosh(v) == arccosh(v)
1041 for v in [-1.0, 0, .99]:
1042 assert math.isnan(arccosh(v))
1043
1044 def test_arctanh(self):
1045 import math
1046 from numpy import arctanh
1047
1048 for v in [.99, .5, 0, -.5, -.99]:
1049 assert math.atanh(v) == arctanh(v)
1050 for v in [2.0, -2.0]:
1051 assert math.isnan(arctanh(v))
1052 for v in [1.0, -1.0]:
1053 assert arctanh(v) == math.copysign(float("inf"), v)
1054
1055 def test_sqrt(self):
1056 import math
1057 from numpy import sqrt
1058
1059 nan, inf = float("nan"), float("inf")
1060 data = [1, 2, 3, inf]
1061 results = [math.sqrt(1), math.sqrt(2), math.sqrt(3), inf]
1062 assert (sqrt(data) == results).all()
1063 assert math.isnan(sqrt(-1))
1064 assert math.isnan(sqrt(nan))
1065
1066 def test_square(self):
1067 import math
1068 from numpy import square
1069
1070 nan, inf, ninf = float("nan"), float("inf"), float("-inf")
1071
1072 assert math.isnan(square(nan))
1073 assert math.isinf(square(inf))
1074 assert math.isinf(square(ninf))
1075 assert square(ninf) > 0
1076 assert [square(x) for x in range(-5, 5)] == [x*x for x in range(-5, 5)]
1077 assert math.isinf(square(1e300))
1078
1079 def test_radians(self):
1080 import math
1081 from numpy import radians, array
1082 a = array([
1083 -181, -180, -179,
1084 181, 180, 179,
1085 359, 360, 361,
1086 400, -1, 0, 1,
1087 float('inf'), float('-inf')])
1088 b = radians(a)
1089 for i in range(len(a)):
1090 assert b[i] == math.radians(a[i])
1091
1092 def test_deg2rad(self):
1093 import math
1094 from numpy import deg2rad, array
1095 a = array([
1096 -181, -180, -179,
1097 181, 180, 179,
1098 359, 360, 361,
1099 400, -1, 0, 1,
1100 float('inf'), float('-inf')])
1101 b = deg2rad(a)
1102 for i in range(len(a)):
1103 assert b[i] == math.radians(a[i])
1104
1105 def test_degrees(self):
1106 import math
1107 from numpy import degrees, array
1108 a = array([
1109 -181, -180, -179,
1110 181, 180, 179,
1111 359, 360, 361,
1112 400, -1, 0, 1,
1113 float('inf'), float('-inf')])
1114 b = degrees(a)
1115 for i in range(len(a)):
1116 assert b[i] == math.degrees(a[i])
1117
1118 def test_rad2deg(self):
1119 import math
1120 from numpy import rad2deg, array
1121 a = array([
1122 -181, -180, -179,
1123 181, 180, 179,
1124 359, 360, 361,
1125 400, -1, 0, 1,
1126 float('inf'), float('-inf')])
1127 b = rad2deg(a)
1128 for i in range(len(a)):
1129 assert b[i] == math.degrees(a[i])
1130
1131 def test_reduce_errors(self):
1132 from numpy import sin, add, maximum, zeros
1133
1134 raises(ValueError, sin.reduce, [1, 2, 3])
1135 assert add.reduce(1) == 1
1136
1137 assert list(maximum.reduce(zeros((2, 0)), axis=0)) == []
1138 exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=None)
1139 assert exc.value[0] == ('zero-size array to reduction operation '
1140 'maximum which has no identity')
1141 exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=1)
1142 assert exc.value[0] == ('zero-size array to reduction operation '
1143 'maximum which has no identity')
1144
1145 a = zeros((2, 2)) + 1
1146 assert (add.reduce(a, axis=1) == [2, 2]).all()
1147 assert (add.reduce(a, axis=(1,)) == [2, 2]).all()
1148 exc = raises(ValueError, add.reduce, a, axis=2)
1149 assert exc.value[0] == "'axis' entry is out of bounds"
1150
1151 def test_reduce_1d(self):
1152 import numpy as np
1153 from numpy import array, add, maximum, less, float16, complex64
1154
1155 assert less.reduce([5, 4, 3, 2, 1])
1156 assert add.reduce([1, 2, 3]) == 6
1157 assert maximum.reduce([1]) == 1
1158 assert maximum.reduce([1, 2, 3]) == 3
1159 raises(ValueError, maximum.reduce, [])
1160
1161 assert add.reduce(array([True, False] * 200)) == 200
1162 assert add.reduce(array([True, False] * 200, dtype='int8')) == 200
1163 assert add.reduce(array([True, False] * 200), dtype='int8') == -56
1164 assert type(add.reduce(array([True, False] * 200, dtype='float16'))) is float16
1165 assert type(add.reduce(array([True, False] * 200, dtype='complex64'))) is complex64
1166
1167 for dtype in ['bool', 'int']:
1168 assert np.equal.reduce([1, 2], dtype=dtype) == True
1169 assert np.equal.reduce([1, 2, 0], dtype=dtype) == False
1170
1171 def test_reduce_axes(self):
1172 import numpy as np
1173 a = np.arange(24).reshape(2, 3, 4)
1174 b = np.add.reduce(a, axis=(0, 1))
1175 assert b.shape == (4,)
1176 assert (b == [60, 66, 72, 78]).all()
1177
1178 def test_reduce_fmax(self):
1179 import numpy as np
1180 assert np.fmax.reduce(np.arange(11).astype('b')) == 10
1181
1182 def test_reduceND(self):
1183 from numpy import add, arange
1184 a = arange(12).reshape(3, 4)
1185 assert (add.reduce(a, 0) == [12, 15, 18, 21]).all()
1186 assert (add.reduce(a, 1) == [6.0, 22.0, 38.0]).all()
1187 raises(ValueError, add.reduce, a, 2)
1188
1189 def test_reduce_keepdims(self):
1190 from numpy import add, arange
1191 a = arange(12).reshape(3, 4)
1192 b = add.reduce(a, 0, keepdims=True)
1193 assert b.shape == (1, 4)
1194 assert (add.reduce(a, 0, keepdims=True) == [12, 15, 18, 21]).all()
1195 assert (add.reduce(a, 0, None, None, True) == [12, 15, 18, 21]).all()
1196
1197 def test_bitwise(self):
1198 from numpy import bitwise_and, bitwise_or, bitwise_xor, arange, array
1199 a = arange(6).reshape(2, 3)
1200 assert (a & 1 == [[0, 1, 0], [1, 0, 1]]).all()
1201 assert (a & 1 == bitwise_and(a, 1)).all()
1202 assert (a | 1 == [[1, 1, 3], [3, 5, 5]]).all()
1203 assert (a | 1 == bitwise_or(a, 1)).all()
1204 assert (a ^ 3 == bitwise_xor(a, 3)).all()
1205 raises(TypeError, 'array([1.0]) & 1')
1206
1207 def test_unary_bitops(self):
1208 from numpy import bitwise_not, invert, array
1209 a = array([1, 2, 3, 4])
1210 assert (~a == [-2, -3, -4, -5]).all()
1211 assert (bitwise_not(a) == ~a).all()
1212 assert (invert(a) == ~a).all()
1213 assert invert(True) == False
1214 assert invert(False) == True
1215
1216 def test_shift(self):
1217 from numpy import left_shift, right_shift, dtype
1218
1219 assert (left_shift([5, 1], [2, 13]) == [20, 2**13]).all()
1220 assert (right_shift(10, range(5)) == [10, 5, 2, 1, 0]).all()
1221 bool_ = dtype('bool').type
1222 assert left_shift(bool(1), 3) == left_shift(1, 3)
1223 assert right_shift(bool(1), 3) == right_shift(1, 3)
1224
1225 def test_comparisons(self):
1226 import operator
1227 from numpy import (equal, not_equal, less, less_equal, greater,
1228 greater_equal, arange)
1229
1230 for ufunc, func in [
1231 (equal, operator.eq),
1232 (not_equal, operator.ne),
1233 (less, operator.lt),
1234 (less_equal, operator.le),
1235 (greater, operator.gt),
1236 (greater_equal, operator.ge),
1237 ]:
1238 for a, b in [
1239 (3, 3),
1240 (3, 4),
1241 (4, 3),
1242 (3.0, 3.0),
1243 (3.0, 3.5),
1244 (3.5, 3.0),
1245 (3.0, 3),
1246 (3, 3.0),
1247 (3.5, 3),
1248 (3, 3.5),
1249 ]:
1250 assert ufunc(a, b) == func(a, b)
1251 c = arange(10)
1252 val = c == 'abcdefg'
1253 assert val == False
1254
1255 def test_count_nonzero(self):
1256 from numpy import count_nonzero
1257 assert count_nonzero(0) == 0
1258 assert count_nonzero(1) == 1
1259 assert count_nonzero([]) == 0
1260 assert count_nonzero([1, 2, 0]) == 2
1261 assert count_nonzero([[1, 2, 0], [1, 0, 2]]) == 4
1262
1263 def test_true_divide_2(self):
1264 from numpy import arange, array, true_divide
1265 assert (true_divide(arange(3), array([2, 2, 2])) == array([0, 0.5, 1])).all()
1266
1267 def test_isnan_isinf(self):
1268 from numpy import isnan, isinf, array, dtype
1269 assert isnan(float('nan'))
1270 assert not isnan(3)
1271 assert not isinf(3)
1272 assert isnan(dtype('float64').type(float('nan')))
1273 assert not isnan(3)
1274 assert isinf(float('inf'))
1275 assert not isnan(3.5)
1276 assert not isinf(3.5)
1277 assert not isnan(float('inf'))
1278 assert not isinf(float('nan'))
1279 assert (isnan(array([0.2, float('inf'), float('nan')])) == [False, False, True]).all()
1280 assert (isinf(array([0.2, float('inf'), float('nan')])) == [False, True, False]).all()
1281 assert isinf(array([0.2])).dtype.kind == 'b'
1282
1283 def test_logical_ops(self):
1284 from numpy import logical_and, logical_or, logical_xor, logical_not
1285
1286 assert (logical_and([True, False , True, True], [1, 1, 3, 0])
1287 == [True, False, True, False]).all()
1288 assert (logical_or([True, False, True, False], [1, 2, 0, 0])
1289 == [True, True, True, False]).all()
1290 assert (logical_xor([True, False, True, False], [1, 2, 0, 0])
1291 == [False, True, True, False]).all()
1292 assert (logical_not([True, False]) == [False, True]).all()
1293 assert logical_and.reduce([1.,1.]) == True
1294
1295 def test_logn(self):
1296 import math
1297 from numpy import log, log2, log10
1298
1299 for log_func, base in [(log, math.e), (log2, 2), (log10, 10)]:
1300 for v in [float('-nan'), float('-inf'), -1, float('nan')]:
1301 assert math.isnan(log_func(v))
1302 for v in [-0.0, 0.0]:
1303 assert log_func(v) == float("-inf")
1304 assert log_func(float('inf')) == float('inf')
1305 assert (log_func([1, base]) == [0, 1]).all()
1306
1307 def test_log1p(self):
1308 import math
1309 from numpy import log1p
1310
1311 for v in [float('-nan'), float('-inf'), -2, float('nan')]:
1312 assert math.isnan(log1p(v))
1313 for v in [-1]:
1314 assert log1p(v) == float("-inf")
1315 assert log1p(float('inf')) == float('inf')
1316 assert (log1p([0, 1e-50, math.e - 1]) == [0, 1e-50, 1]).all()
1317
1318 def test_power_float(self):
1319 import math
1320 from numpy import power, array
1321 a = array([1., 2., 3.])
1322 b = power(a, 3)
1323 for i in range(len(a)):
1324 assert b[i] == a[i] ** 3
1325
1326 a = array([1., 2., 3.])
1327 b = array([1., 2., 3.])
1328 c = power(a, b)
1329 for i in range(len(a)):
1330 assert c[i] == a[i] ** b[i]
1331
1332 assert power(2, float('inf')) == float('inf')
1333 assert power(float('inf'), float('inf')) == float('inf')
1334 assert power(12345.0, 12345.0) == float('inf')
1335 assert power(-12345.0, 12345.0) == float('-inf')
1336 assert power(-12345.0, 12346.0) == float('inf')
1337 assert math.isnan(power(-1, 1.1))
1338 assert math.isnan(power(-1, -1.1))
1339 assert power(-2.0, -1) == -0.5
1340 assert power(-2.0, -2) == 0.25
1341 assert power(12345.0, -12345.0) == 0
1342 assert power(float('-inf'), 2) == float('inf')
1343 assert power(float('-inf'), 2.5) == float('inf')
1344 assert power(float('-inf'), 3) == float('-inf')
1345
1346 def test_power_int(self):
1347 import math
1348 from numpy import power, array
1349 a = array([1, 2, 3])
1350 b = power(a, 3)
1351 for i in range(len(a)):
1352 assert b[i] == a[i] ** 3
1353
1354 a = array([1, 2, 3])
1355 b = array([1, 2, 3])
1356 c = power(a, b)
1357 for i in range(len(a)):
1358 assert c[i] == a[i] ** b[i]
1359
1360 # assert power(12345, 12345) == -9223372036854775808
1361 # assert power(-12345, 12345) == -9223372036854775808
1362 # assert power(-12345, 12346) == -9223372036854775808
1363 assert power(2, 0) == 1
1364 assert power(2, -1) == 0
1365 assert power(2, -2) == 0
1366 assert power(-2, -1) == 0
1367 assert power(-2, -2) == 0
1368 assert power(12345, -12345) == 0
1369
1370 def test_floordiv(self):
1371 from numpy import floor_divide, array
1372 import math
1373 a = array([1., 2., 3., 4., 5., 6., 6.01])
1374 b = floor_divide(a, 2.5)
1375 for i in range(len(a)):
1376 assert b[i] == a[i] // 2.5
1377
1378 a = array([10+10j, -15-100j, 0+10j], dtype=complex)
1379 b = floor_divide(a, 2.5)
1380 for i in range(len(a)):
1381 assert b[i] == a[i] // 2.5
1382 b = floor_divide(a, 2.5+3j)
1383 #numpy returns (a.real*b.real + a.imag*b.imag) / abs(b)**2
1384 expect = [3., -23., 1.]
1385 for i in range(len(a)):
1386 assert b[i] == expect[i]
1387 b = floor_divide(a[0], 0.)
1388 assert math.isnan(b.real)
1389 assert b.imag == 0.
1390
1391 def test_logaddexp(self):
1392 import math
1393 import sys
1394 float_max, float_min = sys.float_info.max, sys.float_info.min
1395 from numpy import logaddexp
1396
1397 # From the numpy documentation
1398 prob1 = math.log(1e-50)
1399 prob2 = math.log(2.5e-50)
1400 prob12 = logaddexp(prob1, prob2)
1401 assert math.fabs(-113.87649168120691 - prob12) < 0.000000000001
1402
1403 assert logaddexp(0, 0) == math.log(2)
1404 assert logaddexp(float('-inf'), 0) == 0
1405 assert logaddexp(float_max, float_max) == float_max
1406 assert logaddexp(float_min, float_min) == math.log(2)
1407
1408 assert math.isnan(logaddexp(float('nan'), 1))
1409 assert math.isnan(logaddexp(1, float('nan')))
1410 assert math.isnan(logaddexp(float('nan'), float('inf')))
1411 assert math.isnan(logaddexp(float('inf'), float('nan')))
1412 assert logaddexp(float('-inf'), float('-inf')) == float('-inf')
1413 assert logaddexp(float('-inf'), float('inf')) == float('inf')
1414 assert logaddexp(float('inf'), float('-inf')) == float('inf')
1415 assert logaddexp(float('inf'), float('inf')) == float('inf')
1416
1417 def test_logaddexp2(self):
1418 import math
1419 import sys
1420 float_max, float_min = sys.float_info.max, sys.float_info.min
1421 from numpy import logaddexp2
1422 log2 = math.log(2)
1423
1424 # From the numpy documentation
1425 prob1 = math.log(1e-50) / log2
1426 prob2 = math.log(2.5e-50) / log2
1427 prob12 = logaddexp2(prob1, prob2)
1428 assert math.fabs(-164.28904982231052 - prob12) < 0.000000000001
1429
1430 assert logaddexp2(0, 0) == 1
1431 assert logaddexp2(float('-inf'), 0) == 0
1432 assert logaddexp2(float_max, float_max) == float_max
1433 assert logaddexp2(float_min, float_min) == 1.0
1434
1435 assert math.isnan(logaddexp2(float('nan'), 1))
1436 assert math.isnan(logaddexp2(1, float('nan')))
1437 assert math.isnan(logaddexp2(float('nan'), float('inf')))
1438 assert math.isnan(logaddexp2(float('inf'), float('nan')))
1439 assert logaddexp2(float('-inf'), float('-inf')) == float('-inf')
1440 assert logaddexp2(float('-inf'), float('inf')) == float('inf')
1441 assert logaddexp2(float('inf'), float('-inf')) == float('inf')
1442 assert logaddexp2(float('inf'), float('inf')) == float('inf')
1443
1444 def test_accumulate(self):
1445 from numpy import add, subtract, multiply, divide, arange, dtype
1446 assert (add.accumulate([2, 3, 5]) == [2, 5, 10]).all()
1447 assert (multiply.accumulate([2, 3, 5]) == [2, 6, 30]).all()
1448 a = arange(4).reshape(2,2)
1449 b = add.accumulate(a, axis=0)
1450 assert (b == [[0, 1], [2, 4]]).all()
1451 b = add.accumulate(a, 1)
1452 assert (b == [[0, 1], [2, 5]]).all()
1453 b = add.accumulate(a) #default axis is 0
1454 assert (b == [[0, 1], [2, 4]]).all()
1455 # dtype
1456 a = arange(0, 3, 0.5).reshape(2, 3)
1457 b = add.accumulate(a, dtype=int, axis=1)
1458 assert (b == [[0, 0, 1], [1, 3, 5]]).all()
1459 assert b.dtype == int
1460 assert add.accumulate([True]*200)[-1] == 200
1461 assert add.accumulate([True]*200).dtype == dtype('int')
1462 assert subtract.accumulate([True]*200).dtype == dtype('bool')
1463 assert divide.accumulate([True]*200).dtype == dtype('int8')
1464
1465 def test_accumulate_shapes(self):
1466 import numpy as np
1467 a = np.arange(6).reshape(2, 1, 3)
1468 assert np.add.accumulate(a).shape == (2, 1, 3)
1469 raises(ValueError, "np.add.accumulate(a, out=np.zeros((3, 1, 3)))")
1470 raises(ValueError, "np.add.accumulate(a, out=np.zeros((2, 3)))")
1471 raises(ValueError, "np.add.accumulate(a, out=np.zeros((2, 3, 1)))")
1472 b = np.zeros((2, 1, 3))
1473 np.add.accumulate(a, out=b, axis=2)
1474 assert b[0, 0, 2] == 3
1475
1476 def test_accumulate_shapes_2(self):
1477 import sys
1478 if '__pypy__' not in sys.builtin_module_names:
1479 skip('PyPy-specific behavior in np.ufunc.accumulate')
1480 import numpy as np
1481 a = np.arange(6).reshape(2, 1, 3)
1482 raises(ValueError, "np.add.accumulate(a, out=np.zeros((2, 1, 3, 2)))")
1483
1484
1485 def test_noncommutative_reduce_accumulate(self):
1486 import numpy as np
1487 tosubtract = np.arange(5)
1488 todivide = np.array([2.0, 0.5, 0.25])
1489 assert np.subtract.reduce(tosubtract) == -10
1490 assert np.divide.reduce(todivide) == 16.0
1491 assert (np.subtract.accumulate(tosubtract) ==
1492 np.array([0, -1, -3, -6, -10])).all()
1493 assert (np.divide.accumulate(todivide) ==
1494 np.array([2., 4., 16.])).all()
1495
1496 def test_outer(self):
1497 import numpy as np
1498 c = np.multiply.outer([1, 2, 3], [4, 5, 6])
1499 assert c.shape == (3, 3)
1500 assert (c ==[[ 4, 5, 6],
1501 [ 8, 10, 12],
1502 [12, 15, 18]]).all()
1503 A = np.array([[1, 2, 3], [4, 5, 6]])
1504 B = np.array([[1, 2, 3, 4]])
1505 c = np.multiply.outer(A, B)
1506 assert c.shape == (2, 3, 1, 4)
1507 assert (c == [[[[ 1, 2, 3, 4]],
1508 [[ 2, 4, 6, 8]],
1509 [[ 3, 6, 9, 12]]],
1510 [[[ 4, 8, 12, 16]],
1511 [[ 5, 10, 15, 20]],
1512 [[ 6, 12, 18, 24]]]]).all()
1513 exc = raises(ValueError, np.absolute.outer, [-1, -2])
1514 assert exc.value[0] == 'outer product only supported for binary functions'
1515
1516 def test_promotion(self):
1517 import numpy as np
1518 assert np.add(np.float16(0), np.int16(0)).dtype == np.float32
1519 assert np.add(np.float16(0), np.int32(0)).dtype == np.float64
1520 assert np.add(np.float16(0), np.int64(0)).dtype == np.float64
1521 assert np.add(np.float16(0), np.float32(0)).dtype == np.float32
1522 assert np.add(np.float16(0), np.float64(0)).dtype == np.float64
1523 assert np.add(np.float16(0), np.longdouble(0)).dtype == np.longdouble
1524 assert np.add(np.float16(0), np.complex64(0)).dtype == np.complex64
1525 assert np.add(np.float16(0), np.complex128(0)).dtype == np.complex128
1526 assert np.add(np.zeros(5, dtype=np.int8), 257).dtype == np.int16
1527 assert np.subtract(np.zeros(5, dtype=np.int8), 257).dtype == np.int16
1528 assert np.divide(np.zeros(5, dtype=np.int8), 257).dtype == np.int16
1529
1530 def test_add_doc(self):
1531 import sys
1532 if '__pypy__' not in sys.builtin_module_names:
1533 skip('cpython sets docstrings differently')
1534 try:
1535 from numpy import set_docstring
1536 except ImportError:
1537 from _numpypy.multiarray import set_docstring
1538 import numpy as np
1539 assert np.add.__doc__ is None
1540 add_doc = np.add.__doc__
1541 ufunc_doc = np.ufunc.__doc__
1542 try:
1543 np.add.__doc__ = 'np.add'
1544 assert np.add.__doc__ == 'np.add'
1545 # Test for interferences between ufunc objects and their class
1546 set_docstring(np.ufunc, 'np.ufunc')
1547 assert np.ufunc.__doc__ == 'np.ufunc'
1548 assert np.add.__doc__ == 'np.add'
1549 finally:
1550 set_docstring(np.ufunc, ufunc_doc)
1551 np.add.__doc__ = add_doc