Repository navigation
Expand file tree
/
Copy pathtest_ndarray.py
More file actions
771 lines (611 loc) · 22.4 KB
/
Copy pathtest_ndarray.py
File metadata and controls
771 lines (611 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
import numpy
import pytest
from numpy.testing import (
assert_allclose,
assert_array_equal,
assert_equal,
assert_raises,
assert_raises_regex,
)
import dpnp
import dpnp.tensor as dpt
from .helper import (
generate_random_numpy_array,
get_abs_array,
get_all_dtypes,
get_complex_dtypes,
get_float_dtypes,
has_support_aspect64,
)
from .third_party.cupy import testing
class TestAsType:
@pytest.mark.usefixtures("suppress_complex_warning")
@pytest.mark.parametrize("res_dtype", get_all_dtypes())
@pytest.mark.parametrize("arr_dtype", get_all_dtypes(no_none=True))
@pytest.mark.parametrize(
"arr",
[[-2, -1, 0, 1, 2], [[-2, -1], [1, 2]], []],
ids=["1d", "2d", "empty"],
)
def test_basic(self, arr, arr_dtype, res_dtype):
a = get_abs_array(arr, arr_dtype)
ia = dpnp.array(a)
expected = a.astype(res_dtype)
result = ia.astype(res_dtype)
assert_allclose(result, expected)
def test_subok_error(self):
x = dpnp.ones(4)
with pytest.raises(NotImplementedError):
x.astype("i4", subok=False)
class TestAttributes:
def setup_method(self):
self.one = dpnp.arange(10)
self.two = dpnp.arange(20).reshape(4, 5)
self.three = dpnp.arange(60).reshape(2, 5, 6)
def test_attributes(self):
assert_equal(self.one.shape, (10,))
assert_equal(self.two.shape, (4, 5))
assert_equal(self.three.shape, (2, 5, 6))
self.three.shape = (10, 3, 2)
assert_equal(self.three.shape, (10, 3, 2))
self.three.shape = (2, 5, 6)
assert_equal(self.one.strides, (self.one.itemsize,))
num = self.two.itemsize
assert_equal(self.two.strides, (5 * num, num))
num = self.three.itemsize
assert_equal(self.three.strides, (30 * num, 6 * num, num))
assert_equal(self.one.ndim, 1)
assert_equal(self.two.ndim, 2)
assert_equal(self.three.ndim, 3)
num = self.two.itemsize
assert_equal(self.two.size, 20)
assert_equal(self.two.nbytes, 20 * num)
assert_equal(self.two.itemsize, self.two.dtype.itemsize)
@testing.parameterize(*testing.product({"xp": [dpnp, numpy]}))
class TestContains:
def test_basic(self):
a = self.xp.arange(10).reshape((2, 5))
assert 4 in a
assert 20 not in a
def test_broadcast(self):
xp = self.xp
a = xp.arange(6).reshape((2, 3))
assert 4 in a
assert xp.array([0, 1, 2]) in a
assert xp.array([5, 3, 4]) not in a
def test_broadcast_error(self):
a = self.xp.arange(10).reshape((2, 5))
with pytest.raises(
ValueError,
match="operands could not be broadcast together with shapes",
):
self.xp.array([1, 2]) in a
def test_strides(self):
xp = self.xp
a = xp.arange(10).reshape((2, 5))
a = a[:, ::2]
assert 4 in a
assert 8 not in a
assert xp.full(a.shape[-1], fill_value=2) in a
assert xp.full_like(a, fill_value=7) in a
assert xp.full_like(a, fill_value=6) not in a
class TestFormat:
def test_basic(self):
a = numpy.array(3.14159)
ia = dpnp.array(a)
spec = ".3f"
assert_equal(format(ia, spec), format(a, spec))
@pytest.mark.parametrize("xp", [dpnp, numpy])
def test_1d(self, xp):
a = xp.array([3.14159])
with pytest.raises(TypeError, match="unsupported format string"):
_ = format(a, ".2f")
class TestToBytes:
@pytest.mark.parametrize("order", ["C", "F", "K", "A", None])
def test_roundtrip_binary_str(self, order):
x = generate_random_numpy_array((2, 4, 3), dtype=complex)
x[0, :, 1] = [numpy.nan, numpy.inf, -numpy.inf, numpy.nan]
a = dpnp.array(x)
s = a.tobytes(order=order)
b = dpnp.frombuffer(s, dtype=a.dtype)
assert_array_equal(b, a.asnumpy().flatten(order))
class TestToFile:
def _create_data(self):
x = generate_random_numpy_array((2, 4, 3), dtype=complex)
x[0, :, 1] = [numpy.nan, numpy.inf, -numpy.inf, numpy.nan]
return dpnp.array(x)
@pytest.fixture(params=["string", "path_obj"])
def tmp_filename(self, tmp_path, request):
# This fixture covers two cases:
# one where the filename is a string and
# another where it is a pathlib object
filename = tmp_path / "file"
if request.param == "string":
filename = str(filename)
yield filename
def test_roundtrip_file(self, tmp_filename):
a = self._create_data()
with open(tmp_filename, "wb") as f:
a.tofile(f)
# reconstruct the array back from the file
with open(tmp_filename, "rb") as f:
b = dpnp.fromfile(f, dtype=a.dtype)
assert_array_equal(b, a.asnumpy().flat)
def test_roundtrip(self, tmp_filename):
a = self._create_data()
a.tofile(tmp_filename)
b = dpnp.fromfile(tmp_filename, dtype=a.dtype)
assert_array_equal(b, a.asnumpy().flat)
def test_sep(self, tmp_filename):
a = dpnp.array([1.51, 2, 3.51, 4])
with open(tmp_filename, "w") as f:
a.tofile(f, sep=",")
# reconstruct the array
with open(tmp_filename) as f:
s = f.read()
b = dpnp.array([float(p) for p in s.split(",")], dtype=a.dtype)
assert_array_equal(a, b.asnumpy())
def test_format(self, tmp_filename):
a = dpnp.array([1.51, 2, 3.51, 4])
with open(tmp_filename, "w") as f:
a.tofile(f, sep=",", format="%.2f")
# reconstruct the array as a string
with open(tmp_filename) as f:
s = f.read()
assert_equal(s, "1.51,2.00,3.51,4.00")
class TestToList:
@pytest.mark.parametrize(
"data", [[1, 2], [[1, 2], [3, 4]]], ids=["1d", "2d"]
)
def test_basic(self, data):
a = numpy.array(data)
ia = dpnp.array(a)
assert_array_equal(ia.tolist(), a.tolist())
class TestView:
def test_none_dtype(self):
a = numpy.ones((1, 2, 4), dtype=numpy.int32)
ia = dpnp.array(a)
expected = a.view()
result = ia.view()
assert_allclose(result, expected)
expected = a.view() # numpy returns dtype(None) otherwise
result = ia.view(None)
assert_allclose(result, expected)
@pytest.mark.parametrize("dt", [bool, int, float, complex])
def test_python_types(self, dt):
a = numpy.ones((8, 4), dtype=numpy.complex64)
ia = dpnp.array(a)
result = ia.view(dt)
if not has_support_aspect64() and dt in [float, complex]:
dt = result.dtype
expected = a.view(dt)
assert_allclose(result, expected)
def test_subclass_basic(self):
class MyArray(dpnp.ndarray):
pass
x = dpnp.array([1, 2, 3])
view = x.view(type=MyArray)
assert isinstance(view, MyArray)
assert type(view) is MyArray
assert (view == x).all()
def test_dtype_type_subclass(self):
class MyArray(dpnp.ndarray):
pass
x = dpnp.array([1, 2, 3])
# All three syntaxes should work identically
view1 = x.view(type=MyArray)
view2 = x.view(MyArray)
view3 = x.view(dtype=MyArray)
assert type(view1) is MyArray
assert type(view2) is MyArray
assert type(view3) is MyArray
def test_subclass_array_finalize(self):
class ArrayWithInfo(dpnp.ndarray):
def __array_finalize__(self, obj):
self.info = getattr(obj, "info", "default")
x = dpnp.array([1, 2, 3]).view(type=ArrayWithInfo)
x.info = "metadata"
# Create a view - __array_finalize__ should be called
view = x.view()
assert hasattr(view, "info")
assert view.info == "metadata"
assert type(view) is ArrayWithInfo
def test_subclass_self_class_preservation(self):
class MyArray(dpnp.ndarray):
pass
x = dpnp.array([1, 2, 3]).view(type=MyArray)
# View without type parameter should preserve MyArray
view = x.view()
assert type(view) is MyArray
def test_subclass_with_dtype_change(self):
class MyArray(dpnp.ndarray):
pass
x = dpnp.array([1.0, 2.0], dtype=dpnp.float32)
view = x.view(dtype=dpnp.int32, type=MyArray)
assert type(view) is MyArray
assert view.dtype == dpnp.int32
@pytest.mark.parametrize("xp", [dpnp, numpy])
def test_subclass_invalid_type(self, xp):
x = xp.array([1, 2, 3])
with pytest.raises(
ValueError, match="Type must be a sub-type of ndarray type"
):
x.view(type=list)
@pytest.mark.parametrize("xp", [dpnp, numpy])
def test_subclass_double_type_specification(self, xp):
class MyArray(xp.ndarray):
pass
class OtherArray(xp.ndarray):
pass
x = xp.array([1, 2, 3])
with pytest.raises(
ValueError, match="Cannot specify output type twice"
):
x.view(dtype=MyArray, type=OtherArray)
@pytest.mark.parametrize(
"arr",
[
numpy.array([1]),
dpnp.array([1]),
[1],
],
ids=["numpy", "dpnp", "list"],
)
def test_create_from_usm_ndarray_error(arr):
with pytest.raises(TypeError):
dpnp.ndarray._create_from_usm_ndarray(arr)
@pytest.mark.parametrize("arr_dtype", get_all_dtypes(no_none=True))
@pytest.mark.parametrize(
"arr",
[[-2, -1, 0, 1, 2], [[-2, -1], [1, 2]], []],
ids=["[-2, -1, 0, 1, 2]", "[[-2, -1], [1, 2]]", "[]"],
)
def test_flatten(arr, arr_dtype):
a = get_abs_array(arr, arr_dtype)
ia = dpnp.array(a)
expected = a.flatten()
result = ia.flatten()
assert_array_equal(result, expected)
@pytest.mark.parametrize(
"shape",
[(), 0, (0,), (2), (5, 2), (5, 0, 2), (5, 3, 2)],
ids=["()", "0", "(0,)", "(2)", "(5, 2)", "(5, 0, 2)", "(5, 3, 2)"],
)
@pytest.mark.parametrize("order", ["C", "F"])
def test_flags(shape, order):
usm_array = dpt.usm_ndarray(shape, order=order)
a = numpy.ndarray(shape, order=order)
ia = dpnp.ndarray(shape, order=order)
assert usm_array.flags == ia.flags
assert a.flags.c_contiguous == ia.flags.c_contiguous
assert a.flags.f_contiguous == ia.flags.f_contiguous
@pytest.mark.parametrize(
"dtype",
[numpy.complex64, numpy.float32, numpy.int64, numpy.int32, numpy.bool_],
)
@pytest.mark.parametrize("strides", [(1, 4), (4, 1)], ids=["(1, 4)", "(4, 1)"])
@pytest.mark.parametrize("order", ["C", "F"])
def test_flags_strides(dtype, order, strides):
itemsize = numpy.dtype(dtype).itemsize
numpy_strides = tuple([el * itemsize for el in strides])
usm_array = dpt.usm_ndarray(
(4, 4), dtype=dtype, order=order, strides=strides
)
a = numpy.ndarray((4, 4), dtype=dtype, order=order, strides=numpy_strides)
ia = dpnp.ndarray((4, 4), dtype=dtype, order=order, strides=numpy_strides)
assert usm_array.flags == ia.flags
assert a.flags.c_contiguous == ia.flags.c_contiguous
assert a.flags.f_contiguous == ia.flags.f_contiguous
def test_flags_writable():
a = dpnp.arange(10, dtype="f4")
a.flags["W"] = False
a.shape = (5, 2)
assert not a.flags.writable
assert not a.T.flags.writable
assert not a.real.flags.writable
assert not a[0:3].flags.writable
a = dpnp.arange(10, dtype="c8")
a.flags["W"] = False
assert not a.real.flags.writable
assert not a.imag.flags.writable
class TestArrayNamespace:
def test_basic(self):
a = dpnp.arange(2)
xp = a.__array_namespace__()
assert xp is dpnp
@pytest.mark.parametrize("api_version", [None, "2024.12"])
def test_api_version(self, api_version):
a = dpnp.arange(2)
xp = a.__array_namespace__(api_version=api_version)
assert xp is dpnp
@pytest.mark.parametrize(
"api_version", ["2021.12", "2022.12", "2023.12", "2025.12"]
)
def test_unsupported_api_version(self, api_version):
a = dpnp.arange(2)
assert_raises_regex(
ValueError,
"Only 2024.12 is supported",
a.__array_namespace__,
api_version=api_version,
)
@pytest.mark.parametrize(
"api_version",
[
2023,
(2022,),
[
2021,
],
],
)
def test_wrong_api_version(self, api_version):
a = dpnp.arange(2)
assert_raises_regex(
TypeError,
"Expected type str",
a.__array_namespace__,
api_version=api_version,
)
class TestArrayUfunc:
def test_add(self):
a = numpy.ones(10)
b = dpnp.ones(10)
msg = "An array must be any of supported type"
with assert_raises_regex(TypeError, msg):
a + b
with assert_raises_regex(TypeError, msg):
b + a
def test_add_inplace(self):
a = numpy.ones(10)
b = dpnp.ones(10)
with assert_raises_regex(
TypeError, "operand 'dpnp_array' does not support ufuncs"
):
a += b
class TestItem:
@pytest.mark.parametrize("args", [2, 7, (1, 2), (2, 0)])
def test_basic(self, args):
a = numpy.arange(12).reshape(3, 4)
ia = dpnp.array(a)
expected = a.item(args)
result = ia.item(args)
assert isinstance(result, int)
assert expected == result
def test_0D(self):
a = numpy.array(5)
ia = dpnp.array(a)
expected = a.item()
result = ia.item()
assert isinstance(result, int)
assert expected == result
def test_error(self):
ia = dpnp.arange(12).reshape(3, 4)
with pytest.raises(ValueError):
ia.item()
class TestUsmNdarrayProtocol:
def test_basic(self):
a = dpnp.arange(256, dtype=dpnp.int64)
usm_a = dpt.asarray(a)
assert a.sycl_queue == usm_a.sycl_queue
assert a.usm_type == usm_a.usm_type
assert a.dtype == usm_a.dtype
assert usm_a.usm_data.reference_obj is None
assert (a == usm_a).all()
def test_print_dpnp_int():
result = repr(dpnp.array([1, 0, 2, -3, -1, 2, 21, -9], dtype="i4"))
expected = "array([ 1, 0, 2, -3, -1, 2, 21, -9], dtype=int32)"
assert result == expected
result = str(dpnp.array([1, 0, 2, -3, -1, 2, 21, -9], dtype="i4"))
expected = "[ 1 0 2 -3 -1 2 21 -9]"
assert result == expected
# int32
result = repr(dpnp.array([1, -1, 21], dtype=dpnp.int32))
expected = "array([ 1, -1, 21], dtype=int32)"
assert result == expected
result = str(dpnp.array([1, -1, 21], dtype=dpnp.int32))
expected = "[ 1 -1 21]"
assert result == expected
# uint8
result = repr(dpnp.array([1, 0, 3], dtype=numpy.uint8))
expected = "array([1, 0, 3], dtype=uint8)"
assert result == expected
result = str(dpnp.array([1, 0, 3], dtype=numpy.uint8))
expected = "[1 0 3]"
assert result == expected
@pytest.mark.parametrize("dtype", get_float_dtypes())
def test_print_dpnp_float(dtype):
result = repr(dpnp.array([1, -1, 21], dtype=dtype))
expected = "array([ 1., -1., 21.])"
if dtype is dpnp.float32:
expected = expected[:-1] + ", dtype=float32)"
result = str(dpnp.array([1, -1, 21], dtype=dtype))
expected = "[ 1. -1. 21.]"
assert result == expected
@pytest.mark.parametrize("dtype", get_complex_dtypes())
def test_print_dpnp_complex(dtype):
result = repr(dpnp.array([1, -1, 21], dtype=dtype))
expected = "array([ 1.+0.j, -1.+0.j, 21.+0.j])"
if dtype is dpnp.complex64:
expected = expected[:-1] + ", dtype=complex64)"
assert result == expected
result = str(dpnp.array([1, -1, 21], dtype=dtype))
expected = "[ 1.+0.j -1.+0.j 21.+0.j]"
assert result == expected
def test_print_dpnp_boolean():
result = repr(dpnp.array([1, 0, 3], dtype=bool))
expected = "array([ True, False, True])"
assert result == expected
result = str(dpnp.array([1, 0, 3], dtype=bool))
expected = "[ True False True]"
assert result == expected
@pytest.mark.parametrize("character", [dpnp.nan, dpnp.inf])
def test_print_dpnp_special_character(character):
result = repr(dpnp.array([1.0, 0.0, character, 3.0]))
expected = f"array([ 1., 0., {character}, 3.])"
if not has_support_aspect64():
expected = expected[:-1] + ", dtype=float32)"
assert result == expected
result = str(dpnp.array([1.0, 0.0, character, 3.0]))
expected = f"[ 1. 0. {character} 3.]"
assert result == expected
# TODO: repr formatting is inconsistent (scientific vs integer-like output)
# This is a minor issue that does not depend on compiler flags
@pytest.mark.skip(reason="SAT-8452")
def test_print_dpnp_1d():
dtype = dpnp.default_float_type()
result = repr(dpnp.arange(10000, dtype=dtype))
expected = "array([0.000e+00, 1.000e+00, 2.000e+00, ..., 9.997e+03, 9.998e+03,\n 9.999e+03], shape=(10000,))"
if not has_support_aspect64():
expected = expected[:-1] + ", dtype=float32)"
assert result == expected
result = str(dpnp.arange(10000, dtype=dtype))
expected = (
"[0.000e+00 1.000e+00 2.000e+00 ... 9.997e+03 9.998e+03 9.999e+03]"
)
assert result == expected
def test_print_dpnp_2d():
dtype = dpnp.default_float_type()
result = repr(dpnp.array([[1, 2], [3, 4]], dtype=dtype))
expected = "array([[1., 2.],\n [3., 4.]])"
if not has_support_aspect64():
expected = expected[:-1] + ", dtype=float32)"
assert result == expected
result = str(dpnp.array([[1, 2], [3, 4]]))
expected = "[[1 2]\n [3 4]]"
assert result == expected
def test_print_dpnp_zero_shape():
result = repr(dpnp.empty(shape=(0, 0)))
if has_support_aspect64():
expected = "array([], shape=(0, 0), dtype=float64)"
else:
expected = "array([], shape=(0, 0), dtype=float32)"
assert result == expected
result = str(dpnp.empty(shape=(0, 0)))
expected = "[]"
assert result == expected
@testing.with_requires("numpy>=2.4")
@pytest.mark.parametrize("xp", [dpnp, numpy])
@pytest.mark.parametrize("shape", [tuple(), (1,), (1, 1), (1, 1, 1)])
class TestPythonScalarConversion:
@pytest.mark.parametrize(
"dtype", get_all_dtypes(no_none=True, no_float16=False, no_complex=True)
)
def test_bool_conversion(self, xp, shape, dtype):
a = xp.full(shape, 5, dtype=dtype)
if xp == dpnp and len(shape) > 0:
# dpnp behavior differs from NumPy:
# non-0D singe-element arrays are not convertible to
# Python bool
assert_raises(TypeError, bool, a)
else:
# NumPy allows conversion to Python bool for
# non-0D singe-element arrays
assert bool(a) is True
@pytest.mark.parametrize(
"dtype", get_all_dtypes(no_none=True, no_float16=False, no_complex=True)
)
def test_bool_method_conversion(self, xp, shape, dtype):
a = xp.full(shape, 5, dtype=dtype)
if xp == dpnp and len(shape) > 0:
assert_raises(TypeError, getattr(a, "__bool__"))
else:
assert a.__bool__() is True
@pytest.mark.parametrize("func", [float, int, complex])
@pytest.mark.parametrize(
"dtype", get_all_dtypes(no_none=True, no_float16=False, no_complex=True)
)
def test_non_bool_conversion(self, xp, func, shape, dtype):
a = xp.full(shape, 5, dtype=dtype)
if len(shape) > 0:
# Non-0D arrays are not allowed to be converted to
# Python numeric scalars
assert_raises(TypeError, func, a)
else:
# 0D arrays are allowed to be converted to
# Python numeric scalars
expected = 1 if dtype == xp.bool else 5
assert func(a) == func(expected)
@pytest.mark.parametrize("method", ["__float__", "__int__", "__complex__"])
@pytest.mark.parametrize(
"dtype", get_all_dtypes(no_none=True, no_float16=False, no_complex=True)
)
def test_non_bool_method_conversion(self, xp, method, shape, dtype):
a = xp.full(shape, 5, dtype=dtype)
if len(shape) > 0:
assert_raises(TypeError, getattr(a, method))
else:
expected = 1 if dtype == xp.bool else 5
func = {"__float__": float, "__int__": int, "__complex__": complex}[
method
]
assert getattr(a, method)() == func(expected)
@pytest.mark.parametrize("index_dtype", [dpnp.int32, dpnp.int64])
def test_array_as_index(index_dtype):
ind_arr = dpnp.ones((1,), dtype=index_dtype)
a = dpnp.arange(ind_arr.size + 1)
assert a[tuple(ind_arr)] == a[1]
# numpy.ndarray.mT is available since numpy >= 2.0
@testing.with_requires("numpy>=2.0")
@pytest.mark.parametrize(
"shape",
[(3, 5), (2, 5, 2), (2, 3, 3, 6)],
ids=["(3, 5)", "(2, 5, 2)", "(2, 3, 3, 6)"],
)
def test_matrix_transpose(shape):
a = numpy.arange(numpy.prod(shape)).reshape(shape)
dp_a = dpnp.array(a)
expected = a.mT
result = dp_a.mT
assert_allclose(result, expected)
# result is a view of dp_a:
# changing result, modifies dp_a
first_elem = (0,) * dp_a.ndim
result[first_elem] = -1.0
assert dp_a[first_elem] == -1.0
@testing.with_requires("numpy>=2.0")
def test_matrix_transpose_error():
# 1D array
dp_a = dpnp.arange(6)
with pytest.raises(ValueError):
dp_a.mT
def test_ravel():
a = dpnp.ones((2, 2))
b = a.ravel()
a[0, 0] = 5
assert_array_equal(a.ravel(), b)
def test_repeat():
a = numpy.arange(4).repeat(3)
ia = dpnp.arange(4).repeat(3)
assert_array_equal(a, ia)
def test_clip():
a = numpy.arange(10)
ia = dpnp.arange(10)
result = dpnp.clip(ia, 3, 7)
expected = numpy.clip(a, 3, 7)
assert_array_equal(result, expected)
def test_rmatmul_dpnp_array():
a = dpnp.ones(10)
b = dpnp.ones(10)
class Dummy(dpnp.ndarray):
def __init__(self, x):
self._array_obj = x.get_array()
def __matmul__(self, other):
return NotImplemented
d = Dummy(a)
result = d @ b
expected = a @ b
assert (result == expected).all()
def test_rmatmul_numpy_array():
a = dpnp.ones(10)
b = numpy.ones(10)
with pytest.raises(TypeError):
b @ a
@pytest.mark.parametrize("xp", [dpnp, numpy])
def test_pow_modulo(xp):
a = xp.array([2, 3, 4])
b = xp.array([5, 2, 3])
assert a.__pow__(b, 10) == NotImplemented
assert a.__rpow__(b, 10) == NotImplemented
assert (a.__pow__(b, None) == a**b).all()
assert (a.__rpow__(b, None) == b**a).all()