codekingpro/portable-devtools
115k
1import inspect
2import itertools
3import math
4import platform
5import sys
6import warnings
7from decimal import Decimal
8
9import pytest
10from hypothesis import given, strategies as st
11from hypothesis.extra import numpy as hynp
12
13import numpy as np
14from numpy import ma
15from numpy._core import sctypes
16from numpy._core._rational_tests import rational
17from numpy._core.numerictypes import obj2sctype
18from numpy.exceptions import AxisError
19from numpy.random import rand, randint, randn
20from numpy.testing import (
21 HAS_REFCOUNT,
22 IS_PYPY,
23 IS_WASM,
24 assert_,
25 assert_almost_equal,
26 assert_array_almost_equal,
27 assert_array_equal,
28 assert_array_max_ulp,
29 assert_equal,
30 assert_raises,
31 assert_raises_regex,
32)
33
34
35class TestResize:
36 def test_copies(self):
37 A = np.array([[1, 2], [3, 4]])
38 Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
39 assert_equal(np.resize(A, (2, 4)), Ar1)
40
41 Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
42 assert_equal(np.resize(A, (4, 2)), Ar2)
43
44 Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])
45 assert_equal(np.resize(A, (4, 3)), Ar3)
46
47 def test_repeats(self):
48 A = np.array([1, 2, 3])
49 Ar1 = np.array([[1, 2, 3, 1], [2, 3, 1, 2]])
50 assert_equal(np.resize(A, (2, 4)), Ar1)
51
52 Ar2 = np.array([[1, 2], [3, 1], [2, 3], [1, 2]])
53 assert_equal(np.resize(A, (4, 2)), Ar2)
54
55 Ar3 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
56 assert_equal(np.resize(A, (4, 3)), Ar3)
57
58 def test_zeroresize(self):
59 A = np.array([[1, 2], [3, 4]])
60 Ar = np.resize(A, (0,))
61 assert_array_equal(Ar, np.array([]))
62 assert_equal(A.dtype, Ar.dtype)
63
64 Ar = np.resize(A, (0, 2))
65 assert_equal(Ar.shape, (0, 2))
66
67 Ar = np.resize(A, (2, 0))
68 assert_equal(Ar.shape, (2, 0))
69
70 def test_reshape_from_zero(self):
71 # See also gh-6740
72 A = np.zeros(0, dtype=[('a', np.float32)])
73 Ar = np.resize(A, (2, 1))
74 assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))
75 assert_equal(A.dtype, Ar.dtype)
76
77 def test_negative_resize(self):
78 A = np.arange(0, 10, dtype=np.float32)
79 new_shape = (-10, -1)
80 with pytest.raises(ValueError, match=r"negative"):
81 np.resize(A, new_shape=new_shape)
82
83 def test_unsigned_resize(self):
84 # ensure unsigned integer sizes don't lead to underflows
85 for dt_pair in [(np.int32, np.uint32), (np.int64, np.uint64)]:
86 arr = np.array([[23, 95], [66, 37]])
87 assert_array_equal(np.resize(arr, dt_pair[0](1)),
88 np.resize(arr, dt_pair[1](1)))
89
90 def test_subclass(self):
91 class MyArray(np.ndarray):
92 __array_priority__ = 1.
93
94 my_arr = np.array([1]).view(MyArray)
95 assert type(np.resize(my_arr, 5)) is MyArray
96 assert type(np.resize(my_arr, 0)) is MyArray
97
98 my_arr = np.array([]).view(MyArray)
99 assert type(np.resize(my_arr, 5)) is MyArray
100
101
102class TestNonarrayArgs:
103 # check that non-array arguments to functions wrap them in arrays
104 def test_choose(self):
105 choices = [[0, 1, 2],
106 [3, 4, 5],
107 [5, 6, 7]]
108 tgt = [5, 1, 5]
109 a = [2, 0, 1]
110
111 out = np.choose(a, choices)
112 assert_equal(out, tgt)
113
114 def test_clip(self):
115 arr = [-1, 5, 2, 3, 10, -4, -9]
116 out = np.clip(arr, 2, 7)
117 tgt = [2, 5, 2, 3, 7, 2, 2]
118 assert_equal(out, tgt)
119
120 def test_compress(self):
121 arr = [[0, 1, 2, 3, 4],
122 [5, 6, 7, 8, 9]]
123 tgt = [[5, 6, 7, 8, 9]]
124 out = np.compress([0, 1], arr, axis=0)
125 assert_equal(out, tgt)
126
127 def test_count_nonzero(self):
128 arr = [[0, 1, 7, 0, 0],
129 [3, 0, 0, 2, 19]]
130 tgt = np.array([2, 3])
131 out = np.count_nonzero(arr, axis=1)
132 assert_equal(out, tgt)
133
134 def test_diagonal(self):
135 a = [[0, 1, 2, 3],
136 [4, 5, 6, 7],
137 [8, 9, 10, 11]]
138 out = np.diagonal(a)
139 tgt = [0, 5, 10]
140
141 assert_equal(out, tgt)
142
143 def test_mean(self):
144 A = [[1, 2, 3], [4, 5, 6]]
145 assert_(np.mean(A) == 3.5)
146 assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])))
147 assert_(np.all(np.mean(A, 1) == np.array([2., 5.])))
148
149 with warnings.catch_warnings(record=True) as w:
150 warnings.filterwarnings('always', '', RuntimeWarning)
151 assert_(np.isnan(np.mean([])))
152 assert_(w[0].category is RuntimeWarning)
153
154 def test_ptp(self):
155 a = [3, 4, 5, 10, -3, -5, 6.0]
156 assert_equal(np.ptp(a, axis=0), 15.0)
157
158 def test_prod(self):
159 arr = [[1, 2, 3, 4],
160 [5, 6, 7, 9],
161 [10, 3, 4, 5]]
162 tgt = [24, 1890, 600]
163
164 assert_equal(np.prod(arr, axis=-1), tgt)
165
166 def test_ravel(self):
167 a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
168 tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
169 assert_equal(np.ravel(a), tgt)
170
171 def test_repeat(self):
172 a = [1, 2, 3]
173 tgt = [1, 1, 2, 2, 3, 3]
174
175 out = np.repeat(a, 2)
176 assert_equal(out, tgt)
177
178 def test_reshape(self):
179 arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
180 tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
181 assert_equal(np.reshape(arr, (2, 6)), tgt)
182
183 def test_reshape_shape_arg(self):
184 arr = np.arange(12)
185 shape = (3, 4)
186 expected = arr.reshape(shape)
187
188 with pytest.raises(
189 TypeError,
190 match=r"reshape\(\) missing 1 required positional "
191 "argument: 'shape'"
192 ):
193 np.reshape(arr)
194
195 assert_equal(np.reshape(arr, shape), expected)
196 assert_equal(np.reshape(arr, shape, order="C"), expected)
197 assert_equal(np.reshape(arr, shape, "C"), expected)
198 assert_equal(np.reshape(arr, shape=shape), expected)
199 assert_equal(np.reshape(arr, shape=shape, order="C"), expected)
200
201 def test_reshape_copy_arg(self):
202 arr = np.arange(24).reshape(2, 3, 4)
203 arr_f_ord = np.array(arr, order="F")
204 shape = (12, 2)
205
206 assert np.shares_memory(np.reshape(arr, shape), arr)
207 assert np.shares_memory(np.reshape(arr, shape, order="C"), arr)
208 assert np.shares_memory(
209 np.reshape(arr_f_ord, shape, order="F"), arr_f_ord)
210 assert np.shares_memory(np.reshape(arr, shape, copy=None), arr)
211 assert np.shares_memory(np.reshape(arr, shape, copy=False), arr)
212 assert np.shares_memory(arr.reshape(shape, copy=False), arr)
213 assert not np.shares_memory(np.reshape(arr, shape, copy=True), arr)
214 assert not np.shares_memory(
215 np.reshape(arr, shape, order="C", copy=True), arr)
216 assert not np.shares_memory(
217 np.reshape(arr, shape, order="F", copy=True), arr)
218 assert not np.shares_memory(
219 np.reshape(arr, shape, order="F", copy=None), arr)
220
221 err_msg = "Unable to avoid creating a copy while reshaping."
222 with pytest.raises(ValueError, match=err_msg):
223 np.reshape(arr, shape, order="F", copy=False)
224 with pytest.raises(ValueError, match=err_msg):
225 np.reshape(arr_f_ord, shape, order="C", copy=False)
226
227 def test_round(self):
228 arr = [1.56, 72.54, 6.35, 3.25]
229 tgt = [1.6, 72.5, 6.4, 3.2]
230 assert_equal(np.around(arr, decimals=1), tgt)
231 s = np.float64(1.)
232 assert_(isinstance(s.round(), np.float64))
233 assert_equal(s.round(), 1.)
234
235 @pytest.mark.parametrize('dtype', [
236 np.int8, np.int16, np.int32, np.int64,
237 np.uint8, np.uint16, np.uint32, np.uint64,
238 np.float16, np.float32, np.float64,
239 ])
240 def test_dunder_round(self, dtype):
241 s = dtype(1)
242 assert_(isinstance(round(s), int))
243 assert_(isinstance(round(s, None), int))
244 assert_(isinstance(round(s, ndigits=None), int))
245 assert_equal(round(s), 1)
246 assert_equal(round(s, None), 1)
247 assert_equal(round(s, ndigits=None), 1)
248
249 @pytest.mark.parametrize('val, ndigits', [
250 pytest.param(2**31 - 1, -1,
251 marks=pytest.mark.skip(reason="Out of range of int32")
252 ),
253 (2**31 - 1, 1 - math.ceil(math.log10(2**31 - 1))),
254 (2**31 - 1, -math.ceil(math.log10(2**31 - 1)))
255 ])
256 def test_dunder_round_edgecases(self, val, ndigits):
257 assert_equal(round(val, ndigits), round(np.int32(val), ndigits))
258
259 def test_dunder_round_accuracy(self):
260 f = np.float64(5.1 * 10**73)
261 assert_(isinstance(round(f, -73), np.float64))
262 assert_array_max_ulp(round(f, -73), 5.0 * 10**73)
263 assert_(isinstance(round(f, ndigits=-73), np.float64))
264 assert_array_max_ulp(round(f, ndigits=-73), 5.0 * 10**73)
265
266 i = np.int64(501)
267 assert_(isinstance(round(i, -2), np.int64))
268 assert_array_max_ulp(round(i, -2), 500)
269 assert_(isinstance(round(i, ndigits=-2), np.int64))
270 assert_array_max_ulp(round(i, ndigits=-2), 500)
271
272 @pytest.mark.xfail(raises=AssertionError, reason="gh-15896")
273 def test_round_py_consistency(self):
274 f = 5.1 * 10**73
275 assert_equal(round(np.float64(f), -73), round(f, -73))
276
277 def test_searchsorted(self):
278 arr = [-8, -5, -1, 3, 6, 10]
279 out = np.searchsorted(arr, 0)
280 assert_equal(out, 3)
281
282 def test_size(self):
283 A = [[1, 2, 3], [4, 5, 6]]
284 assert_(np.size(A) == 6)
285 assert_(np.size(A, 0) == 2)
286 assert_(np.size(A, 1) == 3)
287 assert_(np.size(A, ()) == 1)
288 assert_(np.size(A, (0,)) == 2)
289 assert_(np.size(A, (1,)) == 3)
290 assert_(np.size(A, (0, 1)) == 6)
291
292 def test_squeeze(self):
293 A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]
294 assert_equal(np.squeeze(A).shape, (3, 3))
295 assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))
296 assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))
297 assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))
298 assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))
299 assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))
300 assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))
301 assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))
302 assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))
303
304 def test_std(self):
305 A = [[1, 2, 3], [4, 5, 6]]
306 assert_almost_equal(np.std(A), 1.707825127659933)
307 assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5]))
308 assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658]))
309
310 with warnings.catch_warnings(record=True) as w:
311 warnings.filterwarnings('always', '', RuntimeWarning)
312 assert_(np.isnan(np.std([])))
313 assert_(w[0].category is RuntimeWarning)
314
315 def test_swapaxes(self):
316 tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]]
317 a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
318 out = np.swapaxes(a, 0, 2)
319 assert_equal(out, tgt)
320
321 def test_sum(self):
322 m = [[1, 2, 3],
323 [4, 5, 6],
324 [7, 8, 9]]
325 tgt = [[6], [15], [24]]
326 out = np.sum(m, axis=1, keepdims=True)
327
328 assert_equal(tgt, out)
329
330 def test_take(self):
331 tgt = [2, 3, 5]
332 indices = [1, 2, 4]
333 a = [1, 2, 3, 4, 5]
334
335 out = np.take(a, indices)
336 assert_equal(out, tgt)
337
338 pairs = [
339 (np.int32, np.int32), (np.int32, np.int64),
340 (np.int64, np.int32), (np.int64, np.int64)
341 ]
342 for array_type, indices_type in pairs:
343 x = np.array([1, 2, 3, 4, 5], dtype=array_type)
344 ind = np.array([0, 2, 2, 3], dtype=indices_type)
345 tgt = np.array([1, 3, 3, 4], dtype=array_type)
346 out = np.take(x, ind)
347 assert_equal(out, tgt)
348 assert_equal(out.dtype, tgt.dtype)
349
350 def test_trace(self):
351 c = [[1, 2], [3, 4], [5, 6]]
352 assert_equal(np.trace(c), 5)
353
354 def test_transpose(self):
355 arr = [[1, 2], [3, 4], [5, 6]]
356 tgt = [[1, 3, 5], [2, 4, 6]]
357 assert_equal(np.transpose(arr, (1, 0)), tgt)
358 assert_equal(np.transpose(arr, (-1, -2)), tgt)
359 assert_equal(np.matrix_transpose(arr), tgt)
360
361 def test_var(self):
362 A = [[1, 2, 3], [4, 5, 6]]
363 assert_almost_equal(np.var(A), 2.9166666666666665)
364 assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25]))
365 assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667]))
366
367 with warnings.catch_warnings(record=True) as w:
368 warnings.filterwarnings('always', '', RuntimeWarning)
369 assert_(np.isnan(np.var([])))
370 assert_(w[0].category is RuntimeWarning)
371
372 B = np.array([None, 0])
373 B[0] = 1j
374 assert_almost_equal(np.var(B), 0.25)
375
376 def test_std_with_mean_keyword(self):
377 # Setting the seed to make the test reproducible
378 rng = np.random.RandomState(1234)
379 A = rng.randn(10, 20, 5) + 0.5
380
381 mean_out = np.zeros((10, 1, 5))
382 std_out = np.zeros((10, 1, 5))
383
384 mean = np.mean(A,
385 out=mean_out,
386 axis=1,
387 keepdims=True)
388
389 # The returned object should be the object specified during calling
390 assert mean_out is mean
391
392 std = np.std(A,
393 out=std_out,
394 axis=1,
395 keepdims=True,
396 mean=mean)
397
398 # The returned object should be the object specified during calling
399 assert std_out is std
400
401 # Shape of returned mean and std should be same
402 assert std.shape == mean.shape
403 assert std.shape == (10, 1, 5)
404
405 # Output should be the same as from the individual algorithms
406 std_old = np.std(A, axis=1, keepdims=True)
407
408 assert std_old.shape == mean.shape
409 assert_almost_equal(std, std_old)
410
411 def test_var_with_mean_keyword(self):
412 # Setting the seed to make the test reproducible
413 rng = np.random.RandomState(1234)
414 A = rng.randn(10, 20, 5) + 0.5
415
416 mean_out = np.zeros((10, 1, 5))
417 var_out = np.zeros((10, 1, 5))
418
419 mean = np.mean(A,
420 out=mean_out,
421 axis=1,
422 keepdims=True)
423
424 # The returned object should be the object specified during calling
425 assert mean_out is mean
426
427 var = np.var(A,
428 out=var_out,
429 axis=1,
430 keepdims=True,
431 mean=mean)
432
433 # The returned object should be the object specified during calling
434 assert var_out is var
435
436 # Shape of returned mean and var should be same
437 assert var.shape == mean.shape
438 assert var.shape == (10, 1, 5)
439
440 # Output should be the same as from the individual algorithms
441 var_old = np.var(A, axis=1, keepdims=True)
442
443 assert var_old.shape == mean.shape
444 assert_almost_equal(var, var_old)
445
446 def test_std_with_mean_keyword_keepdims_false(self):
447 rng = np.random.RandomState(1234)
448 A = rng.randn(10, 20, 5) + 0.5
449
450 mean = np.mean(A,
451 axis=1,
452 keepdims=True)
453
454 std = np.std(A,
455 axis=1,
456 keepdims=False,
457 mean=mean)
458
459 # Shape of returned mean and std should be same
460 assert std.shape == (10, 5)
461
462 # Output should be the same as from the individual algorithms
463 std_old = np.std(A, axis=1, keepdims=False)
464 mean_old = np.mean(A, axis=1, keepdims=False)
465
466 assert std_old.shape == mean_old.shape
467 assert_equal(std, std_old)
468
469 def test_var_with_mean_keyword_keepdims_false(self):
470 rng = np.random.RandomState(1234)
471 A = rng.randn(10, 20, 5) + 0.5
472
473 mean = np.mean(A,
474 axis=1,
475 keepdims=True)
476
477 var = np.var(A,
478 axis=1,
479 keepdims=False,
480 mean=mean)
481
482 # Shape of returned mean and var should be same
483 assert var.shape == (10, 5)
484
485 # Output should be the same as from the individual algorithms
486 var_old = np.var(A, axis=1, keepdims=False)
487 mean_old = np.mean(A, axis=1, keepdims=False)
488
489 assert var_old.shape == mean_old.shape
490 assert_equal(var, var_old)
491
492 def test_std_with_mean_keyword_where_nontrivial(self):
493 rng = np.random.RandomState(1234)
494 A = rng.randn(10, 20, 5) + 0.5
495
496 where = A > 0.5
497
498 mean = np.mean(A,
499 axis=1,
500 keepdims=True,
501 where=where)
502
503 std = np.std(A,
504 axis=1,
505 keepdims=False,
506 mean=mean,
507 where=where)
508
509 # Shape of returned mean and std should be same
510 assert std.shape == (10, 5)
511
512 # Output should be the same as from the individual algorithms
513 std_old = np.std(A, axis=1, where=where)
514 mean_old = np.mean(A, axis=1, where=where)
515
516 assert std_old.shape == mean_old.shape
517 assert_equal(std, std_old)
518
519 def test_var_with_mean_keyword_where_nontrivial(self):
520 rng = np.random.RandomState(1234)
521 A = rng.randn(10, 20, 5) + 0.5
522
523 where = A > 0.5
524
525 mean = np.mean(A,
526 axis=1,
527 keepdims=True,
528 where=where)
529
530 var = np.var(A,
531 axis=1,
532 keepdims=False,
533 mean=mean,
534 where=where)
535
536 # Shape of returned mean and var should be same
537 assert var.shape == (10, 5)
538
539 # Output should be the same as from the individual algorithms
540 var_old = np.var(A, axis=1, where=where)
541 mean_old = np.mean(A, axis=1, where=where)
542
543 assert var_old.shape == mean_old.shape
544 assert_equal(var, var_old)
545
546 def test_std_with_mean_keyword_multiple_axis(self):
547 # Setting the seed to make the test reproducible
548 rng = np.random.RandomState(1234)
549 A = rng.randn(10, 20, 5) + 0.5
550
551 axis = (0, 2)
552
553 mean = np.mean(A,
554 out=None,
555 axis=axis,
556 keepdims=True)
557
558 std = np.std(A,
559 out=None,
560 axis=axis,
561 keepdims=False,
562 mean=mean)
563
564 # Shape of returned mean and std should be same
565 assert std.shape == (20,)
566
567 # Output should be the same as from the individual algorithms
568 std_old = np.std(A, axis=axis, keepdims=False)
569
570 assert_almost_equal(std, std_old)
571
572 def test_std_with_mean_keyword_axis_None(self):
573 # Setting the seed to make the test reproducible
574 rng = np.random.RandomState(1234)
575 A = rng.randn(10, 20, 5) + 0.5
576
577 axis = None
578
579 mean = np.mean(A,
580 out=None,
581 axis=axis,
582 keepdims=True)
583
584 std = np.std(A,
585 out=None,
586 axis=axis,
587 keepdims=False,
588 mean=mean)
589
590 # Shape of returned mean and std should be same
591 assert std.shape == ()
592
593 # Output should be the same as from the individual algorithms
594 std_old = np.std(A, axis=axis, keepdims=False)
595
596 assert_almost_equal(std, std_old)
597
598 def test_std_with_mean_keyword_keepdims_true_masked(self):
599
600 A = ma.array([[2., 3., 4., 5.],
601 [1., 2., 3., 4.]],
602 mask=[[True, False, True, False],
603 [True, False, True, False]])
604
605 B = ma.array([[100., 3., 104., 5.],
606 [101., 2., 103., 4.]],
607 mask=[[True, False, True, False],
608 [True, False, True, False]])
609
610 mean_out = ma.array([[0., 0., 0., 0.]],
611 mask=[[False, False, False, False]])
612 std_out = ma.array([[0., 0., 0., 0.]],
613 mask=[[False, False, False, False]])
614
615 axis = 0
616
617 mean = np.mean(A, out=mean_out,
618 axis=axis, keepdims=True)
619
620 std = np.std(A, out=std_out,
621 axis=axis, keepdims=True,
622 mean=mean)
623
624 # Shape of returned mean and std should be same
625 assert std.shape == mean.shape
626 assert std.shape == (1, 4)
627
628 # Output should be the same as from the individual algorithms
629 std_old = np.std(A, axis=axis, keepdims=True)
630 mean_old = np.mean(A, axis=axis, keepdims=True)
631
632 assert std_old.shape == mean_old.shape
633 assert_almost_equal(std, std_old)
634 assert_almost_equal(mean, mean_old)
635
636 assert mean_out is mean
637 assert std_out is std
638
639 # masked elements should be ignored
640 mean_b = np.mean(B, axis=axis, keepdims=True)
641 std_b = np.std(B, axis=axis, keepdims=True, mean=mean_b)
642 assert_almost_equal(std, std_b)
643 assert_almost_equal(mean, mean_b)
644
645 def test_var_with_mean_keyword_keepdims_true_masked(self):
646
647 A = ma.array([[2., 3., 4., 5.],
648 [1., 2., 3., 4.]],
649 mask=[[True, False, True, False],
650 [True, False, True, False]])
651
652 B = ma.array([[100., 3., 104., 5.],
653 [101., 2., 103., 4.]],
654 mask=[[True, False, True, False],
655 [True, False, True, False]])
656
657 mean_out = ma.array([[0., 0., 0., 0.]],
658 mask=[[False, False, False, False]])
659 var_out = ma.array([[0., 0., 0., 0.]],
660 mask=[[False, False, False, False]])
661
662 axis = 0
663
664 mean = np.mean(A, out=mean_out,
665 axis=axis, keepdims=True)
666
667 var = np.var(A, out=var_out,
668 axis=axis, keepdims=True,
669 mean=mean)
670
671 # Shape of returned mean and var should be same
672 assert var.shape == mean.shape
673 assert var.shape == (1, 4)
674
675 # Output should be the same as from the individual algorithms
676 var_old = np.var(A, axis=axis, keepdims=True)
677 mean_old = np.mean(A, axis=axis, keepdims=True)
678
679 assert var_old.shape == mean_old.shape
680 assert_almost_equal(var, var_old)
681 assert_almost_equal(mean, mean_old)
682
683 assert mean_out is mean
684 assert var_out is var
685
686 # masked elements should be ignored
687 mean_b = np.mean(B, axis=axis, keepdims=True)
688 var_b = np.var(B, axis=axis, keepdims=True, mean=mean_b)
689 assert_almost_equal(var, var_b)
690 assert_almost_equal(mean, mean_b)
691
692
693class TestIsscalar:
694 def test_isscalar(self):
695 assert_(np.isscalar(3.1))
696 assert_(np.isscalar(np.int16(12345)))
697 assert_(np.isscalar(False))
698 assert_(np.isscalar('numpy'))
699 assert_(not np.isscalar([3.1]))
700 assert_(not np.isscalar(None))
701
702 # PEP 3141
703 from fractions import Fraction
704 assert_(np.isscalar(Fraction(5, 17)))
705 from numbers import Number
706 assert_(np.isscalar(Number()))
707
708
709class TestBoolScalar:
710 def test_logical(self):
711 f = np.False_
712 t = np.True_
713 s = "xyz"
714 assert_((t and s) is s)
715 assert_((f and s) is f)
716
717 def test_bitwise_or(self):
718 f = np.False_
719 t = np.True_
720 assert_((t | t) is t)
721 assert_((f | t) is t)
722 assert_((t | f) is t)
723 assert_((f | f) is f)
724
725 def test_bitwise_and(self):
726 f = np.False_
727 t = np.True_
728 assert_((t & t) is t)
729 assert_((f & t) is f)
730 assert_((t & f) is f)
731 assert_((f & f) is f)
732
733 def test_bitwise_xor(self):
734 f = np.False_
735 t = np.True_
736 assert_((t ^ t) is f)
737 assert_((f ^ t) is t)
738 assert_((t ^ f) is t)
739 assert_((f ^ f) is f)
740
741
742class TestBoolArray:
743 def _create_bool_arrays(self):
744 # offset for simd tests
745 t = np.array([True] * 41, dtype=bool)[1::]
746 f = np.array([False] * 41, dtype=bool)[1::]
747 o = np.array([False] * 42, dtype=bool)[2::]
748 nm = f.copy()
749 im = t.copy()
750 nm[3] = True
751 nm[-2] = True
752 im[3] = False
753 im[-2] = False
754 return t, f, o, nm, im
755
756 def test_all_any(self):
757 t, f, _, nm, im = self._create_bool_arrays()
758 assert_(t.all())
759 assert_(t.any())
760 assert_(not f.all())
761 assert_(not f.any())
762 assert_(nm.any())
763 assert_(im.any())
764 assert_(not nm.all())
765 assert_(not im.all())
766 # check bad element in all positions
767 for i in range(256 - 7):
768 d = np.array([False] * 256, dtype=bool)[7::]
769 d[i] = True
770 assert_(np.any(d))
771 e = np.array([True] * 256, dtype=bool)[7::]
772 e[i] = False
773 assert_(not np.all(e))
774 assert_array_equal(e, ~d)
775 # big array test for blocked libc loops
776 for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
777 d = np.array([False] * 100043, dtype=bool)
778 d[i] = True
779 assert_(np.any(d), msg=f"{i!r}")
780 e = np.array([True] * 100043, dtype=bool)
781 e[i] = False
782 assert_(not np.all(e), msg=f"{i!r}")
783
784 def test_logical_not_abs(self):
785 t, f, o, nm, im = self._create_bool_arrays()
786 assert_array_equal(~t, f)
787 assert_array_equal(np.abs(~t), f)
788 assert_array_equal(np.abs(~f), t)
789 assert_array_equal(np.abs(f), f)
790 assert_array_equal(~np.abs(f), t)
791 assert_array_equal(~np.abs(t), f)
792 assert_array_equal(np.abs(~nm), im)
793 np.logical_not(t, out=o)
794 assert_array_equal(o, f)
795 np.abs(t, out=o)
796 assert_array_equal(o, t)
797
798 def test_logical_and_or_xor(self):
799 t, f, o, nm, im = self._create_bool_arrays()
800 assert_array_equal(t | t, t)
801 assert_array_equal(f | f, f)
802 assert_array_equal(t | f, t)
803 assert_array_equal(f | t, t)
804 np.logical_or(t, t, out=o)
805 assert_array_equal(o, t)
806 assert_array_equal(t & t, t)
807 assert_array_equal(f & f, f)
808 assert_array_equal(t & f, f)
809 assert_array_equal(f & t, f)
810 np.logical_and(t, t, out=o)
811 assert_array_equal(o, t)
812 assert_array_equal(t ^ t, f)
813 assert_array_equal(f ^ f, f)
814 assert_array_equal(t ^ f, t)
815 assert_array_equal(f ^ t, t)
816 np.logical_xor(t, t, out=o)
817 assert_array_equal(o, f)
818
819 assert_array_equal(nm & t, nm)
820 assert_array_equal(im & f, False)
821 assert_array_equal(nm & True, nm)
822 assert_array_equal(im & False, f)
823 assert_array_equal(nm | t, t)
824 assert_array_equal(im | f, im)
825 assert_array_equal(nm | True, t)
826 assert_array_equal(im | False, im)
827 assert_array_equal(nm ^ t, im)
828 assert_array_equal(im ^ f, im)
829 assert_array_equal(nm ^ True, im)
830 assert_array_equal(im ^ False, im)
831
832
833class TestBoolCmp:
834 def _create_data(self, dtype, size):
835 # generate data using given dtype and num for size of array
836 a = np.ones(size, dtype=dtype)
837 e = np.ones(a.size, dtype=bool)
838 # generate values for all permutation of 256bit simd vectors
839 s = 0
840 r = int(size / 32)
841 for i in range(int(size / 8)):
842 a[s:s + r] = [i & 2**x for x in range(r)]
843 e[s:s + r] = [(i & 2**x) != 0 for x in range(r)]
844 s += r
845 n = a.copy()
846 n[e] = np.nan
847
848 inf = a.copy()
849 inf[::3][e[::3]] = np.inf
850 inf[1::3][e[1::3]] = -np.inf
851 inf[2::3][e[2::3]] = np.nan
852 enonan = e.copy()
853 enonan[2::3] = False
854
855 sign = a.copy()
856 sign[e] *= -1.
857 sign[1::6][e[1::6]] = -np.inf
858 # On RISC-V, many operations that produce NaNs, such as converting
859 # a -NaN from f64 to f32, return a canonical NaN. The canonical
860 # NaNs are always positive. See section 11.3 NaN Generation and
861 # Propagation of the RISC-V Unprivileged ISA for more details.
862 # We disable the float32 sign test on riscv64 for -np.nan as the sign
863 # of the NaN will be lost when it's converted to a float32.
864 if not (dtype == np.float32 and platform.machine() == 'riscv64'):
865 sign[3::6][e[3::6]] = -np.nan
866 sign[4::6][e[4::6]] = -0.
867 return a, e, n, inf, enonan, sign
868
869 def test_float(self):
870 # offset for alignment test
871 f, ef, nf, inff, efnonan, signf = self._create_data(np.float32, 256)
872 for i in range(4):
873 assert_array_equal(f[i:] > 0, ef[i:])
874 assert_array_equal(f[i:] - 1 >= 0, ef[i:])
875 assert_array_equal(f[i:] == 0, ~ef[i:])
876 assert_array_equal(-f[i:] < 0, ef[i:])
877 assert_array_equal(-f[i:] + 1 <= 0, ef[i:])
878 r = f[i:] != 0
879 assert_array_equal(r, ef[i:])
880 r2 = f[i:] != np.zeros_like(f[i:])
881 r3 = 0 != f[i:]
882 assert_array_equal(r, r2)
883 assert_array_equal(r, r3)
884 # check bool == 0x1
885 assert_array_equal(r.view(np.int8), r.astype(np.int8))
886 assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
887 assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
888
889 # isnan on amd64 takes the same code path
890 assert_array_equal(np.isnan(nf[i:]), ef[i:])
891 assert_array_equal(np.isfinite(nf[i:]), ~ef[i:])
892 assert_array_equal(np.isfinite(inff[i:]), ~ef[i:])
893 assert_array_equal(np.isinf(inff[i:]), efnonan[i:])
894 assert_array_equal(np.signbit(signf[i:]), ef[i:])
895
896 def test_double(self):
897 # offset for alignment test
898 d, ed, nd, infd, ednonan, signd = self._create_data(np.float64, 128)
899 for i in range(2):
900 assert_array_equal(d[i:] > 0, ed[i:])
901 assert_array_equal(d[i:] - 1 >= 0, ed[i:])
902 assert_array_equal(d[i:] == 0, ~ed[i:])
903 assert_array_equal(-d[i:] < 0, ed[i:])
904 assert_array_equal(-d[i:] + 1 <= 0, ed[i:])
905 r = d[i:] != 0
906 assert_array_equal(r, ed[i:])
907 r2 = d[i:] != np.zeros_like(d[i:])
908 r3 = 0 != d[i:]
909 assert_array_equal(r, r2)
910 assert_array_equal(r, r3)
911 # check bool == 0x1
912 assert_array_equal(r.view(np.int8), r.astype(np.int8))
913 assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
914 assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
915
916 # isnan on amd64 takes the same code path
917 assert_array_equal(np.isnan(nd[i:]), ed[i:])
918 assert_array_equal(np.isfinite(nd[i:]), ~ed[i:])
919 assert_array_equal(np.isfinite(infd[i:]), ~ed[i:])
920 assert_array_equal(np.isinf(infd[i:]), ednonan[i:])
921 assert_array_equal(np.signbit(signd[i:]), ed[i:])
922
923
924class TestSeterr:
925 def test_default(self):
926 err = np.geterr()
927 assert_equal(err,
928 {'divide': 'warn',
929 'invalid': 'warn',
930 'over': 'warn',
931 'under': 'ignore'}
932 )
933
934 def test_set(self):
935 with np.errstate():
936 err = np.seterr()
937 old = np.seterr(divide='print')
938 assert_(err == old)
939 new = np.seterr()
940 assert_(new['divide'] == 'print')
941 np.seterr(over='raise')
942 assert_(np.geterr()['over'] == 'raise')
943 assert_(new['divide'] == 'print')
944 np.seterr(**old)
945 assert_(np.geterr() == old)
946
947 @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
948 @pytest.mark.skipif(platform.machine() == "armv5tel", reason="See gh-413.")
949 def test_divide_err(self):
950 with np.errstate(divide='raise'):
951 with assert_raises(FloatingPointError):
952 np.array([1.]) / np.array([0.])
953
954 np.seterr(divide='ignore')
955 np.array([1.]) / np.array([0.])
956
957
958class TestFloatExceptions:
959 def assert_raises_fpe(self, fpeerr, flop, x, y):
960 ftype = type(x)
961 try:
962 flop(x, y)
963 assert_(False,
964 f"Type {ftype} did not raise fpe error '{fpeerr}'.")
965 except FloatingPointError as exc:
966 assert_(str(exc).find(fpeerr) >= 0,
967 f"Type {ftype} raised wrong fpe error '{exc}'.")
968
969 def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):
970 # Check that fpe exception is raised.
971 #
972 # Given a floating operation `flop` and two scalar values, check that
973 # the operation raises the floating point exception specified by
974 # `fpeerr`. Tests all variants with 0-d array scalars as well.
975
976 self.assert_raises_fpe(fpeerr, flop, sc1, sc2)
977 self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2)
978 self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()])
979 self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()])
980
981 # Test for all real and complex float types
982 @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
983 @pytest.mark.parametrize("typecode", np.typecodes["AllFloat"])
984 def test_floating_exceptions(self, typecode):
985 if 'bsd' in sys.platform and typecode in 'gG':
986 pytest.skip(reason="Fallback impl for (c)longdouble may not raise "
987 "FPE errors as expected on BSD OSes, "
988 "see gh-24876, gh-23379")
989
990 # Test basic arithmetic function errors
991 with np.errstate(all='raise'):
992 ftype = obj2sctype(typecode)
993 if np.dtype(ftype).kind == 'f':
994 # Get some extreme values for the type
995 fi = np.finfo(ftype)
996 ft_tiny = fi.tiny
997 ft_max = fi.max
998 ft_eps = fi.eps
999 underflow = 'underflow'
1000 divbyzero = 'divide by zero'
1001 else:
1002 # 'c', complex, corresponding real dtype
1003 rtype = type(ftype(0).real)
1004 fi = np.finfo(rtype)
1005 ft_tiny = ftype(fi.tiny)
1006 ft_max = ftype(fi.max)
1007 ft_eps = ftype(fi.eps)
1008 # The complex types raise different exceptions
1009 underflow = ''
1010 divbyzero = ''
1011 overflow = 'overflow'
1012 invalid = 'invalid'
1013
1014 # The value of tiny for double double is NaN, so we need to
1015 # pass the assert
1016 if not np.isnan(ft_tiny):
1017 self.assert_raises_fpe(underflow,
1018 lambda a, b: a / b, ft_tiny, ft_max)
1019 self.assert_raises_fpe(underflow,
1020 lambda a, b: a * b, ft_tiny, ft_tiny)
1021 self.assert_raises_fpe(overflow,
1022 lambda a, b: a * b, ft_max, ftype(2))
1023 self.assert_raises_fpe(overflow,
1024 lambda a, b: a / b, ft_max, ftype(0.5))
1025 self.assert_raises_fpe(overflow,
1026 lambda a, b: a + b, ft_max, ft_max * ft_eps)
1027 self.assert_raises_fpe(overflow,
1028 lambda a, b: a - b, -ft_max, ft_max * ft_eps)
1029 # On AIX, pow() with double does not raise the overflow exception,
1030 # it returns inf. Long double is the same as double.
1031 if sys.platform != 'aix' or typecode not in 'dDgG':
1032 self.assert_raises_fpe(overflow,
1033 np.power, ftype(2), ftype(2**fi.nexp))
1034 self.assert_raises_fpe(divbyzero,
1035 lambda a, b: a / b, ftype(1), ftype(0))
1036 self.assert_raises_fpe(
1037 invalid, lambda a, b: a / b, ftype(np.inf), ftype(np.inf)
1038 )
1039 self.assert_raises_fpe(invalid,
1040 lambda a, b: a / b, ftype(0), ftype(0))
1041 self.assert_raises_fpe(
1042 invalid, lambda a, b: a - b, ftype(np.inf), ftype(np.inf)
1043 )
1044 self.assert_raises_fpe(
1045 invalid, lambda a, b: a + b, ftype(np.inf), ftype(-np.inf)
1046 )
1047 self.assert_raises_fpe(invalid,
1048 lambda a, b: a * b, ftype(0), ftype(np.inf))
1049
1050 @pytest.mark.skipif(IS_WASM, reason="no wasm fp exception support")
1051 def test_warnings(self):
1052 # test warning code path
1053 with warnings.catch_warnings(record=True) as w:
1054 warnings.simplefilter("always")
1055 with np.errstate(all="warn"):
1056 np.divide(1, 0.)
1057 assert_equal(len(w), 1)
1058 assert_("divide by zero" in str(w[0].message))
1059 np.array(1e300) * np.array(1e300)
1060 assert_equal(len(w), 2)
1061 assert_("overflow" in str(w[-1].message))
1062 np.array(np.inf) - np.array(np.inf)
1063 assert_equal(len(w), 3)
1064 assert_("invalid value" in str(w[-1].message))
1065 np.array(1e-300) * np.array(1e-300)
1066 assert_equal(len(w), 4)
1067 assert_("underflow" in str(w[-1].message))
1068
1069
1070class TestTypes:
1071 def check_promotion_cases(self, promote_func):
1072 # tests that the scalars get coerced correctly.
1073 b = np.bool(0)
1074 i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
1075 u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0)
1076 f32, f64, fld = np.float32(0), np.float64(0), np.longdouble(0)
1077 c64, c128, cld = np.complex64(0), np.complex128(0), np.clongdouble(0)
1078
1079 # coercion within the same kind
1080 assert_equal(promote_func(i8, i16), np.dtype(np.int16))
1081 assert_equal(promote_func(i32, i8), np.dtype(np.int32))
1082 assert_equal(promote_func(i16, i64), np.dtype(np.int64))
1083 assert_equal(promote_func(u8, u32), np.dtype(np.uint32))
1084 assert_equal(promote_func(f32, f64), np.dtype(np.float64))
1085 assert_equal(promote_func(fld, f32), np.dtype(np.longdouble))
1086 assert_equal(promote_func(f64, fld), np.dtype(np.longdouble))
1087 assert_equal(promote_func(c128, c64), np.dtype(np.complex128))
1088 assert_equal(promote_func(cld, c128), np.dtype(np.clongdouble))
1089 assert_equal(promote_func(c64, fld), np.dtype(np.clongdouble))
1090
1091 # coercion between kinds
1092 assert_equal(promote_func(b, i32), np.dtype(np.int32))
1093 assert_equal(promote_func(b, u8), np.dtype(np.uint8))
1094 assert_equal(promote_func(i8, u8), np.dtype(np.int16))
1095 assert_equal(promote_func(u8, i32), np.dtype(np.int32))
1096 assert_equal(promote_func(i64, u32), np.dtype(np.int64))
1097 assert_equal(promote_func(u64, i32), np.dtype(np.float64))
1098 assert_equal(promote_func(i32, f32), np.dtype(np.float64))
1099 assert_equal(promote_func(i64, f32), np.dtype(np.float64))
1100 assert_equal(promote_func(f32, i16), np.dtype(np.float32))
1101 assert_equal(promote_func(f32, u32), np.dtype(np.float64))
1102 assert_equal(promote_func(f32, c64), np.dtype(np.complex64))
1103 assert_equal(promote_func(c128, f32), np.dtype(np.complex128))
1104 assert_equal(promote_func(cld, f64), np.dtype(np.clongdouble))
1105
1106 # coercion between scalars and 1-D arrays
1107 assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8))
1108 assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8))
1109 assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32))
1110 assert_equal(promote_func(np.array([b]), u32), np.dtype(np.uint32))
1111 assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int64))
1112 # unsigned and signed unfortunately tend to promote to float64:
1113 assert_equal(promote_func(u64, np.array([i32])), np.dtype(np.float64))
1114 assert_equal(promote_func(i64, np.array([u32])), np.dtype(np.int64))
1115 assert_equal(promote_func(np.array([u16]), i32), np.dtype(np.int32))
1116 assert_equal(promote_func(np.int32(-1), np.array([u64])),
1117 np.dtype(np.float64))
1118 assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float64))
1119 assert_equal(promote_func(fld, np.array([f32])),
1120 np.dtype(np.longdouble))
1121 assert_equal(promote_func(np.array([f64]), fld),
1122 np.dtype(np.longdouble))
1123 assert_equal(promote_func(fld, np.array([c64])),
1124 np.dtype(np.clongdouble))
1125 assert_equal(promote_func(c64, np.array([f64])),
1126 np.dtype(np.complex128))
1127 assert_equal(promote_func(np.complex64(3j), np.array([f64])),
1128 np.dtype(np.complex128))
1129 assert_equal(promote_func(np.array([f32]), c128),
1130 np.dtype(np.complex128))
1131
1132 # coercion between scalars and 1-D arrays, where
1133 # the scalar has greater kind than the array
1134 assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64))
1135 assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64))
1136 assert_equal(promote_func(np.array([b]), u64), np.dtype(np.uint64))
1137 assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64))
1138 assert_equal(promote_func(np.array([u16]), f64), np.dtype(np.float64))
1139
1140 def test_coercion(self):
1141 def res_type(a, b):
1142 return np.add(a, b).dtype
1143
1144 self.check_promotion_cases(res_type)
1145
1146 # Use-case: float/complex scalar * bool/int8 array
1147 # shouldn't narrow the float/complex type
1148 for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:
1149 b = 1.234 * a
1150 assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
1151 b = np.longdouble(1.234) * a
1152 assert_equal(b.dtype, np.dtype(np.longdouble),
1153 f"array type {a.dtype}")
1154 b = np.float64(1.234) * a
1155 assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
1156 b = np.float32(1.234) * a
1157 assert_equal(b.dtype, np.dtype('f4'), f"array type {a.dtype}")
1158 b = np.float16(1.234) * a
1159 assert_equal(b.dtype, np.dtype('f2'), f"array type {a.dtype}")
1160
1161 b = 1.234j * a
1162 assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
1163 b = np.clongdouble(1.234j) * a
1164 assert_equal(b.dtype, np.dtype(np.clongdouble),
1165 f"array type {a.dtype}")
1166 b = np.complex128(1.234j) * a
1167 assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
1168 b = np.complex64(1.234j) * a
1169 assert_equal(b.dtype, np.dtype('c8'), f"array type {a.dtype}")
1170
1171 # The following use-case is problematic, and to resolve its
1172 # tricky side-effects requires more changes.
1173 #
1174 # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is
1175 # a float32, shouldn't promote to float64
1176 #
1177 # a = np.array([1.0, 1.5], dtype=np.float32)
1178 # t = np.array([True, False])
1179 # b = t*a
1180 # assert_equal(b, [1.0, 0.0])
1181 # assert_equal(b.dtype, np.dtype('f4'))
1182 # b = (1-t)*a
1183 # assert_equal(b, [0.0, 1.5])
1184 # assert_equal(b.dtype, np.dtype('f4'))
1185 #
1186 # Probably ~t (bitwise negation) is more proper to use here,
1187 # but this is arguably less intuitive to understand at a glance, and
1188 # would fail if 't' is actually an integer array instead of boolean:
1189 #
1190 # b = (~t)*a
1191 # assert_equal(b, [0.0, 1.5])
1192 # assert_equal(b.dtype, np.dtype('f4'))
1193
1194 def test_result_type(self):
1195 self.check_promotion_cases(np.result_type)
1196 assert_(np.result_type(None) == np.dtype(None))
1197
1198 def test_promote_types_endian(self):
1199 # promote_types should always return native-endian types
1200 assert_equal(np.promote_types('<i8', '<i8'), np.dtype('i8'))
