• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020-2021 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""unit tests for numpy array operations"""
16
17import pytest
18import numpy as onp
19import mindspore.numpy as mnp
20from mindspore import context
21
22from .utils import rand_int, rand_bool, match_array, match_res, match_meta, \
23    match_all_arrays, run_multi_test, to_tensor
24
25context.set_context(mode=context.PYNATIVE_MODE)
26
27class Cases():
28    def __init__(self):
29        self.all_shapes = [
30            1, 2, (1,), (2,), (1, 2, 3), [1], [2], [1, 2, 3]
31        ]
32        self.onp_dtypes = [onp.int32, 'int32', int,
33                           onp.float32, 'float32', float,
34                           onp.uint32, 'uint32',
35                           onp.bool_, 'bool', bool]
36
37        self.mnp_dtypes = [mnp.int32, 'int32', int,
38                           mnp.float32, 'float32', float,
39                           mnp.uint32, 'uint32',
40                           mnp.bool_, 'bool', bool]
41
42        self.array_sets = [1, 1.1, True, [1, 0, True], [1, 1.0, 2], (1,),
43                           [(1, 2, 3), (4, 5, 6)], onp.random.random(  # pylint: disable=no-member
44                               (100, 100)).astype(onp.float32).tolist(),
45                           onp.random.random((100, 100)).astype(onp.bool).tolist()]
46
47        self.arrs = [
48            rand_int(2),
49            rand_int(2, 3),
50            rand_int(2, 3, 4),
51            rand_int(2, 3, 4, 5),
52        ]
53
54        # scalars expanded across the 0th dimension
55        self.scalars = [
56            rand_int(),
57            rand_int(1),
58            rand_int(1, 1),
59            rand_int(1, 1, 1),
60        ]
61
62        # arrays of the same size expanded across the 0th dimension
63        self.expanded_arrs = [
64            rand_int(2, 3),
65            rand_int(1, 2, 3),
66            rand_int(1, 1, 2, 3),
67            rand_int(1, 1, 1, 2, 3),
68        ]
69
70        # arrays with dimensions of size 1
71        self.nested_arrs = [
72            rand_int(1),
73            rand_int(1, 2),
74            rand_int(3, 1, 8),
75            rand_int(1, 3, 9, 1),
76        ]
77
78        # arrays which can be broadcast
79        self.broadcastables = [
80            rand_int(5),
81            rand_int(6, 1),
82            rand_int(7, 1, 5),
83            rand_int(8, 1, 6, 1)
84        ]
85
86        # boolean arrays which can be broadcast
87        self.bool_broadcastables = [
88            rand_bool(),
89            rand_bool(1),
90            rand_bool(5),
91            rand_bool(6, 1),
92            rand_bool(7, 1, 5),
93            rand_bool(8, 1, 6, 1),
94        ]
95
96        self.mnp_prototypes = [
97            mnp.ones((2, 3, 4)),
98            mnp.ones((1, 3, 1, 2, 5)),
99            mnp.ones((2, 7, 1)),
100            [mnp.ones(3), (1, 2, 3), mnp.ones(3), [4, 5, 6]],
101            ([(1, 2), mnp.ones(2)], (mnp.ones(2), [3, 4])),
102        ]
103
104        self.onp_prototypes = [
105            onp.ones((2, 3, 4)),
106            onp.ones((1, 3, 1, 2, 5)),
107            onp.ones((2, 7, 1)),
108            [onp.ones(3), (1, 2, 3), onp.ones(3), [4, 5, 6]],
109            ([(1, 2), onp.ones(2)], (onp.ones(2), [3, 4])),
110        ]
111
112
113@pytest.mark.level1
114@pytest.mark.platform_arm_ascend_training
115@pytest.mark.platform_x86_ascend_training
116@pytest.mark.platform_x86_gpu_training
117@pytest.mark.platform_x86_cpu
118@pytest.mark.env_onecard
119def test_asarray():
120    test_case = Cases()
121    for array in test_case.array_sets:
122        # Check for dtype matching
123        actual = onp.asarray(array)
124        expected = mnp.asarray(array).asnumpy()
125        # Since we set float32/int32 as the default dtype in mindspore, we need
126        # to make a conversion between numpy.asarray and mindspore.numpy.asarray
127        if actual.dtype is onp.dtype('float64'):
128            assert expected.dtype == onp.dtype('float32')
129        elif actual.dtype is onp.dtype('int64'):
130            assert expected.dtype == onp.dtype('int32')
131        else:
132            assert actual.dtype == expected.dtype
133        match_array(actual, expected, error=7)
134
135        for i in range(len(test_case.onp_dtypes)):
136            actual = onp.asarray(array, test_case.onp_dtypes[i])
137            expected = mnp.asarray(array, test_case.mnp_dtypes[i]).asnumpy()
138            match_array(actual, expected, error=7)
139
140    # Additional tests for nested tensor mixture
141    mnp_input = [(mnp.ones(3,), mnp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
142    onp_input = [(onp.ones(3,), onp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
143
144    actual = onp.asarray(onp_input)
145    expected = mnp.asarray(mnp_input).asnumpy()
146    match_array(actual, expected, error=7)
147
148
149@pytest.mark.level1
150@pytest.mark.platform_arm_ascend_training
151@pytest.mark.platform_x86_ascend_training
152@pytest.mark.platform_x86_gpu_training
153@pytest.mark.platform_x86_cpu
154@pytest.mark.env_onecard
155def test_array():
156    # array's function is very similar to asarray, so we mainly test the
157    # `copy` argument.
158    test_case = Cases()
159    for array in test_case.array_sets:
160        arr1 = mnp.asarray(array)
161        arr2 = mnp.array(arr1, copy=False)
162        arr3 = mnp.array(arr1)
163        arr4 = mnp.asarray(array, dtype='int32')
164        arr5 = mnp.asarray(arr4, dtype=mnp.int32)
165        assert arr1 is arr2
166        assert arr1 is not arr3
167        assert arr4 is arr5
168
169    # Additional tests for nested tensor/numpy_array mixture
170    mnp_input = [(mnp.ones(3,), mnp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
171    onp_input = [(onp.ones(3,), onp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
172
173    actual = onp.array(onp_input)
174    expected = mnp.array(mnp_input).asnumpy()
175    match_array(actual, expected, error=7)
176
177
178@pytest.mark.level1
179@pytest.mark.platform_arm_ascend_training
180@pytest.mark.platform_x86_ascend_training
181@pytest.mark.platform_x86_gpu_training
182@pytest.mark.platform_x86_cpu
183@pytest.mark.env_onecard
184def test_asfarray():
185    test_case = Cases()
186    for array in test_case.array_sets:
187        # Check for dtype matching
188        actual = onp.asfarray(array)
189        expected = mnp.asfarray(array).asnumpy()
190        # Since we set float32/int32 as the default dtype in mindspore, we need
191        # to make a conversion between numpy.asarray and mindspore.numpy.asarray
192        if actual.dtype is onp.dtype('float64'):
193            assert expected.dtype == onp.dtype('float32')
194        else:
195            assert actual.dtype == expected.dtype
196        match_array(actual, expected, error=7)
197
198        for i in range(len(test_case.onp_dtypes)):
199            actual = onp.asfarray(array, test_case.onp_dtypes[i])
200            expected = mnp.asfarray(array, test_case.mnp_dtypes[i]).asnumpy()
201            match_array(actual, expected, error=7)
202
203    # Additional tests for nested tensor/numpy_array mixture
204    mnp_input = [(mnp.ones(3,), mnp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
205    onp_input = [(onp.ones(3,), onp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
206
207    actual = onp.asfarray(onp_input)
208    expected = mnp.asfarray(mnp_input).asnumpy()
209    match_array(actual, expected, error=7)
210
211
212@pytest.mark.level1
213@pytest.mark.platform_arm_ascend_training
214@pytest.mark.platform_x86_ascend_training
215@pytest.mark.platform_x86_gpu_training
216@pytest.mark.platform_x86_cpu
217@pytest.mark.env_onecard
218def test_zeros():
219    test_case = Cases()
220    for shape in test_case.all_shapes:
221        for i in range(len(test_case.onp_dtypes)):
222            actual = onp.zeros(shape, test_case.onp_dtypes[i])
223            expected = mnp.zeros(shape, test_case.mnp_dtypes[i]).asnumpy()
224            match_array(actual, expected)
225        actual = onp.zeros(shape)
226        expected = mnp.zeros(shape).asnumpy()
227        match_array(actual, expected)
228
229
230@pytest.mark.level1
231@pytest.mark.platform_arm_ascend_training
232@pytest.mark.platform_x86_ascend_training
233@pytest.mark.platform_x86_gpu_training
234@pytest.mark.platform_x86_cpu
235@pytest.mark.env_onecard
236def test_ones():
237    test_case = Cases()
238    for shape in test_case.all_shapes:
239        for i in range(len(test_case.onp_dtypes)):
240            actual = onp.ones(shape, test_case.onp_dtypes[i])
241            expected = mnp.ones(shape, test_case.mnp_dtypes[i]).asnumpy()
242            match_array(actual, expected)
243        actual = onp.ones(shape)
244        expected = mnp.ones(shape).asnumpy()
245        match_array(actual, expected)
246
247
248@pytest.mark.level1
249@pytest.mark.platform_arm_ascend_training
250@pytest.mark.platform_x86_ascend_training
251@pytest.mark.platform_x86_gpu_training
252@pytest.mark.platform_x86_cpu
253@pytest.mark.env_onecard
254def test_full():
255    actual = onp.full((2, 2), [1, 2])
256    expected = mnp.full((2, 2), [1, 2]).asnumpy()
257    match_array(actual, expected)
258
259    actual = onp.full((2, 3), True)
260    expected = mnp.full((2, 3), True).asnumpy()
261    match_array(actual, expected)
262
263    actual = onp.full((3, 4, 5), 7.5)
264    expected = mnp.full((3, 4, 5), 7.5).asnumpy()
265    match_array(actual, expected)
266
267
268@pytest.mark.level1
269@pytest.mark.platform_arm_ascend_training
270@pytest.mark.platform_x86_ascend_training
271@pytest.mark.platform_x86_gpu_training
272@pytest.mark.platform_x86_cpu
273@pytest.mark.env_onecard
274def test_eye():
275    test_case = Cases()
276    for i in range(len(test_case.onp_dtypes)):
277        for m in range(1, 5):
278            actual = onp.eye(m, dtype=test_case.onp_dtypes[i])
279            expected = mnp.eye(m, dtype=test_case.mnp_dtypes[i]).asnumpy()
280            match_array(actual, expected)
281            for n in range(1, 5):
282                for k in range(0, 5):
283                    actual = onp.eye(m, n, k, dtype=test_case.onp_dtypes[i])
284                    expected = mnp.eye(
285                        m, n, k, dtype=test_case.mnp_dtypes[i]).asnumpy()
286                    match_array(actual, expected)
287
288
289@pytest.mark.level1
290@pytest.mark.platform_arm_ascend_training
291@pytest.mark.platform_x86_ascend_training
292@pytest.mark.platform_x86_gpu_training
293@pytest.mark.platform_x86_cpu
294@pytest.mark.env_onecard
295def test_identity():
296    test_case = Cases()
297    for i in range(len(test_case.onp_dtypes)):
298        for m in range(1, 5):
299            actual = onp.identity(m, dtype=test_case.onp_dtypes[i])
300            expected = mnp.identity(m, dtype=test_case.mnp_dtypes[i]).asnumpy()
301            match_array(actual, expected)
302
303
304@pytest.mark.level1
305@pytest.mark.platform_arm_ascend_training
306@pytest.mark.platform_x86_ascend_training
307@pytest.mark.platform_x86_gpu_training
308@pytest.mark.platform_x86_cpu
309@pytest.mark.env_onecard
310def test_arange():
311    actual = onp.arange(10)
312    expected = mnp.arange(10).asnumpy()
313    match_array(actual, expected)
314
315    actual = onp.arange(0, 10)
316    expected = mnp.arange(0, 10).asnumpy()
317    match_array(actual, expected)
318
319    actual = onp.arange(10, step=0.1)
320    expected = mnp.arange(10, step=0.1).asnumpy()
321    match_array(actual, expected, error=6)
322
323    actual = onp.arange(0.1, 9.9)
324    expected = mnp.arange(0.1, 9.9).asnumpy()
325    match_array(actual, expected, error=6)
326
327
328@pytest.mark.level0
329@pytest.mark.platform_arm_ascend_training
330@pytest.mark.platform_x86_ascend_training
331@pytest.mark.platform_x86_gpu_training
332@pytest.mark.platform_x86_cpu
333@pytest.mark.env_onecard
334def test_linspace():
335    actual = onp.linspace(2.0, 3.0, dtype=onp.float32)
336    expected = mnp.linspace(2.0, 3.0).asnumpy()
337    match_array(actual, expected, error=6)
338
339    actual = onp.linspace(2.0, 3.0, num=5, dtype=onp.float32)
340    expected = mnp.linspace(2.0, 3.0, num=5).asnumpy()
341    match_array(actual, expected, error=6)
342
343    actual = onp.linspace(
344        2.0, 3.0, num=5, endpoint=False, dtype=onp.float32)
345    expected = mnp.linspace(2.0, 3.0, num=5, endpoint=False).asnumpy()
346    match_array(actual, expected, error=6)
347
348    actual = onp.linspace(2.0, 3.0, num=5, retstep=True, dtype=onp.float32)
349    expected = mnp.linspace(2.0, 3.0, num=5, retstep=True)
350    match_array(actual[0], expected[0].asnumpy())
351    assert actual[1] == expected[1].asnumpy()
352
353    actual = onp.linspace(2.0, [3, 4, 5], num=5,
354                          endpoint=False, dtype=onp.float32)
355    expected = mnp.linspace(
356        2.0, [3, 4, 5], num=5, endpoint=False).asnumpy()
357    match_array(actual, expected, error=6)
358
359    actual = onp.linspace(2.0, [[3, 4, 5]], num=5, endpoint=False, axis=2)
360    expected = mnp.linspace(2.0, [[3, 4, 5]], num=5, endpoint=False, axis=2).asnumpy()
361    match_array(actual, expected, error=6)
362
363    start = onp.random.random([2, 1, 4]).astype("float32")
364    stop = onp.random.random([1, 5, 1]).astype("float32")
365    actual = onp.linspace(start, stop, num=20, retstep=True,
366                          endpoint=False, dtype=onp.float32)
367    expected = mnp.linspace(to_tensor(start), to_tensor(stop), num=20,
368                            retstep=True, endpoint=False)
369    match_array(actual[0], expected[0].asnumpy(), error=6)
370    match_array(actual[1], expected[1].asnumpy(), error=6)
371
372    actual = onp.linspace(start, stop, num=20, retstep=True,
373                          endpoint=False, dtype=onp.int16)
374    expected = mnp.linspace(to_tensor(start), to_tensor(stop), num=20,
375                            retstep=True, endpoint=False, dtype=mnp.int16)
376    match_array(actual[0], expected[0].asnumpy(), error=6)
377    match_array(actual[1], expected[1].asnumpy(), error=6)
378
379    for axis in range(2):
380        actual = onp.linspace(start, stop, num=20, retstep=False,
381                              endpoint=False, dtype=onp.float32, axis=axis)
382        expected = mnp.linspace(to_tensor(start), to_tensor(stop), num=20,
383                                retstep=False, endpoint=False, dtype=mnp.float32, axis=axis)
384        match_array(actual, expected.asnumpy(), error=6)
385
386
387@pytest.mark.level1
388@pytest.mark.platform_arm_ascend_training
389@pytest.mark.platform_x86_ascend_training
390@pytest.mark.platform_x86_gpu_training
391@pytest.mark.platform_x86_cpu
392@pytest.mark.env_onecard
393def test_logspace():
394    actual = onp.logspace(2.0, 3.0, dtype=onp.float32)
395    expected = mnp.logspace(2.0, 3.0).asnumpy()
396    match_array(actual, expected, error=3)
397
398    actual = onp.logspace(2.0, 3.0, num=5, dtype=onp.float32)
399    expected = mnp.logspace(2.0, 3.0, num=5).asnumpy()
400    match_array(actual, expected, error=3)
401
402    actual = onp.logspace(
403        2.0, 3.0, num=5, endpoint=False, dtype=onp.float32)
404    expected = mnp.logspace(2.0, 3.0, num=5, endpoint=False).asnumpy()
405    match_array(actual, expected, error=3)
406
407    actual = onp.logspace(2.0, [3, 4, 5], num=5, base=2,
408                          endpoint=False, dtype=onp.float32)
409    expected = mnp.logspace(
410        2.0, [3, 4, 5], num=5, base=2, endpoint=False).asnumpy()
411    match_array(actual, expected, error=3)
412
413
414@pytest.mark.level1
415@pytest.mark.platform_arm_ascend_training
416@pytest.mark.platform_x86_ascend_training
417@pytest.mark.platform_x86_gpu_training
418@pytest.mark.platform_x86_cpu
419@pytest.mark.env_onecard
420def test_empty():
421    test_case = Cases()
422    for shape in test_case.all_shapes:
423        for mnp_dtype, onp_dtype in zip(test_case.mnp_dtypes,
424                                        test_case.onp_dtypes):
425            actual = mnp.empty(shape, mnp_dtype).asnumpy()
426            expected = onp.empty(shape, onp_dtype)
427            match_meta(actual, expected)
428
429
430@pytest.mark.level1
431@pytest.mark.platform_arm_ascend_training
432@pytest.mark.platform_x86_ascend_training
433@pytest.mark.platform_x86_gpu_training
434@pytest.mark.platform_x86_cpu
435@pytest.mark.env_onecard
436def test_empty_like():
437    test_case = Cases()
438    for mnp_proto, onp_proto in zip(test_case.mnp_prototypes, test_case.onp_prototypes):
439        actual = mnp.empty_like(mnp_proto).asnumpy()
440        expected = onp.empty_like(onp_proto)
441        assert actual.shape == expected.shape
442
443        for mnp_dtype, onp_dtype in zip(test_case.mnp_dtypes,
444                                        test_case.onp_dtypes):
445            actual = mnp.empty_like(mnp_proto, dtype=mnp_dtype).asnumpy()
446            expected = onp.empty_like(onp_proto, dtype=onp_dtype)
447            match_meta(actual, expected)
448
449
450def run_x_like(mnp_fn, onp_fn):
451    test_case = Cases()
452    for mnp_proto, onp_proto in zip(test_case.mnp_prototypes, test_case.onp_prototypes):
453        actual = mnp_fn(mnp_proto).asnumpy()
454        expected = onp_fn(onp_proto)
455        match_array(actual, expected)
456
457        for shape in test_case.all_shapes:
458            actual = mnp_fn(mnp_proto, shape=shape).asnumpy()
459            expected = onp_fn(onp_proto, shape=shape)
460            match_array(actual, expected)
461            for mnp_dtype, onp_dtype in zip(test_case.mnp_dtypes,
462                                            test_case.onp_dtypes):
463                actual = mnp_fn(mnp_proto, dtype=mnp_dtype).asnumpy()
464                expected = onp_fn(onp_proto, dtype=onp_dtype)
465                match_array(actual, expected)
466
467                actual = mnp_fn(mnp_proto, dtype=mnp_dtype,
468                                shape=shape).asnumpy()
469                expected = onp_fn(onp_proto, dtype=onp_dtype, shape=shape)
470                match_array(actual, expected)
471
472
473@pytest.mark.level1
474@pytest.mark.platform_arm_ascend_training
475@pytest.mark.platform_x86_ascend_training
476@pytest.mark.platform_x86_gpu_training
477@pytest.mark.platform_x86_cpu
478@pytest.mark.env_onecard
479def test_ones_like():
480    run_x_like(mnp.ones_like, onp.ones_like)
481
482
483@pytest.mark.level1
484@pytest.mark.platform_arm_ascend_training
485@pytest.mark.platform_x86_ascend_training
486@pytest.mark.platform_x86_gpu_training
487@pytest.mark.platform_x86_cpu
488@pytest.mark.env_onecard
489def test_zeros_like():
490    run_x_like(mnp.zeros_like, onp.zeros_like)
491
492
493@pytest.mark.level1
494@pytest.mark.platform_arm_ascend_training
495@pytest.mark.platform_x86_ascend_training
496@pytest.mark.platform_x86_gpu_training
497@pytest.mark.platform_x86_cpu
498@pytest.mark.env_onecard
499def test_full_like():
500    test_case = Cases()
501    for mnp_proto, onp_proto in zip(test_case.mnp_prototypes, test_case.onp_prototypes):
502        shape = onp.zeros_like(onp_proto).shape
503        fill_value = rand_int()
504        actual = mnp.full_like(mnp_proto, to_tensor(fill_value)).asnumpy()
505        expected = onp.full_like(onp_proto, fill_value)
506        match_array(actual, expected)
507
508        for i in range(len(shape) - 1, 0, -1):
509            fill_value = rand_int(*shape[i:])
510            actual = mnp.full_like(mnp_proto, to_tensor(fill_value)).asnumpy()
511            expected = onp.full_like(onp_proto, fill_value)
512            match_array(actual, expected)
513
514            fill_value = rand_int(1, *shape[i + 1:])
515            actual = mnp.full_like(mnp_proto, to_tensor(fill_value)).asnumpy()
516            expected = onp.full_like(onp_proto, fill_value)
517            match_array(actual, expected)
518
519
520@pytest.mark.level1
521@pytest.mark.platform_arm_ascend_training
522@pytest.mark.platform_x86_ascend_training
523@pytest.mark.platform_x86_gpu_training
524@pytest.mark.platform_x86_cpu
525@pytest.mark.env_onecard
526def test_tri_triu_tril():
527    x = mnp.ones((16, 32), dtype="bool")
528    match_array(mnp.tril(x).asnumpy(), onp.tril(x.asnumpy()))
529    match_array(mnp.tril(x, -1).asnumpy(), onp.tril(x.asnumpy(), -1))
530    match_array(mnp.triu(x).asnumpy(), onp.triu(x.asnumpy()))
531    match_array(mnp.triu(x, -1).asnumpy(), onp.triu(x.asnumpy(), -1))
532
533    x = mnp.ones((64, 64), dtype="uint8")
534    match_array(mnp.tril(x).asnumpy(), onp.tril(x.asnumpy()))
535    match_array(mnp.tril(x, 25).asnumpy(), onp.tril(x.asnumpy(), 25))
536    match_array(mnp.triu(x).asnumpy(), onp.triu(x.asnumpy()))
537    match_array(mnp.triu(x, 25).asnumpy(), onp.triu(x.asnumpy(), 25))
538
539    match_array(mnp.tri(64, 64).asnumpy(), onp.tri(64, 64))
540    match_array(mnp.tri(64, 64, -10).asnumpy(), onp.tri(64, 64, -10))
541
542
543@pytest.mark.level1
544@pytest.mark.platform_x86_gpu_training
545@pytest.mark.platform_x86_cpu
546@pytest.mark.env_onecard
547def test_nancumsum():
548    x = rand_int(2, 3, 4, 5)
549    x[0][2][1][3] = onp.nan
550    x[1][0][2][4] = onp.nan
551    x[1][1][1][1] = onp.nan
552    match_res(mnp.nancumsum, onp.nancumsum, x)
553    match_res(mnp.nancumsum, onp.nancumsum, x, axis=-2)
554    match_res(mnp.nancumsum, onp.nancumsum, x, axis=0)
555    match_res(mnp.nancumsum, onp.nancumsum, x, axis=3)
556
557
558def mnp_diagonal(arr):
559    return mnp.diagonal(arr, offset=2, axis1=-1, axis2=0)
560
561
562def onp_diagonal(arr):
563    return onp.diagonal(arr, offset=2, axis1=-1, axis2=0)
564
565
566@pytest.mark.level1
567@pytest.mark.platform_arm_ascend_training
568@pytest.mark.platform_x86_ascend_training
569@pytest.mark.platform_x86_gpu_training
570@pytest.mark.platform_x86_cpu
571@pytest.mark.env_onecard
572def test_diagonal():
573
574    arr = rand_int(3, 5)
575    for i in [-1, 0, 2]:
576        match_res(mnp.diagonal, onp.diagonal, arr, offset=i, axis1=0, axis2=1)
577        match_res(mnp.diagonal, onp.diagonal, arr, offset=i, axis1=1, axis2=0)
578
579    arr = rand_int(7, 4, 9)
580    for i in [-1, 0, 2]:
581        match_res(mnp.diagonal, onp.diagonal, arr, offset=i, axis1=0, axis2=-1)
582        match_res(mnp.diagonal, onp.diagonal, arr, offset=i, axis1=-2, axis2=2)
583        match_res(mnp.diagonal, onp.diagonal, arr,
584                  offset=i, axis1=-1, axis2=-2)
585
586
587def mnp_trace(arr):
588    return mnp.trace(arr, offset=4, axis1=1, axis2=2)
589
590
591def onp_trace(arr):
592    return onp.trace(arr, offset=4, axis1=1, axis2=2)
593
594
595@pytest.mark.level0
596@pytest.mark.platform_arm_ascend_training
597@pytest.mark.platform_x86_ascend_training
598@pytest.mark.platform_x86_gpu_training
599@pytest.mark.platform_x86_cpu
600@pytest.mark.env_onecard
601def test_trace():
602
603    arr = rand_int(3, 5)
604    match_res(mnp.trace, onp.trace, arr, offset=-1, axis1=0, axis2=1)
605
606    arr = rand_int(7, 4, 9)
607    match_res(mnp.trace, onp.trace, arr, offset=0, axis1=-2, axis2=2)
608
609
610def mnp_meshgrid(*xi):
611    a = mnp.meshgrid(*xi)
612    b = mnp.meshgrid(*xi, sparse=True)
613    c = mnp.meshgrid(*xi, indexing='ij')
614    d = mnp.meshgrid(*xi, sparse=False, indexing='ij')
615    return a, b, c, d
616
617
618def onp_meshgrid(*xi):
619    a = onp.meshgrid(*xi)
620    b = onp.meshgrid(*xi, sparse=True)
621    c = onp.meshgrid(*xi, indexing='ij')
622    d = onp.meshgrid(*xi, sparse=False, indexing='ij')
623    return a, b, c, d
624
625
626@pytest.mark.level0
627@pytest.mark.platform_arm_ascend_training
628@pytest.mark.platform_x86_ascend_training
629@pytest.mark.platform_x86_gpu_training
630@pytest.mark.platform_x86_cpu
631@pytest.mark.env_onecard
632def test_meshgrid():
633    xi = (onp.full(3, 2), onp.full(1, 5), onp.full(
634        (2, 3), 9), onp.full((4, 5, 6), 7))
635    for i in range(len(xi)):
636        arrs = xi[i:]
637        mnp_arrs = map(to_tensor, arrs)
638        for mnp_res, onp_res in zip(mnp_meshgrid(*mnp_arrs), onp_meshgrid(*arrs)):
639            match_all_arrays(mnp_res, onp_res)
640
641
642@pytest.mark.level1
643@pytest.mark.platform_arm_ascend_training
644@pytest.mark.platform_x86_ascend_training
645@pytest.mark.platform_x86_gpu_training
646@pytest.mark.platform_x86_cpu
647@pytest.mark.env_onecard
648def test_diagflat():
649    arrs = [rand_int(2, 3)]
650    for arr in arrs:
651        for i in [-2, 0, 7]:
652            match_res(mnp.diagflat, onp.diagflat, arr, k=i)
653
654
655@pytest.mark.level1
656@pytest.mark.platform_arm_ascend_training
657@pytest.mark.platform_x86_ascend_training
658@pytest.mark.platform_x86_gpu_training
659@pytest.mark.platform_x86_cpu
660@pytest.mark.env_onecard
661def test_diag():
662    arrs = [rand_int(7), rand_int(5, 5), rand_int(3, 8), rand_int(9, 6)]
663    for arr in arrs:
664        for i in [-10, -5, -1, 0, 2, 5, 6, 10]:
665            match_res(mnp.diag, onp.diag, arr, k=i)
666
667
668@pytest.mark.level1
669@pytest.mark.platform_arm_ascend_training
670@pytest.mark.platform_x86_ascend_training
671@pytest.mark.platform_x86_gpu_training
672@pytest.mark.platform_x86_cpu
673@pytest.mark.env_onecard
674def test_diag_indices():
675    mnp_res = mnp.diag_indices(5, 7)
676    onp_res = onp.diag_indices(5, 7)
677    match_all_arrays(mnp_res, onp_res)
678
679
680def mnp_ix_(*args):
681    return mnp.ix_(*args)
682
683
684def onp_ix_(*args):
685    return onp.ix_(*args)
686
687
688@pytest.mark.level1
689@pytest.mark.platform_arm_ascend_training
690@pytest.mark.platform_x86_ascend_training
691@pytest.mark.platform_x86_gpu_training
692@pytest.mark.platform_x86_cpu
693@pytest.mark.env_onecard
694def test_ix_():
695    arrs = [rand_int(i + 1) for i in range(10)]
696    for i in range(10):
697        test_arrs = arrs[:i + 1]
698        match_res(mnp_ix_, onp_ix_, *test_arrs)
699
700
701def mnp_indices():
702    a = mnp.indices((2, 3))
703    b = mnp.indices((2, 3, 4), sparse=True)
704    return a, b
705
706
707def onp_indices():
708    a = onp.indices((2, 3))
709    b = onp.indices((2, 3, 4), sparse=True)
710    return a, b
711
712
713def test_indices():
714    run_multi_test(mnp_indices, onp_indices, ())
715
716
717@pytest.mark.level1
718@pytest.mark.platform_arm_ascend_training
719@pytest.mark.platform_x86_ascend_training
720@pytest.mark.platform_x86_gpu_training
721@pytest.mark.platform_x86_cpu
722@pytest.mark.env_onecard
723def test_geomspace():
724    start = onp.arange(1, 7).reshape(2, 3)
725    end = [1000, 2000, 3000]
726    match_array(mnp.geomspace(1, 256, num=9).asnumpy(),
727                onp.geomspace(1, 256, num=9), error=1)
728    match_array(mnp.geomspace(1, 256, num=8, endpoint=False).asnumpy(),
729                onp.geomspace(1, 256, num=8, endpoint=False), error=1)
730    match_array(mnp.geomspace(to_tensor(start), end, num=4).asnumpy(),
731                onp.geomspace(start, end, num=4), error=1)
732    match_array(mnp.geomspace(to_tensor(start), end, num=4, endpoint=False).asnumpy(),
733                onp.geomspace(start, end, num=4, endpoint=False), error=1)
734    match_array(mnp.geomspace(to_tensor(start), end, num=4, axis=-1).asnumpy(),
735                onp.geomspace(start, end, num=4, axis=-1), error=1)
736    match_array(mnp.geomspace(to_tensor(start), end, num=4, endpoint=False, axis=-1).asnumpy(),
737                onp.geomspace(start, end, num=4, endpoint=False, axis=-1), error=1)
738
739    start = onp.arange(1, 1 + 2*3*4*5).reshape(2, 3, 4, 5)
740    end = [1000, 2000, 3000, 4000, 5000]
741    for i in range(-5, 5):
742        match_array(mnp.geomspace(to_tensor(start), end, num=4, axis=i).asnumpy(),
743                    onp.geomspace(start, end, num=4, axis=i), error=1)
744
745
746@pytest.mark.level1
747@pytest.mark.platform_arm_ascend_training
748@pytest.mark.platform_x86_ascend_training
749@pytest.mark.platform_x86_gpu_training
750@pytest.mark.platform_x86_cpu
751@pytest.mark.env_onecard
752def test_vander():
753    arrs = [rand_int(i + 3) for i in range(3)]
754    for i in range(3):
755        mnp_vander = mnp.vander(to_tensor(arrs[i]))
756        onp_vander = onp.vander(arrs[i])
757        match_all_arrays(mnp_vander, onp_vander, error=1e-4)
758        mnp_vander = mnp.vander(to_tensor(arrs[i]), N=2, increasing=True)
759        onp_vander = onp.vander(arrs[i], N=2, increasing=True)
760        match_all_arrays(mnp_vander, onp_vander, error=1e-4)
761
762
763@pytest.mark.level0
764@pytest.mark.platform_arm_ascend_training
765@pytest.mark.platform_x86_ascend_training
766@pytest.mark.platform_x86_gpu_training
767@pytest.mark.platform_x86_cpu
768@pytest.mark.env_onecard
769def test_tensor_fill():
770    x = rand_int(2, 1, 4).astype(onp.float32)
771    mnp_x = to_tensor(x)
772    x.fill(6)
773    match_all_arrays(mnp_x.fill(6), x)
774    x.fill(None)
775    match_all_arrays(mnp_x.fill(None), x)
776
777
778@pytest.mark.level1
779@pytest.mark.platform_arm_ascend_training
780@pytest.mark.platform_x86_ascend_training
781@pytest.mark.platform_x86_gpu_training
782@pytest.mark.platform_x86_cpu
783@pytest.mark.env_onecard
784def test_bartlett():
785    for i in [-3, -1, 0, 1, 5, 6, 10, 15]:
786        match_all_arrays(mnp.bartlett(i), onp.bartlett(i), error=3)
787
788
789@pytest.mark.level1
790@pytest.mark.platform_arm_ascend_training
791@pytest.mark.platform_x86_ascend_training
792@pytest.mark.platform_x86_gpu_training
793@pytest.mark.platform_x86_cpu
794@pytest.mark.env_onecard
795def test_blackman():
796    for i in [-3, -1, 0, 1, 5, 6, 10, 15]:
797        match_all_arrays(mnp.blackman(i), onp.blackman(i), error=3)
798
799
800@pytest.mark.level1
801@pytest.mark.platform_arm_ascend_training
802@pytest.mark.platform_x86_ascend_training
803@pytest.mark.platform_x86_gpu_training
804@pytest.mark.platform_x86_cpu
805@pytest.mark.env_onecard
806def test_hamming():
807    for i in [-3, -1, 0, 1, 5, 6, 10, 15]:
808        match_all_arrays(mnp.hamming(i), onp.hamming(i), error=3)
809
810
811@pytest.mark.level1
812@pytest.mark.platform_arm_ascend_training
813@pytest.mark.platform_x86_ascend_training
814@pytest.mark.platform_x86_gpu_training
815@pytest.mark.platform_x86_cpu
816@pytest.mark.env_onecard
817def test_hanning():
818    for i in [-3, -1, 0, 1, 5, 6, 10, 15]:
819        match_all_arrays(mnp.hanning(i), onp.hanning(i), error=3)
820
821
822@pytest.mark.level1
823@pytest.mark.platform_arm_ascend_training
824@pytest.mark.platform_x86_ascend_training
825@pytest.mark.platform_x86_gpu_training
826@pytest.mark.platform_x86_cpu
827@pytest.mark.env_onecard
828def test_triu_indices():
829    m = rand_int().tolist()
830    n = rand_int().tolist()
831    k = rand_int().tolist()
832    mnp_res = mnp.triu_indices(n, k, m)
833    onp_res = onp.triu_indices(n, k, m)
834    match_all_arrays(mnp_res, onp_res)
835
836
837@pytest.mark.level1
838@pytest.mark.platform_arm_ascend_training
839@pytest.mark.platform_x86_ascend_training
840@pytest.mark.platform_x86_gpu_training
841@pytest.mark.platform_x86_cpu
842@pytest.mark.env_onecard
843def test_tril_indices():
844    m = rand_int().tolist()
845    n = rand_int().tolist()
846    k = rand_int().tolist()
847    mnp_res = mnp.tril_indices(n, k, m)
848    onp_res = onp.tril_indices(n, k, m)
849    match_all_arrays(mnp_res, onp_res)
850
851
852@pytest.mark.level1
853@pytest.mark.platform_arm_ascend_training
854@pytest.mark.platform_x86_ascend_training
855@pytest.mark.platform_x86_gpu_training
856@pytest.mark.platform_x86_cpu
857@pytest.mark.env_onecard
858def test_triu_indices_from():
859    m = int(rand_int().tolist())
860    n = int(rand_int().tolist())
861    t = mnp.asarray(rand_int(m, n).tolist())
862    k = rand_int().tolist()
863    mnp_res = mnp.triu_indices_from(t, k)
864    onp_res = onp.triu_indices_from(t.asnumpy(), k)
865    match_all_arrays(mnp_res, onp_res)
866
867
868@pytest.mark.level1
869@pytest.mark.platform_arm_ascend_training
870@pytest.mark.platform_x86_ascend_training
871@pytest.mark.platform_x86_gpu_training
872@pytest.mark.platform_x86_cpu
873@pytest.mark.env_onecard
874def test_tril_indices_from():
875    m = int(rand_int().tolist())
876    n = int(rand_int().tolist())
877    t = mnp.asarray(rand_int(m, n).tolist())
878    k = rand_int().tolist()
879    mnp_res = mnp.tril_indices_from(t, k)
880    onp_res = onp.tril_indices_from(t.asnumpy(), k)
881    match_all_arrays(mnp_res, onp_res)
882
883
884@pytest.mark.level0
885@pytest.mark.platform_arm_ascend_training
886@pytest.mark.platform_x86_ascend_training
887@pytest.mark.platform_x86_gpu_training
888@pytest.mark.platform_x86_cpu
889@pytest.mark.env_onecard
890def test_histogram_bin_edges():
891    x = onp.random.randint(-10, 10, 10)
892    match_res(mnp.histogram_bin_edges, onp.histogram_bin_edges, x, onp.arange(5))
893    match_res(mnp.histogram_bin_edges, onp.histogram_bin_edges, x, bins=(1, 2, 3), range=None, error=3)
894    match_res(mnp.histogram_bin_edges, onp.histogram_bin_edges, x, bins=10, range=(2, 20), error=3)
895
896
897@pytest.mark.level1
898@pytest.mark.platform_arm_ascend_training
899@pytest.mark.platform_x86_ascend_training
900@pytest.mark.platform_x86_gpu_training
901@pytest.mark.platform_x86_cpu
902@pytest.mark.env_onecard
903def test_asarray_exception():
904    with pytest.raises(TypeError):
905        mnp.asarray({1, 2, 3})
906
907
908@pytest.mark.level1
909@pytest.mark.platform_arm_ascend_training
910@pytest.mark.platform_x86_ascend_training
911@pytest.mark.platform_x86_gpu_training
912@pytest.mark.platform_x86_cpu
913@pytest.mark.env_onecard
914def test_linspace_exception():
915    with pytest.raises(TypeError):
916        mnp.linspace(0, 1, num=2.5)
917
918
919@pytest.mark.level1
920@pytest.mark.platform_arm_ascend_training
921@pytest.mark.platform_x86_ascend_training
922@pytest.mark.platform_x86_gpu_training
923@pytest.mark.platform_x86_cpu
924@pytest.mark.env_onecard
925def test_empty_like_exception():
926    with pytest.raises(ValueError):
927        mnp.empty_like([[1, 2, 3], [4, 5]])
928
929
930@pytest.mark.level0
931@pytest.mark.platform_arm_ascend_training
932@pytest.mark.platform_x86_ascend_training
933@pytest.mark.platform_x86_gpu_training
934@pytest.mark.platform_x86_cpu
935@pytest.mark.env_onecard
936def test_pad():
937    x_np = onp.random.random([2, 3, 4]).astype("float32")
938    x_ms = mnp.asarray(x_np.tolist())
939
940    # pad constant
941    mnp_res = mnp.pad(x_ms, ((1, 1), (2, 2), (3, 4)))
942    onp_res = onp.pad(x_np, ((1, 1), (2, 2), (3, 4)))
943    match_all_arrays(mnp_res, onp_res, error=1e-5)
944    mnp_res = mnp.pad(x_ms, ((1, 1), (2, 3), (4, 5)), constant_values=((3, 4), (5, 6), (7, 8)))
945    onp_res = onp.pad(x_np, ((1, 1), (2, 3), (4, 5)), constant_values=((3, 4), (5, 6), (7, 8)))
946    match_all_arrays(mnp_res, onp_res, error=1e-5)
947
948    # pad statistic
949    mnp_res = mnp.pad(x_ms, ((1, 1), (2, 2), (3, 4)), mode="mean", stat_length=((1, 2), (2, 10), (3, 4)))
950    onp_res = onp.pad(x_np, ((1, 1), (2, 2), (3, 4)), mode="mean", stat_length=((1, 2), (2, 10), (3, 4)))
951    match_all_arrays(mnp_res, onp_res, error=1e-5)
952
953    # pad edge
954    mnp_res = mnp.pad(x_ms, ((1, 1), (2, 2), (3, 4)), mode="edge")
955    onp_res = onp.pad(x_np, ((1, 1), (2, 2), (3, 4)), mode="edge")
956    match_all_arrays(mnp_res, onp_res, error=1e-5)
957
958    # pad wrap
959    mnp_res = mnp.pad(x_ms, ((1, 1), (2, 2), (3, 4)), mode="wrap")
960    onp_res = onp.pad(x_np, ((1, 1), (2, 2), (3, 4)), mode="wrap")
961    match_all_arrays(mnp_res, onp_res, error=1e-5)
962
963    # pad linear_ramp
964    mnp_res = mnp.pad(x_ms, ((1, 3), (5, 2), (3, 0)), mode="linear_ramp", end_values=((0, 10), (9, 1), (-10, 99)))
965    onp_res = onp.pad(x_np, ((1, 3), (5, 2), (3, 0)), mode="linear_ramp", end_values=((0, 10), (9, 1), (-10, 99)))
966    match_all_arrays(mnp_res, onp_res, error=1e-5)
967
968
969def pad_with_msfunc(vector, pad_width, iaxis, kwargs):
970    pad_value = kwargs.get('padder', 10)
971    vector[:pad_width[0]] = pad_value
972    vector[-pad_width[1]:] = pad_value
973    return vector
974
975
976def pad_with_npfunc(vector, pad_width, iaxis, kwargs):
977    pad_value = kwargs.get('padder', 10)
978    vector[:pad_width[0]] = pad_value
979    vector[-pad_width[1]:] = pad_value
980
981
982@pytest.mark.level0
983@pytest.mark.platform_x86_gpu_training
984@pytest.mark.env_onecard
985def test_pad_gpu():
986    x_np = onp.random.random([2, 1, 4, 3]).astype("float32")
987    x_ms = mnp.asarray(x_np.tolist())
988
989    # pad symmetric odd
990    mnp_res = mnp.pad(x_ms, ((10, 3), (5, 2), (3, 0), (2, 6)), mode='symmetric', reflect_type='odd')
991    onp_res = onp.pad(x_np, ((10, 3), (5, 2), (3, 0), (2, 6)), mode='symmetric', reflect_type='odd')
992    match_all_arrays(mnp_res, onp_res, error=1e-5)
993
994    # pad symmetric even
995    mnp_res = mnp.pad(x_ms, ((10, 13), (5, 12), (3, 0), (2, 6)), mode='symmetric', reflect_type='even')
996    onp_res = onp.pad(x_np, ((10, 13), (5, 12), (3, 0), (2, 6)), mode='symmetric', reflect_type='even')
997    match_all_arrays(mnp_res, onp_res, error=1e-5)
998
999    # pad reflect odd
1000    mnp_res = mnp.pad(x_ms, ((10, 3), (5, 2), (3, 0), (2, 6)), mode='reflect', reflect_type='odd')
1001    onp_res = onp.pad(x_np, ((10, 3), (5, 2), (3, 0), (2, 6)), mode='reflect', reflect_type='odd')
1002    match_all_arrays(mnp_res, onp_res, error=1e-5)
1003
1004    # pad reflect even
1005    mnp_res = mnp.pad(x_ms, ((10, 13)), mode='reflect', reflect_type='even')
1006    onp_res = onp.pad(x_np, ((10, 13)), mode='reflect', reflect_type='even')
1007    match_all_arrays(mnp_res, onp_res, error=1e-5)
1008
1009    # pad func
1010    x_np = onp.random.random([2, 4]).astype("float32")
1011    x_ms = mnp.asarray(x_np.tolist())
1012    mnp_res = mnp.pad(x_ms, ((5, 5)), mode=pad_with_msfunc, padder=99)
1013    onp_res = onp.pad(x_np, ((5, 5)), mode=pad_with_npfunc, padder=99)
1014    match_all_arrays(mnp_res, onp_res, error=1e-5)
1015