xref: /aosp_15_r20/external/pytorch/test/torch_np/numpy_tests/core/test_numeric.py (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1# Owner(s): ["module: dynamo"]
2
3import functools
4import itertools
5import math
6import platform
7import sys
8import warnings
9
10import numpy
11import pytest
12
13
14IS_WASM = False
15HAS_REFCOUNT = True
16
17import operator
18from unittest import expectedFailure as xfail, skipIf as skipif, SkipTest
19
20from hypothesis import given, strategies as st
21from hypothesis.extra import numpy as hynp
22from pytest import raises as assert_raises
23
24from torch.testing._internal.common_utils import (
25    instantiate_parametrized_tests,
26    parametrize,
27    run_tests,
28    subtest,
29    TEST_WITH_TORCHDYNAMO,
30    TestCase,
31    xfailIfTorchDynamo,
32    xpassIfTorchDynamo,
33)
34
35
36# If we are going to trace through these, we should use NumPy
37# If testing on eager mode, we use torch._numpy
38if TEST_WITH_TORCHDYNAMO:
39    import numpy as np
40    from numpy.random import rand, randint, randn
41    from numpy.testing import (
42        assert_,
43        assert_allclose,
44        assert_almost_equal,
45        assert_array_almost_equal,
46        assert_array_equal,
47        assert_equal,
48        assert_warns,  # assert_array_max_ulp, HAS_REFCOUNT, IS_WASM
49    )
50else:
51    import torch._numpy as np
52    from torch._numpy.random import rand, randint, randn
53    from torch._numpy.testing import (
54        assert_,
55        assert_allclose,
56        assert_almost_equal,
57        assert_array_almost_equal,
58        assert_array_equal,
59        assert_equal,
60        assert_warns,  # assert_array_max_ulp, HAS_REFCOUNT, IS_WASM
61    )
62
63
64skip = functools.partial(skipif, True)
65
66
67@instantiate_parametrized_tests
68class TestResize(TestCase):
69    def test_copies(self):
70        A = np.array([[1, 2], [3, 4]])
71        Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]])
72        assert_equal(np.resize(A, (2, 4)), Ar1)
73
74        Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
75        assert_equal(np.resize(A, (4, 2)), Ar2)
76
77        Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]])
78        assert_equal(np.resize(A, (4, 3)), Ar3)
79
80    def test_repeats(self):
81        A = np.array([1, 2, 3])
82        Ar1 = np.array([[1, 2, 3, 1], [2, 3, 1, 2]])
83        assert_equal(np.resize(A, (2, 4)), Ar1)
84
85        Ar2 = np.array([[1, 2], [3, 1], [2, 3], [1, 2]])
86        assert_equal(np.resize(A, (4, 2)), Ar2)
87
88        Ar3 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])
89        assert_equal(np.resize(A, (4, 3)), Ar3)
90
91    def test_zeroresize(self):
92        A = np.array([[1, 2], [3, 4]])
93        Ar = np.resize(A, (0,))
94        assert_array_equal(Ar, np.array([]))
95        assert_equal(A.dtype, Ar.dtype)
96
97        Ar = np.resize(A, (0, 2))
98        assert_equal(Ar.shape, (0, 2))
99
100        Ar = np.resize(A, (2, 0))
101        assert_equal(Ar.shape, (2, 0))
102
103    def test_reshape_from_zero(self):
104        # See also gh-6740
105        A = np.zeros(0, dtype=np.float32)
106        Ar = np.resize(A, (2, 1))
107        assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype))
108        assert_equal(A.dtype, Ar.dtype)
109
110    def test_negative_resize(self):
111        A = np.arange(0, 10, dtype=np.float32)
112        new_shape = (-10, -1)
113        with pytest.raises((RuntimeError, ValueError)):
114            np.resize(A, new_shape=new_shape)
115
116
117@instantiate_parametrized_tests
118class TestNonarrayArgs(TestCase):
119    # check that non-array arguments to functions wrap them in arrays
120    def test_choose(self):
121        choices = [[0, 1, 2], [3, 4, 5], [5, 6, 7]]
122        tgt = [5, 1, 5]
123        a = [2, 0, 1]
124
125        out = np.choose(a, choices)
126        assert_equal(out, tgt)
127
128    def test_clip(self):
129        arr = [-1, 5, 2, 3, 10, -4, -9]
130        out = np.clip(arr, 2, 7)
131        tgt = [2, 5, 2, 3, 7, 2, 2]
132        assert_equal(out, tgt)
133
134    @xpassIfTorchDynamo  # (reason="TODO implement compress(...)")
135    def test_compress(self):
136        arr = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
137        tgt = [[5, 6, 7, 8, 9]]
138        out = np.compress([0, 1], arr, axis=0)
139        assert_equal(out, tgt)
140
141    def test_count_nonzero(self):
142        arr = [[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]]
143        tgt = np.array([2, 3])
144        out = np.count_nonzero(arr, axis=1)
145        assert_equal(out, tgt)
146
147    def test_cumproduct(self):
148        A = [[1, 2, 3], [4, 5, 6]]
149        assert_(np.all(np.cumprod(A) == np.array([1, 2, 6, 24, 120, 720])))
150
151    def test_diagonal(self):
152        a = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
153        out = np.diagonal(a)
154        tgt = [0, 5, 10]
155
156        assert_equal(out, tgt)
157
158    def test_mean(self):
159        A = [[1, 2, 3], [4, 5, 6]]
160        assert_(np.mean(A) == 3.5)
161        assert_(np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])))
162        assert_(np.all(np.mean(A, 1) == np.array([2.0, 5.0])))
163
164        #    with warnings.catch_warnings(record=True) as w:
165        #        warnings.filterwarnings('always', '', RuntimeWarning)
166        assert_(np.isnan(np.mean([])))
167
168    #        assert_(w[0].category is RuntimeWarning)
169
170    def test_ptp(self):
171        a = [3, 4, 5, 10, -3, -5, 6.0]
172        assert_equal(np.ptp(a, axis=0), 15.0)
173
174    def test_prod(self):
175        arr = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
176        tgt = [24, 1890, 600]
177
178        assert_equal(np.prod(arr, axis=-1), tgt)
179
180    def test_ravel(self):
181        a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
182        tgt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
183        assert_equal(np.ravel(a), tgt)
184
185    def test_repeat(self):
186        a = [1, 2, 3]
187        tgt = [1, 1, 2, 2, 3, 3]
188
189        out = np.repeat(a, 2)
190        assert_equal(out, tgt)
191
192    def test_reshape(self):
193        arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
194        tgt = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
195        assert_equal(np.reshape(arr, (2, 6)), tgt)
196
197    def test_round(self):
198        arr = [1.56, 72.54, 6.35, 3.25]
199        tgt = [1.6, 72.5, 6.4, 3.2]
200        assert_equal(np.around(arr, decimals=1), tgt)
201        s = np.float64(1.0)
202        assert_equal(s.round(), 1.0)
203
204    def test_round_2(self):
205        s = np.float64(1.0)
206        assert_(isinstance(s.round(), (np.float64, np.ndarray)))
207
208    @xpassIfTorchDynamo  # (reason="scalar instances")
209    @parametrize(
210        "dtype",
211        [
212            np.int8,
213            np.int16,
214            np.int32,
215            np.int64,
216            np.uint8,
217            np.float16,
218            np.float32,
219            np.float64,
220        ],
221    )
222    def test_dunder_round(self, dtype):
223        s = dtype(1)
224        assert_(isinstance(round(s), int))
225        assert_(isinstance(round(s, None), int))
226        assert_(isinstance(round(s, ndigits=None), int))
227        assert_equal(round(s), 1)
228        assert_equal(round(s, None), 1)
229        assert_equal(round(s, ndigits=None), 1)
230
231    @parametrize(
232        "val, ndigits",
233        [
234            # pytest.param(
235            #    2**31 - 1, -1, marks=pytest.mark.xfail(reason="Out of range of int32")
236            # ),
237            subtest((2**31 - 1, -1), decorators=[xpassIfTorchDynamo]),
238            subtest(
239                (2**31 - 1, 1 - math.ceil(math.log10(2**31 - 1))),
240                decorators=[xpassIfTorchDynamo],
241            ),
242            subtest(
243                (2**31 - 1, -math.ceil(math.log10(2**31 - 1))),
244                decorators=[xpassIfTorchDynamo],
245            ),
246        ],
247    )
248    def test_dunder_round_edgecases(self, val, ndigits):
249        assert_equal(round(val, ndigits), round(np.int32(val), ndigits))
250
251    @xfail  # (reason="scalar instances")
252    def test_dunder_round_accuracy(self):
253        f = np.float64(5.1 * 10**73)
254        assert_(isinstance(round(f, -73), np.float64))
255        assert_array_max_ulp(round(f, -73), 5.0 * 10**73)
256        assert_(isinstance(round(f, ndigits=-73), np.float64))
257        assert_array_max_ulp(round(f, ndigits=-73), 5.0 * 10**73)
258
259        i = np.int64(501)
260        assert_(isinstance(round(i, -2), np.int64))
261        assert_array_max_ulp(round(i, -2), 500)
262        assert_(isinstance(round(i, ndigits=-2), np.int64))
263        assert_array_max_ulp(round(i, ndigits=-2), 500)
264
265    @xfail  # (raises=AssertionError, reason="gh-15896")
266    def test_round_py_consistency(self):
267        f = 5.1 * 10**73
268        assert_equal(round(np.float64(f), -73), round(f, -73))
269
270    def test_searchsorted(self):
271        arr = [-8, -5, -1, 3, 6, 10]
272        out = np.searchsorted(arr, 0)
273        assert_equal(out, 3)
274
275    def test_size(self):
276        A = [[1, 2, 3], [4, 5, 6]]
277        assert_(np.size(A) == 6)
278        assert_(np.size(A, 0) == 2)
279        assert_(np.size(A, 1) == 3)
280
281    def test_squeeze(self):
282        A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]
283        assert_equal(np.squeeze(A).shape, (3, 3))
284        assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))
285        assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))
286        assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))
287        assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))
288        assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))
289        assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))
290        assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))
291        assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))
292
293    def test_std(self):
294        A = [[1, 2, 3], [4, 5, 6]]
295        assert_almost_equal(np.std(A), 1.707825127659933)
296        assert_almost_equal(np.std(A, 0), np.array([1.5, 1.5, 1.5]))
297        assert_almost_equal(np.std(A, 1), np.array([0.81649658, 0.81649658]))
298
299        #  with warnings.catch_warnings(record=True) as w:
300        #      warnings.filterwarnings('always', '', RuntimeWarning)
301        assert_(np.isnan(np.std([])))
302
303    #      assert_(w[0].category is RuntimeWarning)
304
305    def test_swapaxes(self):
306        tgt = [[[0, 4], [2, 6]], [[1, 5], [3, 7]]]
307        a = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
308        out = np.swapaxes(a, 0, 2)
309        assert_equal(out, tgt)
310
311    def test_sum(self):
312        m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
313        tgt = [[6], [15], [24]]
314        out = np.sum(m, axis=1, keepdims=True)
315
316        assert_equal(tgt, out)
317
318    def test_take(self):
319        tgt = [2, 3, 5]
320        indices = [1, 2, 4]
321        a = [1, 2, 3, 4, 5]
322
323        out = np.take(a, indices)
324        assert_equal(out, tgt)
325
326    def test_trace(self):
327        c = [[1, 2], [3, 4], [5, 6]]
328        assert_equal(np.trace(c), 5)
329
330    def test_transpose(self):
331        arr = [[1, 2], [3, 4], [5, 6]]
332        tgt = [[1, 3, 5], [2, 4, 6]]
333        assert_equal(np.transpose(arr, (1, 0)), tgt)
334
335    def test_var(self):
336        A = [[1, 2, 3], [4, 5, 6]]
337        assert_almost_equal(np.var(A), 2.9166666666666665)
338        assert_almost_equal(np.var(A, 0), np.array([2.25, 2.25, 2.25]))
339        assert_almost_equal(np.var(A, 1), np.array([0.66666667, 0.66666667]))
340
341        #  with warnings.catch_warnings(record=True) as w:
342        #      warnings.filterwarnings('always', '', RuntimeWarning)
343        assert_(np.isnan(np.var([])))
344
345    #      assert_(w[0].category is RuntimeWarning)
346
347
348@xfail  # (reason="TODO")
349class TestIsscalar(TestCase):
350    def test_isscalar(self):
351        assert_(np.isscalar(3.1))
352        assert_(np.isscalar(np.int16(12345)))
353        assert_(np.isscalar(False))
354        assert_(np.isscalar("numpy"))
355        assert_(not np.isscalar([3.1]))
356        assert_(not np.isscalar(None))
357
358        # PEP 3141
359        from fractions import Fraction
360
361        assert_(np.isscalar(Fraction(5, 17)))
362        from numbers import Number
363
364        assert_(np.isscalar(Number()))
365
366
367class TestBoolScalar(TestCase):
368    def test_logical(self):
369        f = np.False_
370        t = np.True_
371        s = "xyz"
372        assert_((t and s) is s)
373        assert_((f and s) is f)
374
375    def test_bitwise_or_eq(self):
376        f = np.False_
377        t = np.True_
378        assert_((t | t) == t)
379        assert_((f | t) == t)
380        assert_((t | f) == t)
381        assert_((f | f) == f)
382
383    def test_bitwise_or_is(self):
384        f = np.False_
385        t = np.True_
386        assert_(bool(t | t) is bool(t))
387        assert_(bool(f | t) is bool(t))
388        assert_(bool(t | f) is bool(t))
389        assert_(bool(f | f) is bool(f))
390
391    def test_bitwise_and_eq(self):
392        f = np.False_
393        t = np.True_
394        assert_((t & t) == t)
395        assert_((f & t) == f)
396        assert_((t & f) == f)
397        assert_((f & f) == f)
398
399    def test_bitwise_and_is(self):
400        f = np.False_
401        t = np.True_
402        assert_(bool(t & t) is bool(t))
403        assert_(bool(f & t) is bool(f))
404        assert_(bool(t & f) is bool(f))
405        assert_(bool(f & f) is bool(f))
406
407    def test_bitwise_xor_eq(self):
408        f = np.False_
409        t = np.True_
410        assert_((t ^ t) == f)
411        assert_((f ^ t) == t)
412        assert_((t ^ f) == t)
413        assert_((f ^ f) == f)
414
415    def test_bitwise_xor_is(self):
416        f = np.False_
417        t = np.True_
418        assert_(bool(t ^ t) is bool(f))
419        assert_(bool(f ^ t) is bool(t))
420        assert_(bool(t ^ f) is bool(t))
421        assert_(bool(f ^ f) is bool(f))
422
423
424class TestBoolArray(TestCase):
425    def setUp(self):
426        super().setUp()
427        # offset for simd tests
428        self.t = np.array([True] * 41, dtype=bool)[1::]
429        self.f = np.array([False] * 41, dtype=bool)[1::]
430        self.o = np.array([False] * 42, dtype=bool)[2::]
431        self.nm = self.f.copy()
432        self.im = self.t.copy()
433        self.nm[3] = True
434        self.nm[-2] = True
435        self.im[3] = False
436        self.im[-2] = False
437
438    def test_all_any(self):
439        assert_(self.t.all())
440        assert_(self.t.any())
441        assert_(not self.f.all())
442        assert_(not self.f.any())
443        assert_(self.nm.any())
444        assert_(self.im.any())
445        assert_(not self.nm.all())
446        assert_(not self.im.all())
447        # check bad element in all positions
448        for i in range(256 - 7):
449            d = np.array([False] * 256, dtype=bool)[7::]
450            d[i] = True
451            assert_(np.any(d))
452            e = np.array([True] * 256, dtype=bool)[7::]
453            e[i] = False
454            assert_(not np.all(e))
455            assert_array_equal(e, ~d)
456        # big array test for blocked libc loops
457        for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
458            d = np.array([False] * 100043, dtype=bool)
459            d[i] = True
460            assert_(np.any(d), msg=f"{i!r}")
461            e = np.array([True] * 100043, dtype=bool)
462            e[i] = False
463            assert_(not np.all(e), msg=f"{i!r}")
464
465    def test_logical_not_abs(self):
466        assert_array_equal(~self.t, self.f)
467        assert_array_equal(np.abs(~self.t), self.f)
468        assert_array_equal(np.abs(~self.f), self.t)
469        assert_array_equal(np.abs(self.f), self.f)
470        assert_array_equal(~np.abs(self.f), self.t)
471        assert_array_equal(~np.abs(self.t), self.f)
472        assert_array_equal(np.abs(~self.nm), self.im)
473        np.logical_not(self.t, out=self.o)
474        assert_array_equal(self.o, self.f)
475        np.abs(self.t, out=self.o)
476        assert_array_equal(self.o, self.t)
477
478    def test_logical_and_or_xor(self):
479        assert_array_equal(self.t | self.t, self.t)
480        assert_array_equal(self.f | self.f, self.f)
481        assert_array_equal(self.t | self.f, self.t)
482        assert_array_equal(self.f | self.t, self.t)
483        np.logical_or(self.t, self.t, out=self.o)
484        assert_array_equal(self.o, self.t)
485        assert_array_equal(self.t & self.t, self.t)
486        assert_array_equal(self.f & self.f, self.f)
487        assert_array_equal(self.t & self.f, self.f)
488        assert_array_equal(self.f & self.t, self.f)
489        np.logical_and(self.t, self.t, out=self.o)
490        assert_array_equal(self.o, self.t)
491        assert_array_equal(self.t ^ self.t, self.f)
492        assert_array_equal(self.f ^ self.f, self.f)
493        assert_array_equal(self.t ^ self.f, self.t)
494        assert_array_equal(self.f ^ self.t, self.t)
495        np.logical_xor(self.t, self.t, out=self.o)
496        assert_array_equal(self.o, self.f)
497
498        assert_array_equal(self.nm & self.t, self.nm)
499        assert_array_equal(self.im & self.f, False)
500        assert_array_equal(self.nm & True, self.nm)
501        assert_array_equal(self.im & False, self.f)
502        assert_array_equal(self.nm | self.t, self.t)
503        assert_array_equal(self.im | self.f, self.im)
504        assert_array_equal(self.nm | True, self.t)
505        assert_array_equal(self.im | False, self.im)
506        assert_array_equal(self.nm ^ self.t, self.im)
507        assert_array_equal(self.im ^ self.f, self.im)
508        assert_array_equal(self.nm ^ True, self.im)
509        assert_array_equal(self.im ^ False, self.im)
510
511
512@xfailIfTorchDynamo
513class TestBoolCmp(TestCase):
514    def setUp(self):
515        super().setUp()
516        self.f = np.ones(256, dtype=np.float32)
517        self.ef = np.ones(self.f.size, dtype=bool)
518        self.d = np.ones(128, dtype=np.float64)
519        self.ed = np.ones(self.d.size, dtype=bool)
520        # generate values for all permutation of 256bit simd vectors
521        s = 0
522        for i in range(32):
523            self.f[s : s + 8] = [i & 2**x for x in range(8)]
524            self.ef[s : s + 8] = [(i & 2**x) != 0 for x in range(8)]
525            s += 8
526        s = 0
527        for i in range(16):
528            self.d[s : s + 4] = [i & 2**x for x in range(4)]
529            self.ed[s : s + 4] = [(i & 2**x) != 0 for x in range(4)]
530            s += 4
531
532        self.nf = self.f.copy()
533        self.nd = self.d.copy()
534        self.nf[self.ef] = np.nan
535        self.nd[self.ed] = np.nan
536
537        self.inff = self.f.copy()
538        self.infd = self.d.copy()
539        self.inff[::3][self.ef[::3]] = np.inf
540        self.infd[::3][self.ed[::3]] = np.inf
541        self.inff[1::3][self.ef[1::3]] = -np.inf
542        self.infd[1::3][self.ed[1::3]] = -np.inf
543        self.inff[2::3][self.ef[2::3]] = np.nan
544        self.infd[2::3][self.ed[2::3]] = np.nan
545        self.efnonan = self.ef.copy()
546        self.efnonan[2::3] = False
547        self.ednonan = self.ed.copy()
548        self.ednonan[2::3] = False
549
550        self.signf = self.f.copy()
551        self.signd = self.d.copy()
552        self.signf[self.ef] *= -1.0
553        self.signd[self.ed] *= -1.0
554        self.signf[1::6][self.ef[1::6]] = -np.inf
555        self.signd[1::6][self.ed[1::6]] = -np.inf
556        self.signf[3::6][self.ef[3::6]] = -np.nan
557        self.signd[3::6][self.ed[3::6]] = -np.nan
558        self.signf[4::6][self.ef[4::6]] = -0.0
559        self.signd[4::6][self.ed[4::6]] = -0.0
560
561    def test_float(self):
562        # offset for alignment test
563        for i in range(4):
564            assert_array_equal(self.f[i:] > 0, self.ef[i:])
565            assert_array_equal(self.f[i:] - 1 >= 0, self.ef[i:])
566            assert_array_equal(self.f[i:] == 0, ~self.ef[i:])
567            assert_array_equal(-self.f[i:] < 0, self.ef[i:])
568            assert_array_equal(-self.f[i:] + 1 <= 0, self.ef[i:])
569            r = self.f[i:] != 0
570            assert_array_equal(r, self.ef[i:])
571            r2 = self.f[i:] != np.zeros_like(self.f[i:])
572            r3 = 0 != self.f[i:]
573            assert_array_equal(r, r2)
574            assert_array_equal(r, r3)
575            # check bool == 0x1
576            assert_array_equal(r.view(np.int8), r.astype(np.int8))
577            assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
578            assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
579
580            # isnan on amd64 takes the same code path
581            assert_array_equal(np.isnan(self.nf[i:]), self.ef[i:])
582            assert_array_equal(np.isfinite(self.nf[i:]), ~self.ef[i:])
583            assert_array_equal(np.isfinite(self.inff[i:]), ~self.ef[i:])
584            assert_array_equal(np.isinf(self.inff[i:]), self.efnonan[i:])
585            assert_array_equal(np.signbit(self.signf[i:]), self.ef[i:])
586
587    def test_double(self):
588        # offset for alignment test
589        for i in range(2):
590            assert_array_equal(self.d[i:] > 0, self.ed[i:])
591            assert_array_equal(self.d[i:] - 1 >= 0, self.ed[i:])
592            assert_array_equal(self.d[i:] == 0, ~self.ed[i:])
593            assert_array_equal(-self.d[i:] < 0, self.ed[i:])
594            assert_array_equal(-self.d[i:] + 1 <= 0, self.ed[i:])
595            r = self.d[i:] != 0
596            assert_array_equal(r, self.ed[i:])
597            r2 = self.d[i:] != np.zeros_like(self.d[i:])
598            r3 = 0 != self.d[i:]
599            assert_array_equal(r, r2)
600            assert_array_equal(r, r3)
601            # check bool == 0x1
602            assert_array_equal(r.view(np.int8), r.astype(np.int8))
603            assert_array_equal(r2.view(np.int8), r2.astype(np.int8))
604            assert_array_equal(r3.view(np.int8), r3.astype(np.int8))
605
606            # isnan on amd64 takes the same code path
607            assert_array_equal(np.isnan(self.nd[i:]), self.ed[i:])
608            assert_array_equal(np.isfinite(self.nd[i:]), ~self.ed[i:])
609            assert_array_equal(np.isfinite(self.infd[i:]), ~self.ed[i:])
610            assert_array_equal(np.isinf(self.infd[i:]), self.ednonan[i:])
611            assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:])
612
613
614@xpassIfTorchDynamo  # (reason="TODO")
615class TestSeterr(TestCase):
616    def test_default(self):
617        err = np.geterr()
618        assert_equal(
619            err, dict(divide="warn", invalid="warn", over="warn", under="ignore")
620        )
621
622    def test_set(self):
623        err = np.seterr()
624        old = np.seterr(divide="print")
625        assert_(err == old)
626        new = np.seterr()
627        assert_(new["divide"] == "print")
628        np.seterr(over="raise")
629        assert_(np.geterr()["over"] == "raise")
630        assert_(new["divide"] == "print")
631        np.seterr(**old)
632        assert_(np.geterr() == old)
633
634    @xfail
635    @skipif(IS_WASM, reason="no wasm fp exception support")
636    @skipif(platform.machine() == "armv5tel", reason="See gh-413.")
637    def test_divide_err(self):
638        with assert_raises(FloatingPointError):
639            np.array([1.0]) / np.array([0.0])
640
641        np.seterr(divide="ignore")
642        np.array([1.0]) / np.array([0.0])
643
644    @skipif(IS_WASM, reason="no wasm fp exception support")
645    def test_errobj(self):
646        olderrobj = np.geterrobj()
647        self.called = 0
648        try:
649            with warnings.catch_warnings(record=True) as w:
650                warnings.simplefilter("always")
651                np.seterrobj([20000, 1, None])
652                np.array([1.0]) / np.array([0.0])
653                assert_equal(len(w), 1)
654
655            def log_err(*args):
656                self.called += 1
657                extobj_err = args
658                assert_(len(extobj_err) == 2)
659                assert_("divide" in extobj_err[0])
660
661            np.seterrobj([20000, 3, log_err])
662            np.array([1.0]) / np.array([0.0])
663            assert_equal(self.called, 1)
664
665            np.seterrobj(olderrobj)
666            np.divide(1.0, 0.0, extobj=[20000, 3, log_err])
667            assert_equal(self.called, 2)
668        finally:
669            np.seterrobj(olderrobj)
670            del self.called
671
672
673@xfail  # (reason="TODO")
674@instantiate_parametrized_tests
675class TestFloatExceptions(TestCase):
676    def assert_raises_fpe(self, fpeerr, flop, x, y):
677        ftype = type(x)
678        try:
679            flop(x, y)
680            assert_(False, f"Type {ftype} did not raise fpe error '{fpeerr}'.")
681        except FloatingPointError as exc:
682            assert_(
683                str(exc).find(fpeerr) >= 0,
684                f"Type {ftype} raised wrong fpe error '{exc}'.",
685            )
686
687    def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):
688        # Check that fpe exception is raised.
689        #
690        # Given a floating operation `flop` and two scalar values, check that
691        # the operation raises the floating point exception specified by
692        # `fpeerr`. Tests all variants with 0-d array scalars as well.
693
694        self.assert_raises_fpe(fpeerr, flop, sc1, sc2)
695        self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2)
696        self.assert_raises_fpe(fpeerr, flop, sc1, sc2[()])
697        self.assert_raises_fpe(fpeerr, flop, sc1[()], sc2[()])
698
699    # Test for all real and complex float types
700    @skipif(IS_WASM, reason="no wasm fp exception support")
701    @parametrize("typecode", np.typecodes["AllFloat"])
702    def test_floating_exceptions(self, typecode):
703        # Test basic arithmetic function errors
704        ftype = np.dtype(typecode).type
705        if np.dtype(ftype).kind == "f":
706            # Get some extreme values for the type
707            fi = np.finfo(ftype)
708            ft_tiny = fi._machar.tiny
709            ft_max = fi.max
710            ft_eps = fi.eps
711            underflow = "underflow"
712            divbyzero = "divide by zero"
713        else:
714            # 'c', complex, corresponding real dtype
715            rtype = type(ftype(0).real)
716            fi = np.finfo(rtype)
717            ft_tiny = ftype(fi._machar.tiny)
718            ft_max = ftype(fi.max)
719            ft_eps = ftype(fi.eps)
720            # The complex types raise different exceptions
721            underflow = ""
722            divbyzero = ""
723        overflow = "overflow"
724        invalid = "invalid"
725
726        # The value of tiny for double double is NaN, so we need to
727        # pass the assert
728        if not np.isnan(ft_tiny):
729            self.assert_raises_fpe(underflow, operator.truediv, ft_tiny, ft_max)
730            self.assert_raises_fpe(underflow, operator.mul, ft_tiny, ft_tiny)
731        self.assert_raises_fpe(overflow, operator.mul, ft_max, ftype(2))
732        self.assert_raises_fpe(overflow, operator.truediv, ft_max, ftype(0.5))
733        self.assert_raises_fpe(overflow, operator.add, ft_max, ft_max * ft_eps)
734        self.assert_raises_fpe(overflow, operator.sub, -ft_max, ft_max * ft_eps)
735        self.assert_raises_fpe(overflow, np.power, ftype(2), ftype(2**fi.nexp))
736        self.assert_raises_fpe(divbyzero, operator.truediv, ftype(1), ftype(0))
737        self.assert_raises_fpe(invalid, operator.truediv, ftype(np.inf), ftype(np.inf))
738        self.assert_raises_fpe(invalid, operator.truediv, ftype(0), ftype(0))
739        self.assert_raises_fpe(invalid, operator.sub, ftype(np.inf), ftype(np.inf))
740        self.assert_raises_fpe(invalid, operator.add, ftype(np.inf), ftype(-np.inf))
741        self.assert_raises_fpe(invalid, operator.mul, ftype(0), ftype(np.inf))
742
743    @skipif(IS_WASM, reason="no wasm fp exception support")
744    def test_warnings(self):
745        # test warning code path
746        with warnings.catch_warnings(record=True) as w:
747            warnings.simplefilter("always")
748            np.divide(1, 0.0)
749            assert_equal(len(w), 1)
750            assert_("divide by zero" in str(w[0].message))
751            np.array(1e300) * np.array(1e300)
752            assert_equal(len(w), 2)
753            assert_("overflow" in str(w[-1].message))
754            np.array(np.inf) - np.array(np.inf)
755            assert_equal(len(w), 3)
756            assert_("invalid value" in str(w[-1].message))
757            np.array(1e-300) * np.array(1e-300)
758            assert_equal(len(w), 4)
759            assert_("underflow" in str(w[-1].message))
760
761
762class TestTypes(TestCase):
763    def check_promotion_cases(self, promote_func):
764        # tests that the scalars get coerced correctly.
765        b = np.bool_(0)
766        i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
767        u8 = np.uint8(0)
768        f32, f64 = np.float32(0), np.float64(0)
769        c64, c128 = np.complex64(0), np.complex128(0)
770
771        # coercion within the same kind
772        assert_equal(promote_func(i8, i16), np.dtype(np.int16))
773        assert_equal(promote_func(i32, i8), np.dtype(np.int32))
774        assert_equal(promote_func(i16, i64), np.dtype(np.int64))
775        assert_equal(promote_func(f32, f64), np.dtype(np.float64))
776        assert_equal(promote_func(c128, c64), np.dtype(np.complex128))
777
778        # coercion between kinds
779        assert_equal(promote_func(b, i32), np.dtype(np.int32))
780        assert_equal(promote_func(b, u8), np.dtype(np.uint8))
781        assert_equal(promote_func(i8, u8), np.dtype(np.int16))
782        assert_equal(promote_func(u8, i32), np.dtype(np.int32))
783
784        assert_equal(promote_func(f32, i16), np.dtype(np.float32))
785        assert_equal(promote_func(f32, c64), np.dtype(np.complex64))
786        assert_equal(promote_func(c128, f32), np.dtype(np.complex128))
787
788        # coercion between scalars and 1-D arrays
789        assert_equal(promote_func(np.array([b]), i8), np.dtype(np.int8))
790        assert_equal(promote_func(np.array([b]), u8), np.dtype(np.uint8))
791        assert_equal(promote_func(np.array([b]), i32), np.dtype(np.int32))
792        assert_equal(promote_func(c64, np.array([f64])), np.dtype(np.complex128))
793        assert_equal(
794            promote_func(np.complex64(3j), np.array([f64])), np.dtype(np.complex128)
795        )
796
797        # coercion between scalars and 1-D arrays, where
798        # the scalar has greater kind than the array
799        assert_equal(promote_func(np.array([b]), f64), np.dtype(np.float64))
800        assert_equal(promote_func(np.array([b]), i64), np.dtype(np.int64))
801        assert_equal(promote_func(np.array([i8]), f64), np.dtype(np.float64))
802
803    def check_promotion_cases_2(self, promote_func):
804        # these are failing because of the "scalars do not upcast arrays" rule
805        # Two first tests (i32 + f32 -> f64, and i64+f32 -> f64) xfail
806        # until ufuncs implement the proper type promotion (ufunc loops?)
807        b = np.bool_(0)
808        i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
809        u8 = np.uint8(0)
810        f32, f64 = np.float32(0), np.float64(0)
811        c64, c128 = np.complex64(0), np.complex128(0)
812
813        assert_equal(promote_func(i32, f32), np.dtype(np.float64))
814        assert_equal(promote_func(i64, f32), np.dtype(np.float64))
815
816        assert_equal(promote_func(np.array([i8]), i64), np.dtype(np.int8))
817        assert_equal(promote_func(f64, np.array([f32])), np.dtype(np.float32))
818
819        # float and complex are treated as the same "kind" for
820        # the purposes of array-scalar promotion, so that you can do
821        # (0j + float32array) to get a complex64 array instead of
822        # a complex128 array.
823        assert_equal(promote_func(np.array([f32]), c128), np.dtype(np.complex64))
824
825    def test_coercion(self):
826        def res_type(a, b):
827            return np.add(a, b).dtype
828
829        self.check_promotion_cases(res_type)
830
831        # Use-case: float/complex scalar * bool/int8 array
832        #           shouldn't narrow the float/complex type
833        for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:
834            b = 1.234 * a
835            assert_equal(b.dtype, np.dtype("f8"), f"array type {a.dtype}")
836            b = np.float64(1.234) * a
837            assert_equal(b.dtype, np.dtype("f8"), f"array type {a.dtype}")
838            b = np.float32(1.234) * a
839            assert_equal(b.dtype, np.dtype("f4"), f"array type {a.dtype}")
840            b = np.float16(1.234) * a
841            assert_equal(b.dtype, np.dtype("f2"), f"array type {a.dtype}")
842
843            b = 1.234j * a
844            assert_equal(b.dtype, np.dtype("c16"), f"array type {a.dtype}")
845            b = np.complex128(1.234j) * a
846            assert_equal(b.dtype, np.dtype("c16"), f"array type {a.dtype}")
847            b = np.complex64(1.234j) * a
848            assert_equal(b.dtype, np.dtype("c8"), f"array type {a.dtype}")
849
850        # The following use-case is problematic, and to resolve its
851        # tricky side-effects requires more changes.
852        #
853        # Use-case: (1-t)*a, where 't' is a boolean array and 'a' is
854        #            a float32, shouldn't promote to float64
855        #
856        # a = np.array([1.0, 1.5], dtype=np.float32)
857        # t = np.array([True, False])
858        # b = t*a
859        # assert_equal(b, [1.0, 0.0])
860        # assert_equal(b.dtype, np.dtype('f4'))
861        # b = (1-t)*a
862        # assert_equal(b, [0.0, 1.5])
863        # assert_equal(b.dtype, np.dtype('f4'))
864        #
865        # Probably ~t (bitwise negation) is more proper to use here,
866        # but this is arguably less intuitive to understand at a glance, and
867        # would fail if 't' is actually an integer array instead of boolean:
868        #
869        # b = (~t)*a
870        # assert_equal(b, [0.0, 1.5])
871        # assert_equal(b.dtype, np.dtype('f4'))
872
873    @xpassIfTorchDynamo  # (reason="'Scalars do not upcast arrays' rule")
874    def test_coercion_2(self):
875        def res_type(a, b):
876            return np.add(a, b).dtype
877
878        self.check_promotion_cases_2(res_type)
879
880    def test_result_type(self):
881        self.check_promotion_cases(np.result_type)
882
883    @skip(reason="array(None) not supported")
884    def test_tesult_type_2(self):
885        assert_(np.result_type(None) == np.dtype(None))
886
887    @skip(reason="no endianness in dtypes")
888    def test_promote_types_endian(self):
889        # promote_types should always return native-endian types
890        assert_equal(np.promote_types("<i8", "<i8"), np.dtype("i8"))
891        assert_equal(np.promote_types(">i8", ">i8"), np.dtype("i8"))
892
893    def test_can_cast(self):
894        assert_(np.can_cast(np.int32, np.int64))
895        assert_(np.can_cast(np.float64, complex))
896        assert_(not np.can_cast(complex, float))
897
898        assert_(np.can_cast("i8", "f8"))
899        assert_(not np.can_cast("i8", "f4"))
900
901        assert_(np.can_cast("i8", "i8", "no"))
902
903    @skip(reason="no endianness in dtypes")
904    def test_can_cast_2(self):
905        assert_(not np.can_cast("<i8", ">i8", "no"))
906
907        assert_(np.can_cast("<i8", ">i8", "equiv"))
908        assert_(not np.can_cast("<i4", ">i8", "equiv"))
909
910        assert_(np.can_cast("<i4", ">i8", "safe"))
911        assert_(not np.can_cast("<i8", ">i4", "safe"))
912
913        assert_(np.can_cast("<i8", ">i4", "same_kind"))
914        assert_(not np.can_cast("<i8", ">u4", "same_kind"))
915
916        assert_(np.can_cast("<i8", ">u4", "unsafe"))
917
918        assert_raises(TypeError, np.can_cast, "i4", None)
919        assert_raises(TypeError, np.can_cast, None, "i4")
920
921        # Also test keyword arguments
922        assert_(np.can_cast(from_=np.int32, to=np.int64))
923
924    @xpassIfTorchDynamo  # (reason="value-based casting?")
925    def test_can_cast_values(self):
926        # gh-5917
927        for dt in [np.int8, np.int16, np.int32, np.int64] + [
928            np.uint8,
929            np.uint16,
930            np.uint32,
931            np.uint64,
932        ]:
933            ii = np.iinfo(dt)
934            assert_(np.can_cast(ii.min, dt))
935            assert_(np.can_cast(ii.max, dt))
936            assert_(not np.can_cast(ii.min - 1, dt))
937            assert_(not np.can_cast(ii.max + 1, dt))
938
939        for dt in [np.float16, np.float32, np.float64, np.longdouble]:
940            fi = np.finfo(dt)
941            assert_(np.can_cast(fi.min, dt))
942            assert_(np.can_cast(fi.max, dt))
943
944
945# Custom exception class to test exception propagation in fromiter
946class NIterError(Exception):
947    pass
948
949
950@skip(reason="NP_VER: fails on CI")
951@xpassIfTorchDynamo  # (reason="TODO")
952@instantiate_parametrized_tests
953class TestFromiter(TestCase):
954    def makegen(self):
955        return (x**2 for x in range(24))
956
957    def test_types(self):
958        ai32 = np.fromiter(self.makegen(), np.int32)
959        ai64 = np.fromiter(self.makegen(), np.int64)
960        af = np.fromiter(self.makegen(), float)
961        assert_(ai32.dtype == np.dtype(np.int32))
962        assert_(ai64.dtype == np.dtype(np.int64))
963        assert_(af.dtype == np.dtype(float))
964
965    def test_lengths(self):
966        expected = np.array(list(self.makegen()))
967        a = np.fromiter(self.makegen(), int)
968        a20 = np.fromiter(self.makegen(), int, 20)
969        assert_(len(a) == len(expected))
970        assert_(len(a20) == 20)
971        assert_raises(ValueError, np.fromiter, self.makegen(), int, len(expected) + 10)
972
973    def test_values(self):
974        expected = np.array(list(self.makegen()))
975        a = np.fromiter(self.makegen(), int)
976        a20 = np.fromiter(self.makegen(), int, 20)
977        assert_(np.all(a == expected, axis=0))
978        assert_(np.all(a20 == expected[:20], axis=0))
979
980    def load_data(self, n, eindex):
981        # Utility method for the issue 2592 tests.
982        # Raise an exception at the desired index in the iterator.
983        for e in range(n):
984            if e == eindex:
985                raise NIterError(f"error at index {eindex}")
986            yield e
987
988    @parametrize("dtype", [int])
989    @parametrize("count, error_index", [(10, 5), (10, 9)])
990    def test_2592(self, count, error_index, dtype):
991        # Test iteration exceptions are correctly raised. The data/generator
992        # has `count` elements but errors at `error_index`
993        iterable = self.load_data(count, error_index)
994        with pytest.raises(NIterError):
995            np.fromiter(iterable, dtype=dtype, count=count)
996
997    @skip(reason="NP_VER: fails on CI")
998    def test_empty_result(self):
999        class MyIter:
1000            def __length_hint__(self):
1001                return 10
1002
1003            def __iter__(self):
1004                return iter([])  # actual iterator is empty.
1005
1006        res = np.fromiter(MyIter(), dtype="d")
1007        assert res.shape == (0,)
1008        assert res.dtype == "d"
1009
1010    def test_too_few_items(self):
1011        msg = "iterator too short: Expected 10 but iterator had only 3 items."
1012        with pytest.raises(ValueError, match=msg):
1013            np.fromiter([1, 2, 3], count=10, dtype=int)
1014
1015    def test_failed_itemsetting(self):
1016        with pytest.raises(TypeError):
1017            np.fromiter([1, None, 3], dtype=int)
1018
1019        # The following manages to hit somewhat trickier code paths:
1020        iterable = ((2, 3, 4) for i in range(5))
1021        with pytest.raises(ValueError):
1022            np.fromiter(iterable, dtype=np.dtype((int, 2)))
1023
1024
1025@instantiate_parametrized_tests
1026class TestNonzeroAndCountNonzero(TestCase):
1027    def test_count_nonzero_list(self):
1028        lst = [[0, 1, 2, 3], [1, 0, 0, 6]]
1029        assert np.count_nonzero(lst) == 5
1030        assert_array_equal(np.count_nonzero(lst, axis=0), np.array([1, 1, 1, 2]))
1031        assert_array_equal(np.count_nonzero(lst, axis=1), np.array([3, 2]))
1032
1033    def test_nonzero_trivial(self):
1034        assert_equal(np.count_nonzero(np.array([])), 0)
1035        assert_equal(np.count_nonzero(np.array([], dtype="?")), 0)
1036        assert_equal(np.nonzero(np.array([])), ([],))
1037
1038        assert_equal(np.count_nonzero(np.array([0])), 0)
1039        assert_equal(np.count_nonzero(np.array([0], dtype="?")), 0)
1040        assert_equal(np.nonzero(np.array([0])), ([],))
1041
1042        assert_equal(np.count_nonzero(np.array([1])), 1)
1043        assert_equal(np.count_nonzero(np.array([1], dtype="?")), 1)
1044        assert_equal(np.nonzero(np.array([1])), ([0],))
1045
1046    def test_nonzero_trivial_differs(self):
1047        # numpy returns a python int, we return a 0D array
1048        assert isinstance(np.count_nonzero([]), np.ndarray)
1049
1050    def test_nonzero_zerod(self):
1051        assert_equal(np.count_nonzero(np.array(0)), 0)
1052        assert_equal(np.count_nonzero(np.array(0, dtype="?")), 0)
1053
1054        assert_equal(np.count_nonzero(np.array(1)), 1)
1055        assert_equal(np.count_nonzero(np.array(1, dtype="?")), 1)
1056
1057    def test_nonzero_zerod_differs(self):
1058        # numpy returns a python int, we return a 0D array
1059        assert isinstance(np.count_nonzero(np.array(1)), np.ndarray)
1060
1061    def test_nonzero_onedim(self):
1062        x = np.array([1, 0, 2, -1, 0, 0, 8])
1063        assert_equal(np.count_nonzero(x), 4)
1064        assert_equal(np.count_nonzero(x), 4)
1065        assert_equal(np.nonzero(x), ([0, 2, 3, 6],))
1066
1067    def test_nonzero_onedim_differs(self):
1068        # numpy returns a python int, we return a 0D array
1069        x = np.array([1, 0, 2, -1, 0, 0, 8])
1070        assert isinstance(np.count_nonzero(x), np.ndarray)
1071
1072    def test_nonzero_twodim(self):
1073        x = np.array([[0, 1, 0], [2, 0, 3]])
1074        assert_equal(np.count_nonzero(x.astype("i1")), 3)
1075        assert_equal(np.count_nonzero(x.astype("i2")), 3)
1076        assert_equal(np.count_nonzero(x.astype("i4")), 3)
1077        assert_equal(np.count_nonzero(x.astype("i8")), 3)
1078        assert_equal(np.nonzero(x), ([0, 1, 1], [1, 0, 2]))
1079
1080        x = np.eye(3)
1081        assert_equal(np.count_nonzero(x.astype("i1")), 3)
1082        assert_equal(np.count_nonzero(x.astype("i2")), 3)
1083        assert_equal(np.count_nonzero(x.astype("i4")), 3)
1084        assert_equal(np.count_nonzero(x.astype("i8")), 3)
1085        assert_equal(np.nonzero(x), ([0, 1, 2], [0, 1, 2]))
1086
1087    def test_sparse(self):
1088        # test special sparse condition boolean code path
1089        for i in range(20):
1090            c = np.zeros(200, dtype=bool)
1091            c[i::20] = True
1092            assert_equal(np.nonzero(c)[0], np.arange(i, 200 + i, 20))
1093
1094            c = np.zeros(400, dtype=bool)
1095            c[10 + i : 20 + i] = True
1096            c[20 + i * 2] = True
1097            assert_equal(
1098                np.nonzero(c)[0],
1099                np.concatenate((np.arange(10 + i, 20 + i), [20 + i * 2])),
1100            )
1101
1102    def test_count_nonzero_axis(self):
1103        # Basic check of functionality
1104        m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
1105
1106        expected = np.array([1, 1, 1, 1, 1])
1107        assert_array_equal(np.count_nonzero(m, axis=0), expected)
1108
1109        expected = np.array([2, 3])
1110        assert_array_equal(np.count_nonzero(m, axis=1), expected)
1111
1112        assert isinstance(np.count_nonzero(m, axis=1), np.ndarray)
1113
1114        assert_raises(ValueError, np.count_nonzero, m, axis=(1, 1))
1115        assert_raises(TypeError, np.count_nonzero, m, axis="foo")
1116        assert_raises(np.AxisError, np.count_nonzero, m, axis=3)
1117        assert_raises(TypeError, np.count_nonzero, m, axis=np.array([[1], [2]]))
1118
1119    @parametrize("typecode", "efdFDBbhil?")
1120    def test_count_nonzero_axis_all_dtypes(self, typecode):
1121        # More thorough test that the axis argument is respected
1122        # for all dtypes and responds correctly when presented with
1123        # either integer or tuple arguments for axis
1124
1125        m = np.zeros((3, 3), dtype=typecode)
1126        n = np.ones(1, dtype=typecode)
1127
1128        m[0, 0] = n[0]
1129        m[1, 0] = n[0]
1130
1131        expected = np.array([2, 0, 0], dtype=np.intp)
1132        result = np.count_nonzero(m, axis=0)
1133        assert_array_equal(result, expected)
1134        assert expected.dtype == result.dtype
1135
1136        expected = np.array([1, 1, 0], dtype=np.intp)
1137        result = np.count_nonzero(m, axis=1)
1138        assert_array_equal(result, expected)
1139        assert expected.dtype == result.dtype
1140
1141        expected = np.array(2)
1142        assert_array_equal(np.count_nonzero(m, axis=(0, 1)), expected)
1143        assert_array_equal(np.count_nonzero(m, axis=None), expected)
1144        assert_array_equal(np.count_nonzero(m), expected)
1145
1146    def test_countnonzero_axis_empty(self):
1147        a = np.array([[0, 0, 1], [1, 0, 1]])
1148        assert_equal(np.count_nonzero(a, axis=()), a.astype(bool))
1149
1150    def test_countnonzero_keepdims(self):
1151        a = np.array([[0, 0, 1, 0], [0, 3, 5, 0], [7, 9, 2, 0]])
1152        assert_array_equal(np.count_nonzero(a, axis=0, keepdims=True), [[1, 2, 3, 0]])
1153        assert_array_equal(np.count_nonzero(a, axis=1, keepdims=True), [[1], [2], [3]])
1154        assert_array_equal(np.count_nonzero(a, keepdims=True), [[6]])
1155        assert isinstance(np.count_nonzero(a, axis=1, keepdims=True), np.ndarray)
1156
1157
1158class TestIndex(TestCase):
1159    def test_boolean(self):
1160        a = rand(3, 5, 8)
1161        V = rand(5, 8)
1162        g1 = randint(0, 5, size=15)
1163        g2 = randint(0, 8, size=15)
1164        V[g1, g2] = -V[g1, g2]
1165        assert_(
1166            (np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all()
1167        )
1168
1169    def test_boolean_edgecase(self):
1170        a = np.array([], dtype="int32")
1171        b = np.array([], dtype="bool")
1172        c = a[b]
1173        assert_equal(c, [])
1174        assert_equal(c.dtype, np.dtype("int32"))
1175
1176
1177@xpassIfTorchDynamo  # (reason="TODO")
1178class TestBinaryRepr(TestCase):
1179    def test_zero(self):
1180        assert_equal(np.binary_repr(0), "0")
1181
1182    def test_positive(self):
1183        assert_equal(np.binary_repr(10), "1010")
1184        assert_equal(np.binary_repr(12522), "11000011101010")
1185        assert_equal(np.binary_repr(10736848), "101000111101010011010000")
1186
1187    def test_negative(self):
1188        assert_equal(np.binary_repr(-1), "-1")
1189        assert_equal(np.binary_repr(-10), "-1010")
1190        assert_equal(np.binary_repr(-12522), "-11000011101010")
1191        assert_equal(np.binary_repr(-10736848), "-101000111101010011010000")
1192
1193    def test_sufficient_width(self):
1194        assert_equal(np.binary_repr(0, width=5), "00000")
1195        assert_equal(np.binary_repr(10, width=7), "0001010")
1196        assert_equal(np.binary_repr(-5, width=7), "1111011")
1197
1198    def test_neg_width_boundaries(self):
1199        # see gh-8670
1200
1201        # Ensure that the example in the issue does not
1202        # break before proceeding to a more thorough test.
1203        assert_equal(np.binary_repr(-128, width=8), "10000000")
1204
1205        for width in range(1, 11):
1206            num = -(2 ** (width - 1))
1207            exp = "1" + (width - 1) * "0"
1208            assert_equal(np.binary_repr(num, width=width), exp)
1209
1210    def test_large_neg_int64(self):
1211        # See gh-14289.
1212        assert_equal(np.binary_repr(np.int64(-(2**62)), width=64), "11" + "0" * 62)
1213
1214
1215@xpassIfTorchDynamo  # (reason="TODO")
1216class TestBaseRepr(TestCase):
1217    def test_base3(self):
1218        assert_equal(np.base_repr(3**5, 3), "100000")
1219
1220    def test_positive(self):
1221        assert_equal(np.base_repr(12, 10), "12")
1222        assert_equal(np.base_repr(12, 10, 4), "000012")
1223        assert_equal(np.base_repr(12, 4), "30")
1224        assert_equal(np.base_repr(3731624803700888, 36), "10QR0ROFCEW")
1225
1226    def test_negative(self):
1227        assert_equal(np.base_repr(-12, 10), "-12")
1228        assert_equal(np.base_repr(-12, 10, 4), "-000012")
1229        assert_equal(np.base_repr(-12, 4), "-30")
1230
1231    def test_base_range(self):
1232        with assert_raises(ValueError):
1233            np.base_repr(1, 1)
1234        with assert_raises(ValueError):
1235            np.base_repr(1, 37)
1236
1237
1238class TestArrayComparisons(TestCase):
1239    def test_array_equal(self):
1240        res = np.array_equal(np.array([1, 2]), np.array([1, 2]))
1241        assert_(res)
1242        assert_(type(res) is bool)
1243        res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3]))
1244        assert_(not res)
1245        assert_(type(res) is bool)
1246        res = np.array_equal(np.array([1, 2]), np.array([3, 4]))
1247        assert_(not res)
1248        assert_(type(res) is bool)
1249        res = np.array_equal(np.array([1, 2]), np.array([1, 3]))
1250        assert_(not res)
1251        assert_(type(res) is bool)
1252
1253    def test_array_equal_equal_nan(self):
1254        # Test array_equal with equal_nan kwarg
1255        a1 = np.array([1, 2, np.nan])
1256        a2 = np.array([1, np.nan, 2])
1257        a3 = np.array([1, 2, np.inf])
1258
1259        # equal_nan=False by default
1260        assert_(not np.array_equal(a1, a1))
1261        assert_(np.array_equal(a1, a1, equal_nan=True))
1262        assert_(not np.array_equal(a1, a2, equal_nan=True))
1263        # nan's not conflated with inf's
1264        assert_(not np.array_equal(a1, a3, equal_nan=True))
1265        # 0-D arrays
1266        a = np.array(np.nan)
1267        assert_(not np.array_equal(a, a))
1268        assert_(np.array_equal(a, a, equal_nan=True))
1269        # Non-float dtype - equal_nan should have no effect
1270        a = np.array([1, 2, 3], dtype=int)
1271        assert_(np.array_equal(a, a))
1272        assert_(np.array_equal(a, a, equal_nan=True))
1273        # Multi-dimensional array
1274        a = np.array([[0, 1], [np.nan, 1]])
1275        assert_(not np.array_equal(a, a))
1276        assert_(np.array_equal(a, a, equal_nan=True))
1277        # Complex values
1278        a, b = [np.array([1 + 1j])] * 2
1279        a.real, b.imag = np.nan, np.nan
1280        assert_(not np.array_equal(a, b, equal_nan=False))
1281        assert_(np.array_equal(a, b, equal_nan=True))
1282
1283    def test_none_compares_elementwise(self):
1284        a = np.ones(3)
1285        assert_equal(a.__eq__(None), [False, False, False])
1286        assert_equal(a.__ne__(None), [True, True, True])
1287
1288    def test_array_equiv(self):
1289        res = np.array_equiv(np.array([1, 2]), np.array([1, 2]))
1290        assert_(res)
1291        assert_(type(res) is bool)
1292        res = np.array_equiv(np.array([1, 2]), np.array([1, 2, 3]))
1293        assert_(not res)
1294        assert_(type(res) is bool)
1295        res = np.array_equiv(np.array([1, 2]), np.array([3, 4]))
1296        assert_(not res)
1297        assert_(type(res) is bool)
1298        res = np.array_equiv(np.array([1, 2]), np.array([1, 3]))
1299        assert_(not res)
1300        assert_(type(res) is bool)
1301
1302        res = np.array_equiv(np.array([1, 1]), np.array([1]))
1303        assert_(res)
1304        assert_(type(res) is bool)
1305        res = np.array_equiv(np.array([1, 1]), np.array([[1], [1]]))
1306        assert_(res)
1307        assert_(type(res) is bool)
1308        res = np.array_equiv(np.array([1, 2]), np.array([2]))
1309        assert_(not res)
1310        assert_(type(res) is bool)
1311        res = np.array_equiv(np.array([1, 2]), np.array([[1], [2]]))
1312        assert_(not res)
1313        assert_(type(res) is bool)
1314        res = np.array_equiv(
1315            np.array([1, 2]), np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1316        )
1317        assert_(not res)
1318        assert_(type(res) is bool)
1319
1320
1321@instantiate_parametrized_tests
1322class TestClip(TestCase):
1323    def setUp(self):
1324        super().setUp()
1325        self.nr = 5
1326        self.nc = 3
1327
1328    def fastclip(self, a, m, M, out=None, casting=None):
1329        if out is None:
1330            if casting is None:
1331                return a.clip(m, M)
1332            else:
1333                return a.clip(m, M, casting=casting)
1334        else:
1335            if casting is None:
1336                return a.clip(m, M, out)
1337            else:
1338                return a.clip(m, M, out, casting=casting)
1339
1340    def clip(self, a, m, M, out=None):
1341        # use slow-clip
1342        selector = np.less(a, m) + 2 * np.greater(a, M)
1343        return selector.choose((a, m, M), out=out)
1344
1345    # Handy functions
1346    def _generate_data(self, n, m):
1347        return randn(n, m)
1348
1349    def _generate_data_complex(self, n, m):
1350        return randn(n, m) + 1.0j * rand(n, m)
1351
1352    def _generate_flt_data(self, n, m):
1353        return (randn(n, m)).astype(np.float32)
1354
1355    def _neg_byteorder(self, a):
1356        a = np.asarray(a)
1357        if sys.byteorder == "little":
1358            a = a.astype(a.dtype.newbyteorder(">"))
1359        else:
1360            a = a.astype(a.dtype.newbyteorder("<"))
1361        return a
1362
1363    def _generate_non_native_data(self, n, m):
1364        data = randn(n, m)
1365        data = self._neg_byteorder(data)
1366        assert_(not data.dtype.isnative)
1367        return data
1368
1369    def _generate_int_data(self, n, m):
1370        return (10 * rand(n, m)).astype(np.int64)
1371
1372    def _generate_int32_data(self, n, m):
1373        return (10 * rand(n, m)).astype(np.int32)
1374
1375    # Now the real test cases
1376
1377    @parametrize("dtype", "?bhilBfd")
1378    def test_ones_pathological(self, dtype):
1379        # for preservation of behavior described in
1380        # gh-12519; amin > amax behavior may still change
1381        # in the future
1382        arr = np.ones(10, dtype=dtype)
1383        expected = np.zeros(10, dtype=dtype)
1384        actual = np.clip(arr, 1, 0)
1385        assert_equal(actual, expected)
1386
1387    @parametrize("dtype", "eFD")
1388    def test_ones_pathological_2(self, dtype):
1389        if dtype in "FD":
1390            # FIXME: make xfail
1391            raise SkipTest("torch.clamp not implemented for complex types")
1392        # for preservation of behavior described in
1393        # gh-12519; amin > amax behavior may still change
1394        # in the future
1395        arr = np.ones(10, dtype=dtype)
1396        expected = np.zeros(10, dtype=dtype)
1397        actual = np.clip(arr, 1, 0)
1398        assert_equal(actual, expected)
1399
1400    def test_simple_double(self):
1401        # Test native double input with scalar min/max.
1402        a = self._generate_data(self.nr, self.nc)
1403        m = 0.1
1404        M = 0.6
1405        ac = self.fastclip(a, m, M)
1406        act = self.clip(a, m, M)
1407        assert_array_equal(ac, act)
1408
1409    def test_simple_int(self):
1410        # Test native int input with scalar min/max.
1411        a = self._generate_int_data(self.nr, self.nc)
1412        a = a.astype(int)
1413        m = -2
1414        M = 4
1415        ac = self.fastclip(a, m, M)
1416        act = self.clip(a, m, M)
1417        assert_array_equal(ac, act)
1418
1419    def test_array_double(self):
1420        # Test native double input with array min/max.
1421        a = self._generate_data(self.nr, self.nc)
1422        m = np.zeros(a.shape)
1423        M = m + 0.5
1424        ac = self.fastclip(a, m, M)
1425        act = self.clip(a, m, M)
1426        assert_array_equal(ac, act)
1427
1428    @xpassIfTorchDynamo  # (reason="byteorder not supported in torch")
1429    def test_simple_nonnative(self):
1430        # Test non native double input with scalar min/max.
1431        # Test native double input with non native double scalar min/max.
1432        a = self._generate_non_native_data(self.nr, self.nc)
1433        m = -0.5
1434        M = 0.6
1435        ac = self.fastclip(a, m, M)
1436        act = self.clip(a, m, M)
1437        assert_array_equal(ac, act)
1438
1439        # Test native double input with non native double scalar min/max.
1440        a = self._generate_data(self.nr, self.nc)
1441        m = -0.5
1442        M = self._neg_byteorder(0.6)
1443        assert_(not M.dtype.isnative)
1444        ac = self.fastclip(a, m, M)
1445        act = self.clip(a, m, M)
1446        assert_array_equal(ac, act)
1447
1448    @xpassIfTorchDynamo  # (reason="clamp not supported for complex")
1449    def test_simple_complex(self):
1450        # Test native complex input with native double scalar min/max.
1451        # Test native input with complex double scalar min/max.
1452        a = 3 * self._generate_data_complex(self.nr, self.nc)
1453        m = -0.5
1454        M = 1.0
1455        ac = self.fastclip(a, m, M)
1456        act = self.clip(a, m, M)
1457        assert_array_equal(ac, act)
1458
1459        # Test native input with complex double scalar min/max.
1460        a = 3 * self._generate_data(self.nr, self.nc)
1461        m = -0.5 + 1.0j
1462        M = 1.0 + 2.0j
1463        ac = self.fastclip(a, m, M)
1464        act = self.clip(a, m, M)
1465        assert_array_equal(ac, act)
1466
1467    @xfail  # (reason="clamp not supported for complex")
1468    def test_clip_complex(self):
1469        # Address Issue gh-5354 for clipping complex arrays
1470        # Test native complex input without explicit min/max
1471        # ie, either min=None or max=None
1472        a = np.ones(10, dtype=complex)
1473        m = a.min()
1474        M = a.max()
1475        am = self.fastclip(a, m, None)
1476        aM = self.fastclip(a, None, M)
1477        assert_array_equal(am, a)
1478        assert_array_equal(aM, a)
1479
1480    def test_clip_non_contig(self):
1481        # Test clip for non contiguous native input and native scalar min/max.
1482        a = self._generate_data(self.nr * 2, self.nc * 3)
1483        a = a[::2, ::3]
1484        assert_(not a.flags["F_CONTIGUOUS"])
1485        assert_(not a.flags["C_CONTIGUOUS"])
1486        ac = self.fastclip(a, -1.6, 1.7)
1487        act = self.clip(a, -1.6, 1.7)
1488        assert_array_equal(ac, act)
1489
1490    def test_simple_out(self):
1491        # Test native double input with scalar min/max.
1492        a = self._generate_data(self.nr, self.nc)
1493        m = -0.5
1494        M = 0.6
1495        ac = np.zeros(a.shape)
1496        act = np.zeros(a.shape)
1497        self.fastclip(a, m, M, ac)
1498        self.clip(a, m, M, act)
1499        assert_array_equal(ac, act)
1500
1501    #   @xpassIfTorchDynamo  # (reason="casting not supported")
1502    @parametrize(
1503        "casting",
1504        [
1505            subtest(None, decorators=[xfail]),
1506            subtest("unsafe", decorators=[xpassIfTorchDynamo]),
1507        ],
1508    )
1509    def test_simple_int32_inout(self, casting):
1510        # Test native int32 input with double min/max and int32 out.
1511        a = self._generate_int32_data(self.nr, self.nc)
1512        m = np.float64(0)
1513        M = np.float64(2)
1514        ac = np.zeros(a.shape, dtype=np.int32)
1515        act = ac.copy()
1516        if casting is not None:
1517            # explicitly passing "unsafe" will silence warning
1518            self.fastclip(a, m, M, ac, casting=casting)
1519        self.clip(a, m, M, act)
1520        assert_array_equal(ac, act)
1521
1522    def test_simple_int64_out(self):
1523        # Test native int32 input with int32 scalar min/max and int64 out.
1524        a = self._generate_int32_data(self.nr, self.nc)
1525        m = np.int32(-1)
1526        M = np.int32(1)
1527        ac = np.zeros(a.shape, dtype=np.int64)
1528        act = ac.copy()
1529        self.fastclip(a, m, M, ac)
1530        self.clip(a, m, M, act)
1531        assert_array_equal(ac, act)
1532
1533    @xfail  # (reason="FIXME arrays not equal")
1534    def test_simple_int64_inout(self):
1535        # Test native int32 input with double array min/max and int32 out.
1536        a = self._generate_int32_data(self.nr, self.nc)
1537        m = np.zeros(a.shape, np.float64)
1538        M = np.float64(1)
1539        ac = np.zeros(a.shape, dtype=np.int32)
1540        act = ac.copy()
1541        self.clip(a, m, M, act)
1542        assert_array_equal(ac, act)
1543
1544    @xfail  # (reason="FIXME arrays not equal")
1545    def test_simple_int32_out(self):
1546        # Test native double input with scalar min/max and int out.
1547        a = self._generate_data(self.nr, self.nc)
1548        m = -1.0
1549        M = 2.0
1550        ac = np.zeros(a.shape, dtype=np.int32)
1551        act = ac.copy()
1552        self.clip(a, m, M, act)
1553        assert_array_equal(ac, act)
1554
1555    def test_simple_inplace_01(self):
1556        # Test native double input with array min/max in-place.
1557        a = self._generate_data(self.nr, self.nc)
1558        ac = a.copy()
1559        m = np.zeros(a.shape)
1560        M = 1.0
1561        self.fastclip(a, m, M, a)
1562        self.clip(a, m, M, ac)
1563        assert_array_equal(a, ac)
1564
1565    def test_simple_inplace_02(self):
1566        # Test native double input with scalar min/max in-place.
1567        a = self._generate_data(self.nr, self.nc)
1568        ac = a.copy()
1569        m = -0.5
1570        M = 0.6
1571        self.fastclip(a, m, M, a)
1572        self.clip(ac, m, M, ac)
1573        assert_array_equal(a, ac)
1574
1575    def test_noncontig_inplace(self):
1576        # Test non contiguous double input with double scalar min/max in-place.
1577        a = self._generate_data(self.nr * 2, self.nc * 3)
1578        a = a[::2, ::3]
1579        assert_(not a.flags["F_CONTIGUOUS"])
1580        assert_(not a.flags["C_CONTIGUOUS"])
1581        ac = a.copy()
1582        m = -0.5
1583        M = 0.6
1584        self.fastclip(a, m, M, a)
1585        self.clip(ac, m, M, ac)
1586        assert_array_equal(a, ac)
1587
1588    def test_type_cast_01(self):
1589        # Test native double input with scalar min/max.
1590        a = self._generate_data(self.nr, self.nc)
1591        m = -0.5
1592        M = 0.6
1593        ac = self.fastclip(a, m, M)
1594        act = self.clip(a, m, M)
1595        assert_array_equal(ac, act)
1596
1597    def test_type_cast_02(self):
1598        # Test native int32 input with int32 scalar min/max.
1599        a = self._generate_int_data(self.nr, self.nc)
1600        a = a.astype(np.int32)
1601        m = -2
1602        M = 4
1603        ac = self.fastclip(a, m, M)
1604        act = self.clip(a, m, M)
1605        assert_array_equal(ac, act)
1606
1607    def test_type_cast_03(self):
1608        # Test native int32 input with float64 scalar min/max.
1609        a = self._generate_int32_data(self.nr, self.nc)
1610        m = -2
1611        M = 4
1612        ac = self.fastclip(a, np.float64(m), np.float64(M))
1613        act = self.clip(a, np.float64(m), np.float64(M))
1614        assert_array_equal(ac, act)
1615
1616    def test_type_cast_04(self):
1617        # Test native int32 input with float32 scalar min/max.
1618        a = self._generate_int32_data(self.nr, self.nc)
1619        m = np.float32(-2)
1620        M = np.float32(4)
1621        act = self.fastclip(a, m, M)
1622        ac = self.clip(a, m, M)
1623        assert_array_equal(ac, act)
1624
1625    def test_type_cast_05(self):
1626        # Test native int32 with double arrays min/max.
1627        a = self._generate_int_data(self.nr, self.nc)
1628        m = -0.5
1629        M = 1.0
1630        ac = self.fastclip(a, m * np.zeros(a.shape), M)
1631        act = self.clip(a, m * np.zeros(a.shape), M)
1632        assert_array_equal(ac, act)
1633
1634    @xpassIfTorchDynamo  # (reason="newbyteorder not supported")
1635    def test_type_cast_06(self):
1636        # Test native with NON native scalar min/max.
1637        a = self._generate_data(self.nr, self.nc)
1638        m = 0.5
1639        m_s = self._neg_byteorder(m)
1640        M = 1.0
1641        act = self.clip(a, m_s, M)
1642        ac = self.fastclip(a, m_s, M)
1643        assert_array_equal(ac, act)
1644
1645    @xpassIfTorchDynamo  # (reason="newbyteorder not supported")
1646    def test_type_cast_07(self):
1647        # Test NON native with native array min/max.
1648        a = self._generate_data(self.nr, self.nc)
1649        m = -0.5 * np.ones(a.shape)
1650        M = 1.0
1651        a_s = self._neg_byteorder(a)
1652        assert_(not a_s.dtype.isnative)
1653        act = a_s.clip(m, M)
1654        ac = self.fastclip(a_s, m, M)
1655        assert_array_equal(ac, act)
1656
1657    @xpassIfTorchDynamo  # (reason="newbyteorder not supported")
1658    def test_type_cast_08(self):
1659        # Test NON native with native scalar min/max.
1660        a = self._generate_data(self.nr, self.nc)
1661        m = -0.5
1662        M = 1.0
1663        a_s = self._neg_byteorder(a)
1664        assert_(not a_s.dtype.isnative)
1665        ac = self.fastclip(a_s, m, M)
1666        act = a_s.clip(m, M)
1667        assert_array_equal(ac, act)
1668
1669    @xpassIfTorchDynamo  # (reason="newbyteorder not supported")
1670    def test_type_cast_09(self):
1671        # Test native with NON native array min/max.
1672        a = self._generate_data(self.nr, self.nc)
1673        m = -0.5 * np.ones(a.shape)
1674        M = 1.0
1675        m_s = self._neg_byteorder(m)
1676        assert_(not m_s.dtype.isnative)
1677        ac = self.fastclip(a, m_s, M)
1678        act = self.clip(a, m_s, M)
1679        assert_array_equal(ac, act)
1680
1681    def test_type_cast_10(self):
1682        # Test native int32 with float min/max and float out for output argument.
1683        a = self._generate_int_data(self.nr, self.nc)
1684        b = np.zeros(a.shape, dtype=np.float32)
1685        m = np.float32(-0.5)
1686        M = np.float32(1)
1687        act = self.clip(a, m, M, out=b)
1688        ac = self.fastclip(a, m, M, out=b)
1689        assert_array_equal(ac, act)
1690
1691    @xpassIfTorchDynamo  # (reason="newbyteorder not supported")
1692    def test_type_cast_11(self):
1693        # Test non native with native scalar, min/max, out non native
1694        a = self._generate_non_native_data(self.nr, self.nc)
1695        b = a.copy()
1696        b = b.astype(b.dtype.newbyteorder(">"))
1697        bt = b.copy()
1698        m = -0.5
1699        M = 1.0
1700        self.fastclip(a, m, M, out=b)
1701        self.clip(a, m, M, out=bt)
1702        assert_array_equal(b, bt)
1703
1704    def test_type_cast_12(self):
1705        # Test native int32 input and min/max and float out
1706        a = self._generate_int_data(self.nr, self.nc)
1707        b = np.zeros(a.shape, dtype=np.float32)
1708        m = np.int32(0)
1709        M = np.int32(1)
1710        act = self.clip(a, m, M, out=b)
1711        ac = self.fastclip(a, m, M, out=b)
1712        assert_array_equal(ac, act)
1713
1714    def test_clip_with_out_simple(self):
1715        # Test native double input with scalar min/max
1716        a = self._generate_data(self.nr, self.nc)
1717        m = -0.5
1718        M = 0.6
1719        ac = np.zeros(a.shape)
1720        act = np.zeros(a.shape)
1721        self.fastclip(a, m, M, ac)
1722        self.clip(a, m, M, act)
1723        assert_array_equal(ac, act)
1724
1725    @xfail  # (reason="FIXME arrays not equal")
1726    def test_clip_with_out_simple2(self):
1727        # Test native int32 input with double min/max and int32 out
1728        a = self._generate_int32_data(self.nr, self.nc)
1729        m = np.float64(0)
1730        M = np.float64(2)
1731        ac = np.zeros(a.shape, dtype=np.int32)
1732        act = ac.copy()
1733        self.clip(a, m, M, act)
1734        assert_array_equal(ac, act)
1735
1736    def test_clip_with_out_simple_int32(self):
1737        # Test native int32 input with int32 scalar min/max and int64 out
1738        a = self._generate_int32_data(self.nr, self.nc)
1739        m = np.int32(-1)
1740        M = np.int32(1)
1741        ac = np.zeros(a.shape, dtype=np.int64)
1742        act = ac.copy()
1743        self.fastclip(a, m, M, ac)
1744        self.clip(a, m, M, act)
1745        assert_array_equal(ac, act)
1746
1747    @xfail  # (reason="FIXME arrays not equal")
1748    def test_clip_with_out_array_int32(self):
1749        # Test native int32 input with double array min/max and int32 out
1750        a = self._generate_int32_data(self.nr, self.nc)
1751        m = np.zeros(a.shape, np.float64)
1752        M = np.float64(1)
1753        ac = np.zeros(a.shape, dtype=np.int32)
1754        act = ac.copy()
1755        self.clip(a, m, M, act)
1756        assert_array_equal(ac, act)
1757
1758    @xfail  # (reason="FIXME arrays not equal")
1759    def test_clip_with_out_array_outint32(self):
1760        # Test native double input with scalar min/max and int out
1761        a = self._generate_data(self.nr, self.nc)
1762        m = -1.0
1763        M = 2.0
1764        ac = np.zeros(a.shape, dtype=np.int32)
1765        act = ac.copy()
1766        self.clip(a, m, M, act)
1767        assert_array_equal(ac, act)
1768
1769    def test_clip_with_out_transposed(self):
1770        # Test that the out argument works when transposed
1771        a = np.arange(16).reshape(4, 4)
1772        out = np.empty_like(a).T
1773        a.clip(4, 10, out=out)
1774        expected = self.clip(a, 4, 10)
1775        assert_array_equal(out, expected)
1776
1777    def test_clip_with_out_memory_overlap(self):
1778        # Test that the out argument works when it has memory overlap
1779        a = np.arange(16).reshape(4, 4)
1780        ac = a.copy()
1781        a[:-1].clip(4, 10, out=a[1:])
1782        expected = self.clip(ac[:-1], 4, 10)
1783        assert_array_equal(a[1:], expected)
1784
1785    def test_clip_inplace_array(self):
1786        # Test native double input with array min/max
1787        a = self._generate_data(self.nr, self.nc)
1788        ac = a.copy()
1789        m = np.zeros(a.shape)
1790        M = 1.0
1791        self.fastclip(a, m, M, a)
1792        self.clip(a, m, M, ac)
1793        assert_array_equal(a, ac)
1794
1795    def test_clip_inplace_simple(self):
1796        # Test native double input with scalar min/max
1797        a = self._generate_data(self.nr, self.nc)
1798        ac = a.copy()
1799        m = -0.5
1800        M = 0.6
1801        self.fastclip(a, m, M, a)
1802        self.clip(a, m, M, ac)
1803        assert_array_equal(a, ac)
1804
1805    def test_clip_func_takes_out(self):
1806        # Ensure that the clip() function takes an out=argument.
1807        a = self._generate_data(self.nr, self.nc)
1808        ac = a.copy()
1809        m = -0.5
1810        M = 0.6
1811        a2 = np.clip(a, m, M, out=a)
1812        self.clip(a, m, M, ac)
1813        assert_array_equal(a2, ac)
1814        assert_(a2 is a)
1815
1816    @skip(reason="Edge case; Wait until deprecation graduates")
1817    def test_clip_nan(self):
1818        d = np.arange(7.0)
1819        with assert_warns(DeprecationWarning):
1820            assert_equal(d.clip(min=np.nan), d)
1821        with assert_warns(DeprecationWarning):
1822            assert_equal(d.clip(max=np.nan), d)
1823        with assert_warns(DeprecationWarning):
1824            assert_equal(d.clip(min=np.nan, max=np.nan), d)
1825        with assert_warns(DeprecationWarning):
1826            assert_equal(d.clip(min=-2, max=np.nan), d)
1827        with assert_warns(DeprecationWarning):
1828            assert_equal(d.clip(min=np.nan, max=10), d)
1829
1830    @parametrize(
1831        "amin, amax",
1832        [
1833            # two scalars
1834            (1, 0),
1835            # mix scalar and array
1836            (1, np.zeros(10)),
1837            # two arrays
1838            (np.ones(10), np.zeros(10)),
1839        ],
1840    )
1841    def test_clip_value_min_max_flip(self, amin, amax):
1842        a = np.arange(10, dtype=np.int64)
1843        # requirement from ufunc_docstrings.py
1844        expected = np.minimum(np.maximum(a, amin), amax)
1845        actual = np.clip(a, amin, amax)
1846        assert_equal(actual, expected)
1847
1848    @parametrize(
1849        "arr, amin, amax",
1850        [
1851            # problematic scalar nan case from hypothesis
1852            (
1853                np.zeros(10, dtype=np.int64),
1854                np.array(np.nan),
1855                np.zeros(10, dtype=np.int32),
1856            ),
1857        ],
1858    )
1859    def test_clip_scalar_nan_propagation(self, arr, amin, amax):
1860        # enforcement of scalar nan propagation for comparisons
1861        # called through clip()
1862        expected = np.minimum(np.maximum(arr, amin), amax)
1863        actual = np.clip(arr, amin, amax)
1864        assert_equal(actual, expected)
1865
1866    @skip  # hypothesis hynp.from_dtype fails on CI (versions?)
1867    @given(
1868        data=st.data(),
1869        arr=hynp.arrays(
1870            dtype=hynp.integer_dtypes() | hynp.floating_dtypes(),
1871            shape=hynp.array_shapes(),
1872        ),
1873    )
1874    def test_clip_property(self, data, arr):
1875        """A property-based test using Hypothesis.
1876
1877        This aims for maximum generality: it could in principle generate *any*
1878        valid inputs to np.clip, and in practice generates much more varied
1879        inputs than human testers come up with.
1880
1881        Because many of the inputs have tricky dependencies - compatible dtypes
1882        and mutually-broadcastable shapes - we use `st.data()` strategy draw
1883        values *inside* the test function, from strategies we construct based
1884        on previous values.  An alternative would be to define a custom strategy
1885        with `@st.composite`, but until we have duplicated code inline is fine.
1886
1887        That accounts for most of the function; the actual test is just three
1888        lines to calculate and compare actual vs expected results!
1889        """
1890        numeric_dtypes = hynp.integer_dtypes() | hynp.floating_dtypes()
1891        # Generate shapes for the bounds which can be broadcast with each other
1892        # and with the base shape.  Below, we might decide to use scalar bounds,
1893        # but it's clearer to generate these shapes unconditionally in advance.
1894        in_shapes, result_shape = data.draw(
1895            hynp.mutually_broadcastable_shapes(num_shapes=2, base_shape=arr.shape)
1896        )
1897        # Scalar `nan` is deprecated due to the differing behaviour it shows.
1898        s = numeric_dtypes.flatmap(lambda x: hynp.from_dtype(x, allow_nan=False))
1899        amin = data.draw(
1900            s
1901            | hynp.arrays(
1902                dtype=numeric_dtypes, shape=in_shapes[0], elements={"allow_nan": False}
1903            )
1904        )
1905        amax = data.draw(
1906            s
1907            | hynp.arrays(
1908                dtype=numeric_dtypes, shape=in_shapes[1], elements={"allow_nan": False}
1909            )
1910        )
1911
1912        # Then calculate our result and expected result and check that they're
1913        # equal!  See gh-12519 and gh-19457 for discussion deciding on this
1914        # property and the result_type argument.
1915        result = np.clip(arr, amin, amax)
1916        t = np.result_type(arr, amin, amax)
1917        expected = np.minimum(amax, np.maximum(arr, amin, dtype=t), dtype=t)
1918        assert result.dtype == t
1919        assert_array_equal(result, expected)
1920
1921
1922class TestAllclose(TestCase):
1923    rtol = 1e-5
1924    atol = 1e-8
1925
1926    def tst_allclose(self, x, y):
1927        assert_(np.allclose(x, y), f"{x} and {y} not close")
1928
1929    def tst_not_allclose(self, x, y):
1930        assert_(not np.allclose(x, y), f"{x} and {y} shouldn't be close")
1931
1932    def test_ip_allclose(self):
1933        # Parametric test factory.
1934        arr = np.array([100, 1000])
1935        aran = np.arange(125).reshape((5, 5, 5))
1936
1937        atol = self.atol
1938        rtol = self.rtol
1939
1940        data = [
1941            ([1, 0], [1, 0]),
1942            ([atol], [0]),
1943            ([1], [1 + rtol + atol]),
1944            (arr, arr + arr * rtol),
1945            (arr, arr + arr * rtol + atol * 2),
1946            (aran, aran + aran * rtol),
1947            (np.inf, np.inf),
1948            (np.inf, [np.inf]),
1949        ]
1950
1951        for x, y in data:
1952            self.tst_allclose(x, y)
1953
1954    def test_ip_not_allclose(self):
1955        # Parametric test factory.
1956        aran = np.arange(125).reshape((5, 5, 5))
1957
1958        atol = self.atol
1959        rtol = self.rtol
1960
1961        data = [
1962            ([np.inf, 0], [1, np.inf]),
1963            ([np.inf, 0], [1, 0]),
1964            ([np.inf, np.inf], [1, np.inf]),
1965            ([np.inf, np.inf], [1, 0]),
1966            ([-np.inf, 0], [np.inf, 0]),
1967            ([np.nan, 0], [np.nan, 0]),
1968            ([atol * 2], [0]),
1969            ([1], [1 + rtol + atol * 2]),
1970            (aran, aran + aran * atol + atol * 2),
1971            (np.array([np.inf, 1]), np.array([0, np.inf])),
1972        ]
1973
1974        for x, y in data:
1975            self.tst_not_allclose(x, y)
1976
1977    def test_no_parameter_modification(self):
1978        x = np.array([np.inf, 1])
1979        y = np.array([0, np.inf])
1980        np.allclose(x, y)
1981        assert_array_equal(x, np.array([np.inf, 1]))
1982        assert_array_equal(y, np.array([0, np.inf]))
1983
1984    def test_min_int(self):
1985        # Could make problems because of abs(min_int) == min_int
1986        min_int = np.iinfo(np.int_).min
1987        a = np.array([min_int], dtype=np.int_)
1988        assert_(np.allclose(a, a))
1989
1990    def test_equalnan(self):
1991        x = np.array([1.0, np.nan])
1992        assert_(np.allclose(x, x, equal_nan=True))
1993
1994
1995class TestIsclose(TestCase):
1996    rtol = 1e-5
1997    atol = 1e-8
1998
1999    def _setup(self):
2000        atol = self.atol
2001        rtol = self.rtol
2002        arr = np.array([100, 1000])
2003        aran = np.arange(125).reshape((5, 5, 5))
2004
2005        self.all_close_tests = [
2006            ([1, 0], [1, 0]),
2007            ([atol], [0]),
2008            ([1], [1 + rtol + atol]),
2009            (arr, arr + arr * rtol),
2010            (arr, arr + arr * rtol + atol),
2011            (aran, aran + aran * rtol),
2012            (np.inf, np.inf),
2013            (np.inf, [np.inf]),
2014            ([np.inf, -np.inf], [np.inf, -np.inf]),
2015        ]
2016        self.none_close_tests = [
2017            ([np.inf, 0], [1, np.inf]),
2018            ([np.inf, -np.inf], [1, 0]),
2019            ([np.inf, np.inf], [1, -np.inf]),
2020            ([np.inf, np.inf], [1, 0]),
2021            ([np.nan, 0], [np.nan, -np.inf]),
2022            ([atol * 2], [0]),
2023            ([1], [1 + rtol + atol * 2]),
2024            (aran, aran + rtol * 1.1 * aran + atol * 1.1),
2025            (np.array([np.inf, 1]), np.array([0, np.inf])),
2026        ]
2027        self.some_close_tests = [
2028            ([np.inf, 0], [np.inf, atol * 2]),
2029            ([atol, 1, 1e6 * (1 + 2 * rtol) + atol], [0, np.nan, 1e6]),
2030            (np.arange(3), [0, 1, 2.1]),
2031            (np.nan, [np.nan, np.nan, np.nan]),
2032            ([0], [atol, np.inf, -np.inf, np.nan]),
2033            (0, [atol, np.inf, -np.inf, np.nan]),
2034        ]
2035        self.some_close_results = [
2036            [True, False],
2037            [True, False, False],
2038            [True, True, False],
2039            [False, False, False],
2040            [True, False, False, False],
2041            [True, False, False, False],
2042        ]
2043
2044    def test_ip_isclose(self):
2045        self._setup()
2046        tests = self.some_close_tests
2047        results = self.some_close_results
2048        for (x, y), result in zip(tests, results):
2049            assert_array_equal(np.isclose(x, y), result)
2050
2051    def tst_all_isclose(self, x, y):
2052        assert_(np.all(np.isclose(x, y)), f"{x} and {y} not close")
2053
2054    def tst_none_isclose(self, x, y):
2055        msg = "%s and %s shouldn't be close"
2056        assert_(not np.any(np.isclose(x, y)), msg % (x, y))
2057
2058    def tst_isclose_allclose(self, x, y):
2059        msg = "isclose.all() and allclose aren't same for %s and %s"
2060        msg2 = "isclose and allclose aren't same for %s and %s"
2061        if np.isscalar(x) and np.isscalar(y):
2062            assert_(np.isclose(x, y) == np.allclose(x, y), msg=msg2 % (x, y))
2063        else:
2064            assert_array_equal(np.isclose(x, y).all(), np.allclose(x, y), msg % (x, y))
2065
2066    def test_ip_all_isclose(self):
2067        self._setup()
2068        for x, y in self.all_close_tests:
2069            self.tst_all_isclose(x, y)
2070
2071    def test_ip_none_isclose(self):
2072        self._setup()
2073        for x, y in self.none_close_tests:
2074            self.tst_none_isclose(x, y)
2075
2076    def test_ip_isclose_allclose(self):
2077        self._setup()
2078        tests = self.all_close_tests + self.none_close_tests + self.some_close_tests
2079        for x, y in tests:
2080            self.tst_isclose_allclose(x, y)
2081
2082    def test_equal_nan(self):
2083        assert_array_equal(np.isclose(np.nan, np.nan, equal_nan=True), [True])
2084        arr = np.array([1.0, np.nan])
2085        assert_array_equal(np.isclose(arr, arr, equal_nan=True), [True, True])
2086
2087    @xfailIfTorchDynamo  # scalars vs 0D
2088    def test_scalar_return(self):
2089        assert_(np.isscalar(np.isclose(1, 1)))
2090
2091    def test_no_parameter_modification(self):
2092        x = np.array([np.inf, 1])
2093        y = np.array([0, np.inf])
2094        np.isclose(x, y)
2095        assert_array_equal(x, np.array([np.inf, 1]))
2096        assert_array_equal(y, np.array([0, np.inf]))
2097
2098    def test_non_finite_scalar(self):
2099        # GH7014, when two scalars are compared the output should also be a
2100        # scalar
2101        # XXX: test modified since there are array scalars
2102        assert_(np.isclose(np.inf, -np.inf).item() is False)
2103        assert_(np.isclose(0, np.inf).item() is False)
2104
2105
2106class TestStdVar(TestCase):
2107    def setUp(self):
2108        super().setUp()
2109        self.A = np.array([1, -1, 1, -1])
2110        self.real_var = 1
2111
2112    def test_basic(self):
2113        assert_almost_equal(np.var(self.A), self.real_var)
2114        assert_almost_equal(np.std(self.A) ** 2, self.real_var)
2115
2116    def test_scalars(self):
2117        assert_equal(np.var(1), 0)
2118        assert_equal(np.std(1), 0)
2119
2120    def test_ddof1(self):
2121        assert_almost_equal(
2122            np.var(self.A, ddof=1), self.real_var * len(self.A) / (len(self.A) - 1)
2123        )
2124        assert_almost_equal(
2125            np.std(self.A, ddof=1) ** 2, self.real_var * len(self.A) / (len(self.A) - 1)
2126        )
2127
2128    def test_ddof2(self):
2129        assert_almost_equal(
2130            np.var(self.A, ddof=2), self.real_var * len(self.A) / (len(self.A) - 2)
2131        )
2132        assert_almost_equal(
2133            np.std(self.A, ddof=2) ** 2, self.real_var * len(self.A) / (len(self.A) - 2)
2134        )
2135
2136    def test_out_scalar(self):
2137        d = np.arange(10)
2138        out = np.array(0.0)
2139        r = np.std(d, out=out)
2140        assert_(r is out)
2141        assert_array_equal(r, out)
2142        r = np.var(d, out=out)
2143        assert_(r is out)
2144        assert_array_equal(r, out)
2145        r = np.mean(d, out=out)
2146        assert_(r is out)
2147        assert_array_equal(r, out)
2148
2149
2150class TestStdVarComplex(TestCase):
2151    def test_basic(self):
2152        A = np.array([1, 1.0j, -1, -1.0j])
2153        real_var = 1
2154        assert_almost_equal(np.var(A), real_var)
2155        assert_almost_equal(np.std(A) ** 2, real_var)
2156
2157    def test_scalars(self):
2158        assert_equal(np.var(1j), 0)
2159        assert_equal(np.std(1j), 0)
2160
2161
2162class TestCreationFuncs(TestCase):
2163    # Test ones, zeros, empty and full.
2164
2165    def setUp(self):
2166        super().setUp()
2167        dtypes = {np.dtype(tp) for tp in "efdFDBbhil?"}
2168        self.dtypes = dtypes
2169        self.orders = {
2170            "C": "c_contiguous"
2171        }  # XXX: reeenable when implemented, 'F': 'f_contiguous'}
2172        self.ndims = 10
2173
2174    def check_function(self, func, fill_value=None):
2175        par = ((0, 1, 2), range(self.ndims), self.orders, self.dtypes)
2176        fill_kwarg = {}
2177        if fill_value is not None:
2178            fill_kwarg = {"fill_value": fill_value}
2179
2180        for size, ndims, order, dtype in itertools.product(*par):
2181            shape = ndims * [size]
2182
2183            arr = func(shape, order=order, dtype=dtype, **fill_kwarg)
2184
2185            assert_equal(arr.dtype, dtype)
2186            assert_(getattr(arr.flags, self.orders[order]))
2187
2188            if fill_value is not None:
2189                val = fill_value
2190                assert_equal(arr, dtype.type(val))
2191
2192    def test_zeros(self):
2193        self.check_function(np.zeros)
2194
2195    def test_ones(self):
2196        self.check_function(np.ones)
2197
2198    def test_empty(self):
2199        self.check_function(np.empty)
2200
2201    def test_full(self):
2202        self.check_function(np.full, 0)
2203        self.check_function(np.full, 1)
2204
2205    @skipif(TEST_WITH_TORCHDYNAMO, reason="fails with dynamo")
2206    @skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
2207    def test_for_reference_leak(self):
2208        # Make sure we have an object for reference
2209        dim = 1
2210        beg = sys.getrefcount(dim)
2211        np.zeros([dim] * 10)
2212        assert_(sys.getrefcount(dim) == beg)
2213        np.ones([dim] * 10)
2214        assert_(sys.getrefcount(dim) == beg)
2215        np.empty([dim] * 10)
2216        assert_(sys.getrefcount(dim) == beg)
2217        np.full([dim] * 10, 0)
2218        assert_(sys.getrefcount(dim) == beg)
2219
2220
2221@skip(reason="implement order etc")  # FIXME: make xfail
2222@instantiate_parametrized_tests
2223class TestLikeFuncs(TestCase):
2224    """Test ones_like, zeros_like, empty_like and full_like"""
2225
2226    def setUp(self):
2227        super().setUp()
2228        self.data = [
2229            # Array scalars
2230            (np.array(3.0), None),
2231            (np.array(3), "f8"),
2232            # 1D arrays
2233            (np.arange(6, dtype="f4"), None),
2234            (np.arange(6), "c16"),
2235            # 2D C-layout arrays
2236            (np.arange(6).reshape(2, 3), None),
2237            (np.arange(6).reshape(3, 2), "i1"),
2238            # 2D F-layout arrays
2239            (np.arange(6).reshape((2, 3), order="F"), None),
2240            (np.arange(6).reshape((3, 2), order="F"), "i1"),
2241            # 3D C-layout arrays
2242            (np.arange(24).reshape(2, 3, 4), None),
2243            (np.arange(24).reshape(4, 3, 2), "f4"),
2244            # 3D F-layout arrays
2245            (np.arange(24).reshape((2, 3, 4), order="F"), None),
2246            (np.arange(24).reshape((4, 3, 2), order="F"), "f4"),
2247            # 3D non-C/F-layout arrays
2248            (np.arange(24).reshape(2, 3, 4).swapaxes(0, 1), None),
2249            (np.arange(24).reshape(4, 3, 2).swapaxes(0, 1), "?"),
2250        ]
2251        self.shapes = [
2252            (),
2253            (5,),
2254            (
2255                5,
2256                6,
2257            ),
2258            (
2259                5,
2260                6,
2261                7,
2262            ),
2263        ]
2264
2265    def compare_array_value(self, dz, value, fill_value):
2266        if value is not None:
2267            if fill_value:
2268                # Conversion is close to what np.full_like uses
2269                # but we  may want to convert directly in the future
2270                # which may result in errors (where this does not).
2271                z = np.array(value).astype(dz.dtype)
2272                assert_(np.all(dz == z))
2273            else:
2274                assert_(np.all(dz == value))
2275
2276    def check_like_function(self, like_function, value, fill_value=False):
2277        if fill_value:
2278            fill_kwarg = {"fill_value": value}
2279        else:
2280            fill_kwarg = {}
2281        for d, dtype in self.data:
2282            # default (K) order, dtype
2283            dz = like_function(d, dtype=dtype, **fill_kwarg)
2284            assert_equal(dz.shape, d.shape)
2285            assert_equal(
2286                np.array(dz.strides) * d.dtype.itemsize,
2287                np.array(d.strides) * dz.dtype.itemsize,
2288            )
2289            assert_equal(d.flags.c_contiguous, dz.flags.c_contiguous)
2290            assert_equal(d.flags.f_contiguous, dz.flags.f_contiguous)
2291            if dtype is None:
2292                assert_equal(dz.dtype, d.dtype)
2293            else:
2294                assert_equal(dz.dtype, np.dtype(dtype))
2295            self.compare_array_value(dz, value, fill_value)
2296
2297            # C order, default dtype
2298            dz = like_function(d, order="C", dtype=dtype, **fill_kwarg)
2299            assert_equal(dz.shape, d.shape)
2300            assert_(dz.flags.c_contiguous)
2301            if dtype is None:
2302                assert_equal(dz.dtype, d.dtype)
2303            else:
2304                assert_equal(dz.dtype, np.dtype(dtype))
2305            self.compare_array_value(dz, value, fill_value)
2306
2307            # F order, default dtype
2308            dz = like_function(d, order="F", dtype=dtype, **fill_kwarg)
2309            assert_equal(dz.shape, d.shape)
2310            assert_(dz.flags.f_contiguous)
2311            if dtype is None:
2312                assert_equal(dz.dtype, d.dtype)
2313            else:
2314                assert_equal(dz.dtype, np.dtype(dtype))
2315            self.compare_array_value(dz, value, fill_value)
2316
2317            # A order
2318            dz = like_function(d, order="A", dtype=dtype, **fill_kwarg)
2319            assert_equal(dz.shape, d.shape)
2320            if d.flags.f_contiguous:
2321                assert_(dz.flags.f_contiguous)
2322            else:
2323                assert_(dz.flags.c_contiguous)
2324            if dtype is None:
2325                assert_equal(dz.dtype, d.dtype)
2326            else:
2327                assert_equal(dz.dtype, np.dtype(dtype))
2328            self.compare_array_value(dz, value, fill_value)
2329
2330            # Test the 'shape' parameter
2331            for s in self.shapes:
2332                for o in "CFA":
2333                    sz = like_function(d, dtype=dtype, shape=s, order=o, **fill_kwarg)
2334                    assert_equal(sz.shape, s)
2335                    if dtype is None:
2336                        assert_equal(sz.dtype, d.dtype)
2337                    else:
2338                        assert_equal(sz.dtype, np.dtype(dtype))
2339                    if o == "C" or (o == "A" and d.flags.c_contiguous):
2340                        assert_(sz.flags.c_contiguous)
2341                    elif o == "F" or (o == "A" and d.flags.f_contiguous):
2342                        assert_(sz.flags.f_contiguous)
2343                    self.compare_array_value(sz, value, fill_value)
2344
2345                if d.ndim != len(s):
2346                    assert_equal(
2347                        np.argsort(
2348                            like_function(
2349                                d, dtype=dtype, shape=s, order="K", **fill_kwarg
2350                            ).strides
2351                        ),
2352                        np.argsort(np.empty(s, dtype=dtype, order="C").strides),
2353                    )
2354                else:
2355                    assert_equal(
2356                        np.argsort(
2357                            like_function(
2358                                d, dtype=dtype, shape=s, order="K", **fill_kwarg
2359                            ).strides
2360                        ),
2361                        np.argsort(d.strides),
2362                    )
2363
2364    def test_ones_like(self):
2365        self.check_like_function(np.ones_like, 1)
2366
2367    def test_zeros_like(self):
2368        self.check_like_function(np.zeros_like, 0)
2369
2370    def test_empty_like(self):
2371        self.check_like_function(np.empty_like, None)
2372
2373    def test_filled_like(self):
2374        self.check_like_function(np.full_like, 0, True)
2375        self.check_like_function(np.full_like, 1, True)
2376        self.check_like_function(np.full_like, 1000, True)
2377        self.check_like_function(np.full_like, 123.456, True)
2378        # Inf to integer casts cause invalid-value errors: ignore them.
2379        self.check_like_function(np.full_like, np.inf, True)
2380
2381    @parametrize("likefunc", [np.empty_like, np.full_like, np.zeros_like, np.ones_like])
2382    @parametrize("dtype", [str, bytes])
2383    def test_dtype_str_bytes(self, likefunc, dtype):
2384        # Regression test for gh-19860
2385        a = np.arange(16).reshape(2, 8)
2386        b = a[:, ::2]  # Ensure b is not contiguous.
2387        kwargs = {"fill_value": ""} if likefunc == np.full_like else {}
2388        result = likefunc(b, dtype=dtype, **kwargs)
2389        if dtype == str:
2390            assert result.strides == (16, 4)
2391        else:
2392            # dtype is bytes
2393            assert result.strides == (4, 1)
2394
2395
2396class TestCorrelate(TestCase):
2397    def _setup(self, dt):
2398        self.x = np.array([1, 2, 3, 4, 5], dtype=dt)
2399        self.xs = np.arange(1, 20)[::3]
2400        self.y = np.array([-1, -2, -3], dtype=dt)
2401        self.z1 = np.array([-3.0, -8.0, -14.0, -20.0, -26.0, -14.0, -5.0], dtype=dt)
2402        self.z1_4 = np.array([-2.0, -5.0, -8.0, -11.0, -14.0, -5.0], dtype=dt)
2403        self.z1r = np.array([-15.0, -22.0, -22.0, -16.0, -10.0, -4.0, -1.0], dtype=dt)
2404        self.z2 = np.array([-5.0, -14.0, -26.0, -20.0, -14.0, -8.0, -3.0], dtype=dt)
2405        self.z2r = np.array([-1.0, -4.0, -10.0, -16.0, -22.0, -22.0, -15.0], dtype=dt)
2406        self.zs = np.array(
2407            [-3.0, -14.0, -30.0, -48.0, -66.0, -84.0, -102.0, -54.0, -19.0], dtype=dt
2408        )
2409
2410    def test_float(self):
2411        self._setup(float)
2412        z = np.correlate(self.x, self.y, "full")
2413        assert_array_almost_equal(z, self.z1)
2414        z = np.correlate(self.x, self.y[:-1], "full")
2415        assert_array_almost_equal(z, self.z1_4)
2416        z = np.correlate(self.y, self.x, "full")
2417        assert_array_almost_equal(z, self.z2)
2418        z = np.correlate(np.flip(self.x), self.y, "full")
2419        assert_array_almost_equal(z, self.z1r)
2420        z = np.correlate(self.y, np.flip(self.x), "full")
2421        assert_array_almost_equal(z, self.z2r)
2422        z = np.correlate(self.xs, self.y, "full")
2423        assert_array_almost_equal(z, self.zs)
2424
2425    def test_no_overwrite(self):
2426        d = np.ones(100)
2427        k = np.ones(3)
2428        np.correlate(d, k)
2429        assert_array_equal(d, np.ones(100))
2430        assert_array_equal(k, np.ones(3))
2431
2432    def test_complex(self):
2433        x = np.array([1, 2, 3, 4 + 1j], dtype=complex)
2434        y = np.array([-1, -2j, 3 + 1j], dtype=complex)
2435        r_z = np.array([3 - 1j, 6, 8 + 1j, 11 + 5j, -5 + 8j, -4 - 1j], dtype=complex)
2436        r_z = np.flip(r_z).conjugate()
2437        z = np.correlate(y, x, mode="full")
2438        assert_array_almost_equal(z, r_z)
2439
2440    def test_zero_size(self):
2441        with pytest.raises((ValueError, RuntimeError)):
2442            np.correlate(np.array([]), np.ones(1000), mode="full")
2443        with pytest.raises((ValueError, RuntimeError)):
2444            np.correlate(np.ones(1000), np.array([]), mode="full")
2445
2446    @skip(reason="do not implement deprecated behavior")
2447    def test_mode(self):
2448        d = np.ones(100)
2449        k = np.ones(3)
2450        default_mode = np.correlate(d, k, mode="valid")
2451        with assert_warns(DeprecationWarning):
2452            valid_mode = np.correlate(d, k, mode="v")
2453        assert_array_equal(valid_mode, default_mode)
2454        # integer mode
2455        with assert_raises(ValueError):
2456            np.correlate(d, k, mode=-1)
2457        assert_array_equal(np.correlate(d, k, mode=0), valid_mode)
2458        # illegal arguments
2459        with assert_raises(TypeError):
2460            np.correlate(d, k, mode=None)
2461
2462
2463class TestConvolve(TestCase):
2464    def test_object(self):
2465        d = [1.0] * 100
2466        k = [1.0] * 3
2467        assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))
2468
2469    def test_no_overwrite(self):
2470        d = np.ones(100)
2471        k = np.ones(3)
2472        np.convolve(d, k)
2473        assert_array_equal(d, np.ones(100))
2474        assert_array_equal(k, np.ones(3))
2475
2476    @skip(reason="do not implement deprecated behavior")
2477    def test_mode(self):
2478        d = np.ones(100)
2479        k = np.ones(3)
2480        default_mode = np.convolve(d, k, mode="full")
2481        with assert_warns(DeprecationWarning):
2482            full_mode = np.convolve(d, k, mode="f")
2483        assert_array_equal(full_mode, default_mode)
2484        # integer mode
2485        with assert_raises(ValueError):
2486            np.convolve(d, k, mode=-1)
2487        assert_array_equal(np.convolve(d, k, mode=2), full_mode)
2488        # illegal arguments
2489        with assert_raises(TypeError):
2490            np.convolve(d, k, mode=None)
2491
2492    def test_numpy_doc_examples(self):
2493        conv = np.convolve([1, 2, 3], [0, 1, 0.5])
2494        assert_allclose(conv, [0.0, 1.0, 2.5, 4.0, 1.5], atol=1e-15)
2495
2496        conv = np.convolve([1, 2, 3], [0, 1, 0.5], "same")
2497        assert_allclose(conv, [1.0, 2.5, 4.0], atol=1e-15)
2498
2499        conv = np.convolve([1, 2, 3], [0, 1, 0.5], "valid")
2500        assert_allclose(conv, [2.5], atol=1e-15)
2501
2502
2503class TestDtypePositional(TestCase):
2504    def test_dtype_positional(self):
2505        np.empty((2,), bool)
2506
2507
2508@instantiate_parametrized_tests
2509class TestArgwhere(TestCase):
2510    @parametrize("nd", [0, 1, 2])
2511    def test_nd(self, nd):
2512        # get an nd array with multiple elements in every dimension
2513        x = np.empty((2,) * nd, dtype=bool)
2514
2515        # none
2516        x[...] = False
2517        assert_equal(np.argwhere(x).shape, (0, nd))
2518
2519        # only one
2520        x[...] = False
2521        x.ravel()[0] = True
2522        assert_equal(np.argwhere(x).shape, (1, nd))
2523
2524        # all but one
2525        x[...] = True
2526        x.ravel()[0] = False
2527        assert_equal(np.argwhere(x).shape, (x.size - 1, nd))
2528
2529        # all
2530        x[...] = True
2531        assert_equal(np.argwhere(x).shape, (x.size, nd))
2532
2533    def test_2D(self):
2534        x = np.arange(6).reshape((2, 3))
2535        assert_array_equal(np.argwhere(x > 1), [[0, 2], [1, 0], [1, 1], [1, 2]])
2536
2537    def test_list(self):
2538        assert_equal(np.argwhere([4, 0, 2, 1, 3]), [[0], [2], [3], [4]])
2539
2540
2541@xpassIfTorchDynamo  # (reason="TODO")
2542class TestStringFunction(TestCase):
2543    def test_set_string_function(self):
2544        a = np.array([1])
2545        np.set_string_function(lambda x: "FOO", repr=True)
2546        assert_equal(repr(a), "FOO")
2547        np.set_string_function(None, repr=True)
2548        assert_equal(repr(a), "array([1])")
2549
2550        np.set_string_function(lambda x: "FOO", repr=False)
2551        assert_equal(str(a), "FOO")
2552        np.set_string_function(None, repr=False)
2553        assert_equal(str(a), "[1]")
2554
2555
2556class TestRoll(TestCase):
2557    def test_roll1d(self):
2558        x = np.arange(10)
2559        xr = np.roll(x, 2)
2560        assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]))
2561
2562    def test_roll2d(self):
2563        x2 = np.reshape(np.arange(10), (2, 5))
2564        x2r = np.roll(x2, 1)
2565        assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]))
2566
2567        x2r = np.roll(x2, 1, axis=0)
2568        assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
2569
2570        x2r = np.roll(x2, 1, axis=1)
2571        assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
2572
2573        # Roll multiple axes at once.
2574        x2r = np.roll(x2, 1, axis=(0, 1))
2575        assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
2576
2577        x2r = np.roll(x2, (1, 0), axis=(0, 1))
2578        assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
2579
2580        x2r = np.roll(x2, (-1, 0), axis=(0, 1))
2581        assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]))
2582
2583        x2r = np.roll(x2, (0, 1), axis=(0, 1))
2584        assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
2585
2586        x2r = np.roll(x2, (0, -1), axis=(0, 1))
2587        assert_equal(x2r, np.array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]))
2588
2589        x2r = np.roll(x2, (1, 1), axis=(0, 1))
2590        assert_equal(x2r, np.array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]))
2591
2592        x2r = np.roll(x2, (-1, -1), axis=(0, 1))
2593        assert_equal(x2r, np.array([[6, 7, 8, 9, 5], [1, 2, 3, 4, 0]]))
2594
2595        # Roll the same axis multiple times.
2596        x2r = np.roll(x2, 1, axis=(0, 0))
2597        assert_equal(x2r, np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]))
2598
2599        x2r = np.roll(x2, 1, axis=(1, 1))
2600        assert_equal(x2r, np.array([[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]))
2601
2602        # Roll more than one turn in either direction.
2603        x2r = np.roll(x2, 6, axis=1)
2604        assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
2605
2606        x2r = np.roll(x2, -4, axis=1)
2607        assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]))
2608
2609    def test_roll_empty(self):
2610        x = np.array([])
2611        assert_equal(np.roll(x, 1), np.array([]))
2612
2613
2614class TestRollaxis(TestCase):
2615    # expected shape indexed by (axis, start) for array of
2616    # shape (1, 2, 3, 4)
2617    tgtshape = {
2618        (0, 0): (1, 2, 3, 4),
2619        (0, 1): (1, 2, 3, 4),
2620        (0, 2): (2, 1, 3, 4),
2621        (0, 3): (2, 3, 1, 4),
2622        (0, 4): (2, 3, 4, 1),
2623        (1, 0): (2, 1, 3, 4),
2624        (1, 1): (1, 2, 3, 4),
2625        (1, 2): (1, 2, 3, 4),
2626        (1, 3): (1, 3, 2, 4),
2627        (1, 4): (1, 3, 4, 2),
2628        (2, 0): (3, 1, 2, 4),
2629        (2, 1): (1, 3, 2, 4),
2630        (2, 2): (1, 2, 3, 4),
2631        (2, 3): (1, 2, 3, 4),
2632        (2, 4): (1, 2, 4, 3),
2633        (3, 0): (4, 1, 2, 3),
2634        (3, 1): (1, 4, 2, 3),
2635        (3, 2): (1, 2, 4, 3),
2636        (3, 3): (1, 2, 3, 4),
2637        (3, 4): (1, 2, 3, 4),
2638    }
2639
2640    def test_exceptions(self):
2641        a = np.arange(1 * 2 * 3 * 4).reshape(1, 2, 3, 4)
2642        assert_raises(np.AxisError, np.rollaxis, a, -5, 0)
2643        assert_raises(np.AxisError, np.rollaxis, a, 0, -5)
2644        assert_raises(np.AxisError, np.rollaxis, a, 4, 0)
2645        assert_raises(np.AxisError, np.rollaxis, a, 0, 5)
2646
2647    @xfail  # XXX: ndarray.attributes
2648    def test_results(self):
2649        a = np.arange(1 * 2 * 3 * 4).reshape(1, 2, 3, 4).copy()
2650        aind = np.indices(a.shape)
2651        assert_(a.flags["OWNDATA"])
2652        for i, j in self.tgtshape:
2653            # positive axis, positive start
2654            res = np.rollaxis(a, axis=i, start=j)
2655            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
2656            assert_(np.all(res[i0, i1, i2, i3] == a))
2657            assert_(res.shape == self.tgtshape[(i, j)], str((i, j)))
2658            assert_(not res.flags["OWNDATA"])
2659
2660            # negative axis, positive start
2661            ip = i + 1
2662            res = np.rollaxis(a, axis=-ip, start=j)
2663            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
2664            assert_(np.all(res[i0, i1, i2, i3] == a))
2665            assert_(res.shape == self.tgtshape[(4 - ip, j)])
2666            assert_(not res.flags["OWNDATA"])
2667
2668            # positive axis, negative start
2669            jp = j + 1 if j < 4 else j
2670            res = np.rollaxis(a, axis=i, start=-jp)
2671            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
2672            assert_(np.all(res[i0, i1, i2, i3] == a))
2673            assert_(res.shape == self.tgtshape[(i, 4 - jp)])
2674            assert_(not res.flags["OWNDATA"])
2675
2676            # negative axis, negative start
2677            ip = i + 1
2678            jp = j + 1 if j < 4 else j
2679            res = np.rollaxis(a, axis=-ip, start=-jp)
2680            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
2681            assert_(np.all(res[i0, i1, i2, i3] == a))
2682            assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)])
2683            assert_(not res.flags["OWNDATA"])
2684
2685
2686class TestMoveaxis(TestCase):
2687    def test_move_to_end(self):
2688        x = np.random.randn(5, 6, 7)
2689        for source, expected in [
2690            (0, (6, 7, 5)),
2691            (1, (5, 7, 6)),
2692            (2, (5, 6, 7)),
2693            (-1, (5, 6, 7)),
2694        ]:
2695            actual = np.moveaxis(x, source, -1).shape
2696            assert_(actual, expected)
2697
2698    def test_move_new_position(self):
2699        x = np.random.randn(1, 2, 3, 4)
2700        for source, destination, expected in [
2701            (0, 1, (2, 1, 3, 4)),
2702            (1, 2, (1, 3, 2, 4)),
2703            (1, -1, (1, 3, 4, 2)),
2704        ]:
2705            actual = np.moveaxis(x, source, destination).shape
2706            assert_(actual, expected)
2707
2708    def test_preserve_order(self):
2709        x = np.zeros((1, 2, 3, 4))
2710        for source, destination in [
2711            (0, 0),
2712            (3, -1),
2713            (-1, 3),
2714            ([0, -1], [0, -1]),
2715            ([2, 0], [2, 0]),
2716            (range(4), range(4)),
2717        ]:
2718            actual = np.moveaxis(x, source, destination).shape
2719            assert_(actual, (1, 2, 3, 4))
2720
2721    def test_move_multiples(self):
2722        x = np.zeros((0, 1, 2, 3))
2723        for source, destination, expected in [
2724            ([0, 1], [2, 3], (2, 3, 0, 1)),
2725            ([2, 3], [0, 1], (2, 3, 0, 1)),
2726            ([0, 1, 2], [2, 3, 0], (2, 3, 0, 1)),
2727            ([3, 0], [1, 0], (0, 3, 1, 2)),
2728            ([0, 3], [0, 1], (0, 3, 1, 2)),
2729        ]:
2730            actual = np.moveaxis(x, source, destination).shape
2731            assert_(actual, expected)
2732
2733    def test_errors(self):
2734        x = np.random.randn(1, 2, 3)
2735        assert_raises(np.AxisError, np.moveaxis, x, 3, 0)  # 'source.*out of bounds',
2736        assert_raises(np.AxisError, np.moveaxis, x, -4, 0)  # 'source.*out of bounds',
2737        assert_raises(
2738            np.AxisError, np.moveaxis, x, 0, 5  # 'destination.*out of bounds',
2739        )
2740        assert_raises(
2741            ValueError, np.moveaxis, x, [0, 0], [0, 1]  # 'repeated axis in `source`',
2742        )
2743        assert_raises(
2744            ValueError,  # 'repeated axis in `destination`',
2745            np.moveaxis,
2746            x,
2747            [0, 1],
2748            [1, 1],
2749        )
2750        assert_raises(
2751            (ValueError, RuntimeError),  # 'must have the same number',
2752            np.moveaxis,
2753            x,
2754            0,
2755            [0, 1],
2756        )
2757        assert_raises(
2758            (ValueError, RuntimeError),  # 'must have the same number',
2759            np.moveaxis,
2760            x,
2761            [0, 1],
2762            [0],
2763        )
2764
2765        x = [1, 2, 3]
2766        result = np.moveaxis(x, 0, 0)
2767        assert_(x, list(result))
2768        assert_(isinstance(result, np.ndarray))
2769
2770
2771class TestCross(TestCase):
2772    def test_2x2(self):
2773        u = [1, 2]
2774        v = [3, 4]
2775        z = -2
2776        cp = np.cross(u, v)
2777        assert_equal(cp, z)
2778        cp = np.cross(v, u)
2779        assert_equal(cp, -z)
2780
2781    def test_2x3(self):
2782        u = [1, 2]
2783        v = [3, 4, 5]
2784        z = np.array([10, -5, -2])
2785        cp = np.cross(u, v)
2786        assert_equal(cp, z)
2787        cp = np.cross(v, u)
2788        assert_equal(cp, -z)
2789
2790    def test_3x3(self):
2791        u = [1, 2, 3]
2792        v = [4, 5, 6]
2793        z = np.array([-3, 6, -3])
2794        cp = np.cross(u, v)
2795        assert_equal(cp, z)
2796        cp = np.cross(v, u)
2797        assert_equal(cp, -z)
2798
2799    def test_broadcasting(self):
2800        # Ticket #2624 (Trac #2032)
2801        u = np.tile([1, 2], (11, 1))
2802        v = np.tile([3, 4], (11, 1))
2803        z = -2
2804        assert_equal(np.cross(u, v), z)
2805        assert_equal(np.cross(v, u), -z)
2806        assert_equal(np.cross(u, u), 0)
2807
2808        u = np.tile([1, 2], (11, 1)).T
2809        v = np.tile([3, 4, 5], (11, 1))
2810        z = np.tile([10, -5, -2], (11, 1))
2811        assert_equal(np.cross(u, v, axisa=0), z)
2812        assert_equal(np.cross(v, u.T), -z)
2813        assert_equal(np.cross(v, v), 0)
2814
2815        u = np.tile([1, 2, 3], (11, 1)).T
2816        v = np.tile([3, 4], (11, 1)).T
2817        z = np.tile([-12, 9, -2], (11, 1))
2818        assert_equal(np.cross(u, v, axisa=0, axisb=0), z)
2819        assert_equal(np.cross(v.T, u.T), -z)
2820        assert_equal(np.cross(u.T, u.T), 0)
2821
2822        u = np.tile([1, 2, 3], (5, 1))
2823        v = np.tile([4, 5, 6], (5, 1)).T
2824        z = np.tile([-3, 6, -3], (5, 1))
2825        assert_equal(np.cross(u, v, axisb=0), z)
2826        assert_equal(np.cross(v.T, u), -z)
2827        assert_equal(np.cross(u, u), 0)
2828
2829    def test_broadcasting_shapes(self):
2830        u = np.ones((2, 1, 3))
2831        v = np.ones((5, 3))
2832        assert_equal(np.cross(u, v).shape, (2, 5, 3))
2833        u = np.ones((10, 3, 5))
2834        v = np.ones((2, 5))
2835        assert_equal(np.cross(u, v, axisa=1, axisb=0).shape, (10, 5, 3))
2836        assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=2)
2837        assert_raises(np.AxisError, np.cross, u, v, axisa=3, axisb=0)
2838        u = np.ones((10, 3, 5, 7))
2839        v = np.ones((5, 7, 2))
2840        assert_equal(np.cross(u, v, axisa=1, axisc=2).shape, (10, 5, 3, 7))
2841        assert_raises(np.AxisError, np.cross, u, v, axisa=-5, axisb=2)
2842        assert_raises(np.AxisError, np.cross, u, v, axisa=1, axisb=-4)
2843        # gh-5885
2844        u = np.ones((3, 4, 2))
2845        for axisc in range(-2, 2):
2846            assert_equal(np.cross(u, u, axisc=axisc).shape, (3, 4))
2847
2848    @skipif(numpy.__version__ < "1.24", reason="fix landed in NumPy 1.24")
2849    def test_uint8_int32_mixed_dtypes(self):
2850        # regression test for gh-19138
2851        u = np.array([[195, 8, 9]], np.uint8)
2852        v = np.array([250, 166, 68], np.int32)
2853        z = np.array([[950, 11010, -30370]], dtype=np.int32)
2854        assert_equal(np.cross(v, u), z)
2855        assert_equal(np.cross(u, v), -z)
2856
2857
2858class TestOuterMisc(TestCase):
2859    def test_outer_out_param(self):
2860        arr1 = np.ones((5,))
2861        arr2 = np.ones((2,))
2862        arr3 = np.linspace(-2, 2, 5)
2863        out1 = np.empty(shape=(5, 5))
2864        out2 = np.empty(shape=(2, 5))
2865        res1 = np.outer(arr1, arr3, out1)
2866        assert_equal(res1, out1)
2867        assert_equal(np.outer(arr2, arr3, out2), out2)
2868
2869
2870@instantiate_parametrized_tests
2871class TestIndices(TestCase):
2872    def test_simple(self):
2873        [x, y] = np.indices((4, 3))
2874        assert_array_equal(x, np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]))
2875        assert_array_equal(y, np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]))
2876
2877    def test_single_input(self):
2878        [x] = np.indices((4,))
2879        assert_array_equal(x, np.array([0, 1, 2, 3]))
2880
2881        [x] = np.indices((4,), sparse=True)
2882        assert_array_equal(x, np.array([0, 1, 2, 3]))
2883
2884    def test_scalar_input(self):
2885        assert_array_equal([], np.indices(()))
2886        assert_array_equal([], np.indices((), sparse=True))
2887        assert_array_equal([[]], np.indices((0,)))
2888        assert_array_equal([[]], np.indices((0,), sparse=True))
2889
2890    def test_sparse(self):
2891        [x, y] = np.indices((4, 3), sparse=True)
2892        assert_array_equal(x, np.array([[0], [1], [2], [3]]))
2893        assert_array_equal(y, np.array([[0, 1, 2]]))
2894
2895    @parametrize("dtype", [np.int32, np.int64, np.float32, np.float64])
2896    @parametrize("dims", [(), (0,), (4, 3)])
2897    def test_return_type(self, dtype, dims):
2898        inds = np.indices(dims, dtype=dtype)
2899        assert_(inds.dtype == dtype)
2900
2901        for arr in np.indices(dims, dtype=dtype, sparse=True):
2902            assert_(arr.dtype == dtype)
2903
2904
2905@xpassIfTorchDynamo  # (reason="TODO")
2906class TestRequire(TestCase):
2907    flag_names = [
2908        "C",
2909        "C_CONTIGUOUS",
2910        "CONTIGUOUS",
2911        "F",
2912        "F_CONTIGUOUS",
2913        "FORTRAN",
2914        "A",
2915        "ALIGNED",
2916        "W",
2917        "WRITEABLE",
2918        "O",
2919        "OWNDATA",
2920    ]
2921
2922    def generate_all_false(self, dtype):
2923        arr = np.zeros((2, 2), [("junk", "i1"), ("a", dtype)])
2924        arr.setflags(write=False)
2925        a = arr["a"]
2926        assert_(not a.flags["C"])
2927        assert_(not a.flags["F"])
2928        assert_(not a.flags["O"])
2929        assert_(not a.flags["W"])
2930        assert_(not a.flags["A"])
2931        return a
2932
2933    def set_and_check_flag(self, flag, dtype, arr):
2934        if dtype is None:
2935            dtype = arr.dtype
2936        b = np.require(arr, dtype, [flag])
2937        assert_(b.flags[flag])
2938        assert_(b.dtype == dtype)
2939
2940        # a further call to np.require ought to return the same array
2941        # unless OWNDATA is specified.
2942        c = np.require(b, None, [flag])
2943        if flag[0] != "O":
2944            assert_(c is b)
2945        else:
2946            assert_(c.flags[flag])
2947
2948    def test_require_each(self):
2949        id = ["f8", "i4"]
2950        fd = [None, "f8", "c16"]
2951        for idtype, fdtype, flag in itertools.product(id, fd, self.flag_names):
2952            a = self.generate_all_false(idtype)
2953            self.set_and_check_flag(flag, fdtype, a)
2954
2955    def test_unknown_requirement(self):
2956        a = self.generate_all_false("f8")
2957        assert_raises(KeyError, np.require, a, None, "Q")
2958
2959    def test_non_array_input(self):
2960        a = np.require([1, 2, 3, 4], "i4", ["C", "A", "O"])
2961        assert_(a.flags["O"])
2962        assert_(a.flags["C"])
2963        assert_(a.flags["A"])
2964        assert_(a.dtype == "i4")
2965        assert_equal(a, [1, 2, 3, 4])
2966
2967    def test_C_and_F_simul(self):
2968        a = self.generate_all_false("f8")
2969        assert_raises(ValueError, np.require, a, None, ["C", "F"])
2970
2971
2972@xpassIfTorchDynamo  # (reason="TODO")
2973class TestBroadcast(TestCase):
2974    def test_broadcast_in_args(self):
2975        # gh-5881
2976        arrs = [
2977            np.empty((6, 7)),
2978            np.empty((5, 6, 1)),
2979            np.empty((7,)),
2980            np.empty((5, 1, 7)),
2981        ]
2982        mits = [
2983            np.broadcast(*arrs),
2984            np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])),
2985            np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])),
2986            np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])),
2987            np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1]),
2988        ]
2989        for mit in mits:
2990            assert_equal(mit.shape, (5, 6, 7))
2991            assert_equal(mit.ndim, 3)
2992            assert_equal(mit.nd, 3)
2993            assert_equal(mit.numiter, 4)
2994            for a, ia in zip(arrs, mit.iters):
2995                assert_(a is ia.base)
2996
2997    def test_broadcast_single_arg(self):
2998        # gh-6899
2999        arrs = [np.empty((5, 6, 7))]
3000        mit = np.broadcast(*arrs)
3001        assert_equal(mit.shape, (5, 6, 7))
3002        assert_equal(mit.ndim, 3)
3003        assert_equal(mit.nd, 3)
3004        assert_equal(mit.numiter, 1)
3005        assert_(arrs[0] is mit.iters[0].base)
3006
3007    def test_number_of_arguments(self):
3008        arr = np.empty((5,))
3009        for j in range(35):
3010            arrs = [arr] * j
3011            if j > 32:
3012                assert_raises(ValueError, np.broadcast, *arrs)
3013            else:
3014                mit = np.broadcast(*arrs)
3015                assert_equal(mit.numiter, j)
3016
3017    def test_broadcast_error_kwargs(self):
3018        # gh-13455
3019        arrs = [np.empty((5, 6, 7))]
3020        mit = np.broadcast(*arrs)
3021        mit2 = np.broadcast(*arrs, **{})  # noqa: PIE804
3022        assert_equal(mit.shape, mit2.shape)
3023        assert_equal(mit.ndim, mit2.ndim)
3024        assert_equal(mit.nd, mit2.nd)
3025        assert_equal(mit.numiter, mit2.numiter)
3026        assert_(mit.iters[0].base is mit2.iters[0].base)
3027
3028        assert_raises(ValueError, np.broadcast, 1, **{"x": 1})  # noqa: PIE804
3029
3030    @skip(reason="error messages do not match.")
3031    def test_shape_mismatch_error_message(self):
3032        with assert_raises(
3033            ValueError,
3034            match=r"arg 0 with shape \(1, 3\) and " r"arg 2 with shape \(2,\)",
3035        ):
3036            np.broadcast([[1, 2, 3]], [[4], [5]], [6, 7])
3037
3038
3039class TestTensordot(TestCase):
3040    def test_zero_dimension(self):
3041        # Test resolution to issue #5663
3042        a = np.zeros((3, 0))
3043        b = np.zeros((0, 4))
3044        td = np.tensordot(a, b, (1, 0))
3045        assert_array_equal(td, np.dot(a, b))
3046
3047    def test_zero_dimension_einsum(self):
3048        # Test resolution to issue #5663
3049        a = np.zeros((3, 0))
3050        b = np.zeros((0, 4))
3051        td = np.tensordot(a, b, (1, 0))
3052        assert_array_equal(td, np.einsum("ij,jk", a, b))
3053
3054    def test_zero_dimensional(self):
3055        # gh-12130
3056        arr_0d = np.array(1)
3057        ret = np.tensordot(
3058            arr_0d, arr_0d, ([], [])
3059        )  # contracting no axes is well defined
3060        assert_array_equal(ret, arr_0d)
3061
3062
3063if __name__ == "__main__":
3064    run_tests()
3065