-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathdpnp_array.py
More file actions
2533 lines (1970 loc) · 73.2 KB
/
Copy pathdpnp_array.py
File metadata and controls
2533 lines (1970 loc) · 73.2 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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# Copyright (c) 2016, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
"""
Interface of an ndarray representing a multidimensional tensor of numeric
elements stored in a USM allocation on a SYCL device.
"""
# pylint: disable=duplicate-code
# pylint: disable=invalid-name
# pylint: disable=protected-access
import warnings
import dpnp
import dpnp.tensor as dpt
import dpnp.tensor._type_utils as dtu
from . import memory as dpm
from .exceptions import AxisError
def _get_unwrapped_index_key(key):
"""
Get an unwrapped index key.
Return a key where each nested instance of DPNP array is unwrapped into
USM ndarray for further processing in DPCTL advanced indexing functions.
"""
if isinstance(key, tuple):
if any(isinstance(x, dpnp_array) for x in key):
# create a new tuple from the input key with unwrapped DPNP arrays
return tuple(
x.get_array() if isinstance(x, dpnp_array) else x for x in key
)
elif isinstance(key, dpnp_array):
return key.get_array()
return key
# pylint: disable=too-many-public-methods
class dpnp_array:
"""
An array object represents a multidimensional tensor of numeric elements
stored in a USM allocation on a SYCL device.
This is a wrapper around :class:`dpnp.tensor.usm_ndarray` that provides
methods to be compliant with original NumPy.
"""
# pylint: disable=too-many-positional-arguments
def __init__(
self,
shape,
dtype=None,
buffer=None,
offset=0,
strides=None,
order="C",
device=None,
usm_type="device",
sycl_queue=None,
):
if order is None:
order = "C"
if buffer is not None:
# expecting to have buffer as dpnp.ndarray and usm_ndarray,
# or as USM memory allocation
if isinstance(buffer, dpnp_array):
buffer = buffer.get_array()
offset += buffer._element_offset
if dtype is None and hasattr(buffer, "dtype"):
dtype = buffer.dtype
else:
buffer = usm_type
if strides is not None:
# dpctl expects strides as elements displacement in memory,
# while dpnp (and numpy as well) relies on bytes displacement
if dtype is None:
dtype = dpnp.default_float_type(
device=device, sycl_queue=sycl_queue
)
it_sz = dpnp.dtype(dtype).itemsize
strides = tuple(el // it_sz for el in strides)
sycl_queue_normalized = dpnp.get_normalized_queue_device(
device=device, sycl_queue=sycl_queue
)
self._array_obj = dpt.usm_ndarray(
shape,
dtype=dtype,
strides=strides,
buffer=buffer,
offset=offset,
order=order,
buffer_ctor_kwargs={"queue": sycl_queue_normalized},
array_namespace=dpnp,
)
def __abs__(self, /):
r"""Return :math:`|\text{self}|`."""
return dpnp.abs(self)
def __add__(self, other, /):
r"""Return :math:`\text{self + value}`."""
return dpnp.add(self, other)
def __and__(self, other, /):
r"""Return :math:`\text{self & value}`."""
return dpnp.bitwise_and(self, other)
def __array__(self, dtype=None, /, *, copy=None):
"""
NumPy's array protocol method to disallow implicit conversion.
Without this definition, ``numpy.asarray(dpnp_arr)`` converts
:class:`dpnp.ndarray` instance into NumPy array with data type `object`
and every element being zero-dimensional :class:`dpnp.ndarray`.
""" # noqa: D403
raise TypeError(
"Implicit conversion to a NumPy array is not allowed. "
"Please use `.asnumpy()` to construct a NumPy array explicitly."
)
# '__array_finalize__',
# '__array_function__',
# '__array_interface__',
def __array_namespace__(self, /, *, api_version=None):
"""
Return array namespace, member functions of which implement data API.
Parameters
----------
api_version : {None, str}, optional
Request namespace compliant with given version of array API. If
``None``, namespace for the most recent supported version is
returned.
Default: ``None``.
Returns
-------
out : any
An object representing the array API namespace. It should have
every top-level function defined in the specification as
an attribute. It may contain other public names as well, but it is
recommended to only include those names that are part of the
specification.
"""
return self._array_obj.__array_namespace__(api_version=api_version)
# '__array_priority__',
# '__array_struct__',
__array_ufunc__ = None
# '__array_wrap__',
def __bool__(self, /):
"""``True`` if `self` else ``False``."""
return self._array_obj.__bool__()
def __bytes__(self):
r"""Return :math:`\text{bytes(self)}`."""
return bytes(self.asnumpy())
# '__class__',
# `__class_getitem__`,
def __complex__(self, /):
"""Convert a zero-dimensional array to a Python complex object."""
return self._array_obj.__complex__()
def __contains__(self, value, /):
r"""Return :math:`\text{value in self}`."""
return (self == value).any()
def __copy__(self):
"""
Used if :func:`copy.copy` is called on an array. Return a copy of the
array.
Equivalent to ``a.copy(order="K")``.
"""
return self.copy(order="K")
# '__deepcopy__',
# '__dir__',
def __divmod__(self, other, /):
r"""Return :math:`\text{divmod(self, value)}`."""
return dpnp.divmod(self, other)
def __dlpack__(
self, /, *, stream=None, max_version=None, dl_device=None, copy=None
):
"""
Produce DLPack capsule.
Parameters
----------
stream : {:class:`dpctl.SyclQueue`, None}, optional
Execution queue to synchronize with. If ``None``, synchronization
is not performed.
Default: ``None``.
max_version : {tuple of ints, None}, optional
The maximum DLPack version the consumer (caller of ``__dlpack__``)
supports. As ``__dlpack__`` may not always return a DLPack capsule
with version `max_version`, the consumer must verify the version
even if this argument is passed.
Default: ``None``.
dl_device : {tuple, None}, optional:
The device the returned DLPack capsule will be placed on. The
device must be a 2-tuple matching the format of
:meth:`dpnp.ndarray.__dlpack_device__`, an integer enumerator
representing the device type followed by an integer representing
the index of the device.
Default: ``None``.
copy : {bool, None}, optional:
Boolean indicating whether or not to copy the input.
* If `copy` is ``True``, the input will always be copied.
* If ``False``, a ``BufferError`` will be raised if a copy is
deemed necessary.
* If ``None``, a copy will be made only if deemed necessary,
otherwise, the existing memory buffer will be reused.
Default: ``None``.
Raises
------
MemoryError
when host memory can not be allocated.
DLPackCreationError
when array is allocated on a partitioned SYCL device, or with
a non-default context.
BufferError
when a copy is deemed necessary but `copy` is ``False`` or when
the provided `dl_device` cannot be handled.
"""
return self._array_obj.__dlpack__(
stream=stream,
max_version=max_version,
dl_device=dl_device,
copy=copy,
)
def __dlpack_device__(self, /):
"""
Give a tuple (``device_type``, ``device_id``) corresponding to
``DLDevice`` entry in ``DLTensor`` in DLPack protocol.
The tuple describes the non-partitioned device where the array has been
allocated, or the non-partitioned parent device of the allocation
device.
See :class:`dpnp.DLDeviceType` for a list of devices supported by the
DLPack protocol.
Raises
------
DLPackCreationError
when the ``device_id`` could not be determined.
"""
return self._array_obj.__dlpack_device__()
def __eq__(self, other, /):
r"""Return :math:`\text{self == value}`."""
return dpnp.equal(self, other)
def __float__(self, /):
"""Convert a zero-dimensional array to a Python float object."""
return self._array_obj.__float__()
def __floordiv__(self, other, /):
r"""Return :math:`\text{self // value}`."""
return dpnp.floor_divide(self, other)
def __format__(self, format_spec):
r"""Return :math:`\text{format(self, format_spec)}`."""
return format(self.asnumpy(), format_spec)
def __ge__(self, other, /):
r"""Return :math:`\text{self >= value}`."""
return dpnp.greater_equal(self, other)
def __getitem__(self, key, /):
r"""Return :math:`\text{self[key]}`."""
key = _get_unwrapped_index_key(key)
item = self._array_obj.__getitem__(key)
return dpnp_array._create_from_usm_ndarray(item)
# '__getstate__',
def __gt__(self, other, /):
r"""Return :math:`\text{self > value}`."""
return dpnp.greater(self, other)
# '__hash__',
def __iadd__(self, other, /):
r"""Return :math:`\text{self += value}`."""
dpnp.add(self, other, out=self)
return self
def __iand__(self, other, /):
r"""Return :math:`\text{self &= value}`."""
dpnp.bitwise_and(self, other, out=self)
return self
def __ifloordiv__(self, other, /):
r"""Return :math:`\text{self //= value}`."""
dpnp.floor_divide(self, other, out=self)
return self
def __ilshift__(self, other, /):
r"""Return :math:`\text{self <<= value}`."""
dpnp.left_shift(self, other, out=self)
return self
def __imatmul__(self, other, /):
r"""Return :math:`\text{self @= value}`."""
# Unlike `matmul(a, b, out=a)` we ensure that the result isn't broadcast
# if the result without `out` would have less dimensions than `a`.
# Since the signature of matmul is '(n?,k),(k,m?)->(n?,m?)' this is the
# case exactly when the second operand has both core dimensions.
# We have to enforce this check by passing the correct `axes=`.
if self.ndim == 1:
axes = [(-1,), (-2, -1), (-1,)]
else:
axes = [(-2, -1), (-2, -1), (-2, -1)]
try:
dpnp.matmul(self, other, out=self, dtype=self.dtype, axes=axes)
except AxisError as e:
# AxisError should indicate that the axes argument didn't work out
# which should mean the second operand not being 2 dimensional.
raise ValueError(
"inplace matrix multiplication requires the first operand to "
"have at least one and the second at least two dimensions."
) from e
return self
def __imod__(self, other, /):
r"""Return :math:`\text{self %= value}`."""
dpnp.remainder(self, other, out=self)
return self
def __imul__(self, other, /):
r"""Return :math:`\text{self *= value}`."""
dpnp.multiply(self, other, out=self)
return self
def __index__(self, /):
"""Convert a zero-dimensional array to a Python int object."""
return self._array_obj.__index__()
# '__init_subclass__',
def __int__(self, /):
"""Convert a zero-dimensional array to a Python int object."""
return self._array_obj.__int__()
def __invert__(self, /):
r"""Return :math:`\text{~self}`."""
return dpnp.invert(self)
def __ior__(self, other, /):
r"""Return :math:`\text{self |= value}`."""
dpnp.bitwise_or(self, other, out=self)
return self
def __ipow__(self, other, /):
r"""Return :math:`\text{self **= value}`."""
dpnp.power(self, other, out=self)
return self
def __irshift__(self, other, /):
r"""Return :math:`\text{self >>= value}`."""
dpnp.right_shift(self, other, out=self)
return self
def __isub__(self, other, /):
r"""Return :math:`\text{self -= value}`."""
dpnp.subtract(self, other, out=self)
return self
def __iter__(self, /):
r"""Return :math:`\text{iter(self)}`."""
if self.ndim == 0:
raise TypeError("iteration over a 0-d array")
return (self[i] for i in range(self.shape[0]))
def __itruediv__(self, other, /):
r"""Return :math:`\text{self /= value}`."""
dpnp.true_divide(self, other, out=self)
return self
def __ixor__(self, other, /):
r"""Return :math:`\text{self ^= value}`."""
dpnp.bitwise_xor(self, other, out=self)
return self
def __le__(self, other, /):
r"""Return :math:`\text{self <= value}`."""
return dpnp.less_equal(self, other)
def __len__(self):
r"""Return :math:`\text{len(self)}`."""
return self._array_obj.__len__()
def __lshift__(self, other, /):
r"""Return :math:`\text{self << value}`."""
return dpnp.left_shift(self, other)
def __lt__(self, other, /):
r"""Return :math:`\text{self < value}`."""
return dpnp.less(self, other)
def __matmul__(self, other, /):
r"""Return :math:`\text{self @ value}`."""
return dpnp.matmul(self, other)
def __mod__(self, other, /):
r"""Return :math:`\text{self % value}`."""
return dpnp.remainder(self, other)
def __mul__(self, other, /):
r"""Return :math:`\text{self * value}`."""
return dpnp.multiply(self, other)
def __ne__(self, other, /):
r"""Return :math:`\text{self != value}`."""
return dpnp.not_equal(self, other)
def __neg__(self, /):
r"""Return :math:`\text{-self}`."""
return dpnp.negative(self)
# '__new__',
def __or__(self, other, /):
r"""Return :math:`\text{self | value}`."""
return dpnp.bitwise_or(self, other)
def __pos__(self, /):
r"""Return :math:`\text{+self}`."""
return dpnp.positive(self)
def __pow__(self, other, mod=None, /):
r"""Return :math:`\text{self ** value}`."""
if mod is not None:
return NotImplemented
return dpnp.power(self, other)
def __radd__(self, other, /):
r"""Return :math:`\text{value + self}`."""
return dpnp.add(other, self)
def __rand__(self, other, /):
r"""Return :math:`\text{value & self}`."""
return dpnp.bitwise_and(other, self)
def __rdivmod__(self, other, /):
r"""Return :math:`\text{divmod(value, self)}`."""
return dpnp.divmod(other, self)
# '__reduce__',
# '__reduce_ex__',
def __repr__(self):
r"""Return :math:`\text{repr(self)}`."""
return dpt.usm_ndarray_repr(self._array_obj, prefix="array")
def __rfloordiv__(self, other, /):
r"""Return :math:`\text{value // self}`."""
return dpnp.floor_divide(other, self)
def __rlshift__(self, other, /):
r"""Return :math:`\text{value << self}`."""
return dpnp.left_shift(other, self)
def __rmatmul__(self, other, /):
r"""Return :math:`\text{value @ self}`."""
return dpnp.matmul(other, self)
def __rmod__(self, other, /):
r"""Return :math:`\text{value % self}`."""
return dpnp.remainder(other, self)
def __rmul__(self, other, /):
r"""Return :math:`\text{value * self}`."""
return dpnp.multiply(other, self)
def __ror__(self, other, /):
r"""Return :math:`\text{value | self}`."""
return dpnp.bitwise_or(other, self)
def __rpow__(self, other, mod=None, /):
r"""Return :math:`\text{value ** self}`."""
if mod is not None:
return NotImplemented
return dpnp.power(other, self)
def __rrshift__(self, other, /):
r"""Return :math:`\text{value >> self}`."""
return dpnp.right_shift(other, self)
def __rshift__(self, other, /):
r"""Return :math:`\text{self >> value}`."""
return dpnp.right_shift(self, other)
def __rsub__(self, other, /):
r"""Return :math:`\text{value - self}`."""
return dpnp.subtract(other, self)
def __rtruediv__(self, other, /):
r"""Return :math:`\text{value / self}`."""
return dpnp.true_divide(other, self)
def __rxor__(self, other, /):
r"""Return :math:`\text{value ^ self}`."""
return dpnp.bitwise_xor(other, self)
def __setitem__(self, key, value, /):
r"""Set :math:`\text{self[key]}` to a value."""
key = _get_unwrapped_index_key(key)
if isinstance(value, dpnp_array):
value = value.get_array()
self._array_obj.__setitem__(key, value)
# '__setstate__',
# '__sizeof__',
__slots__ = ("_array_obj",)
def __str__(self):
r"""Return :math:`\text{str(self)}`."""
return self._array_obj.__str__()
def __sub__(self, other, /):
r"""Return :math:`\text{self - value}`."""
return dpnp.subtract(self, other)
@property
def __sycl_usm_array_interface__(self):
"""
Give ``__sycl_usm_array_interface__`` dictionary describing the array.
""" # noqa: D200
return self._array_obj.__sycl_usm_array_interface__
def __truediv__(self, other, /):
r"""Return :math:`\text{self / value}`."""
return dpnp.true_divide(self, other)
@property
def __usm_ndarray__(self):
"""
Property to support ``__usm_ndarray__`` protocol.
It assumes to return :class:`dpnp.tensor.usm_ndarray` instance
corresponding to the content of the object.
This property is intended to speed-up conversion from
:class:`dpnp.ndarray` to :class:`dpnp.tensor.usm_ndarray` passed into
:func:`dpnp.tensor.asarray` function. The input object that implements
``__usm_ndarray__`` protocol is recognized as owner of USM allocation
that is managed by a smart pointer, and asynchronous deallocation
will not involve GIL.
"""
return self._array_obj
def __xor__(self, other, /):
r"""Return :math:`\text{self ^ value}`."""
return dpnp.bitwise_xor(self, other)
@staticmethod
def _create_from_usm_ndarray(usm_ary: dpt.usm_ndarray):
"""
Return :class:`dpnp.ndarray` instance from USM allocation providing
by an instance of :class:`dpnp.tensor.usm_ndarray`.
"""
if not isinstance(usm_ary, dpt.usm_ndarray):
raise TypeError(
f"Expected dpnp.tensor.usm_ndarray, got {type(usm_ary)}"
)
res = dpnp_array.__new__(dpnp_array)
res._array_obj = usm_ary
res._array_obj._set_namespace(dpnp)
return res
def _create_view(self, array_class, shape, dtype, strides):
"""
Create a view of an array with the specified class.
The method handles subclass instantiation by creating a usm_ndarray
view and then wrapping it in the appropriate class.
Parameters
----------
array_class : type
The class to instantiate (dpnp_array or a subclass).
shape : tuple
Shape of the view.
dtype : dtype
Data type of the view (can be None to keep source's dtype).
strides : tuple
Strides of the view.
Returns
-------
view : array_class instance
A view of the array as the specified class.
"""
if dtype is None:
dtype = self.dtype
# create the underlying usm_ndarray view
usm_view = dpt.usm_ndarray(
shape,
dtype=dtype,
buffer=self._array_obj,
strides=tuple(s // dpnp.dtype(dtype).itemsize for s in strides),
)
# wrap the view into the appropriate class
if array_class is dpnp_array:
res = dpnp_array._create_from_usm_ndarray(usm_view)
else:
# for subclasses, create using __new__ and set up manually
res = array_class.__new__(array_class)
res._array_obj = usm_view
res._array_obj._set_namespace(dpnp)
if hasattr(res, "__array_finalize__"):
res.__array_finalize__(self)
return res
def _view_impl(self, dtype=None, array_class=None):
"""
Internal implementation of view method to avoid an issue where
`type` parameter in ndarray.view method shadowing builtin type.
"""
# check if dtype is actually a type
if dtype is not None:
if isinstance(dtype, type) and issubclass(dtype, dpnp_array):
if array_class is not None:
raise ValueError("Cannot specify output type twice")
array_class = dtype
dtype = None
# validate array_class parameter
if not (
array_class is None
or isinstance(array_class, type)
and issubclass(array_class, dpnp_array)
):
raise ValueError("Type must be a sub-type of ndarray type")
if array_class is None:
# it's a view on dpnp.ndarray
array_class = self.__class__
old_sh = self.shape
old_strides = self.strides
if dtype is None:
return self._create_view(array_class, old_sh, None, old_strides)
new_dt = dpnp.dtype(dtype)
new_dt = dtu._to_device_supported_dtype(new_dt, self.sycl_device)
new_itemsz = new_dt.itemsize
old_itemsz = self.dtype.itemsize
if new_itemsz == old_itemsz:
return self._create_view(array_class, old_sh, new_dt, old_strides)
ndim = self.ndim
if ndim == 0:
raise ValueError(
"Changing the dtype of a 0d array is only supported "
"if the itemsize is unchanged"
)
# resize on last axis only
axis = ndim - 1
if (
old_sh[axis] != 1
and self.size != 0
and old_strides[axis] != old_itemsz
):
raise ValueError(
"To change to a dtype of a different size, "
"the last axis must be contiguous"
)
# normalize strides whenever itemsize changes
new_strides = tuple(
old_strides[i] if i != axis else new_itemsz for i in range(ndim)
)
new_dim = old_sh[axis] * old_itemsz
if new_dim % new_itemsz != 0:
raise ValueError(
"When changing to a larger dtype, its size must be a divisor "
"of the total size in bytes of the last axis of the array"
)
# normalize shape whenever itemsize changes
new_sh = tuple(
old_sh[i] if i != axis else new_dim // new_itemsz
for i in range(ndim)
)
return self._create_view(array_class, new_sh, new_dt, new_strides)
def all(self, axis=None, *, out=None, keepdims=False, where=True):
"""
Return ``True`` if all elements evaluate to ``True``.
Refer to :obj:`dpnp.all` for full documentation.
See Also
--------
:obj:`dpnp.all` : equivalent function
"""
return dpnp.all(
self, axis=axis, out=out, keepdims=keepdims, where=where
)
def any(self, axis=None, *, out=None, keepdims=False, where=True):
"""
Return ``True`` if any of the elements of `a` evaluate to ``True``.
Refer to :obj:`dpnp.any` for full documentation.
See Also
--------
:obj:`dpnp.any` : equivalent function
"""
return dpnp.any(
self, axis=axis, out=out, keepdims=keepdims, where=where
)
def argmax(self, /, axis=None, out=None, *, keepdims=False):
"""
Return array of indices of the maximum values along the given axis.
Refer to :obj:`dpnp.argmax` for full documentation.
"""
return dpnp.argmax(self, axis=axis, out=out, keepdims=keepdims)
def argmin(self, /, axis=None, out=None, *, keepdims=False):
"""
Return array of indices to the minimum values along the given axis.
Refer to :obj:`dpnp.argmin` for full documentation.
"""
return dpnp.argmin(self, axis=axis, out=out, keepdims=keepdims)
# 'argpartition',
def argsort(
self, axis=-1, kind=None, order=None, *, descending=False, stable=None
):
"""
Return an ndarray of indices that sort the array along the specified
axis.
Refer to :obj:`dpnp.argsort` for full documentation.
Parameters
----------
axis : {None, int}, optional
Axis along which to sort. If ``None``, the array is flattened
before sorting. The default is ``-1``, which sorts along the last
axis.
Default: ``-1``.
kind : {None, "stable", "mergesort", "radixsort"}, optional
Sorting algorithm. The default is ``None``, which uses parallel
merge-sort or parallel radix-sort algorithms depending on the array
data type.
Default: ``None``.
descending : bool, optional
Sort order. If ``True``, the array must be sorted in descending
order (by value). If ``False``, the array must be sorted in
ascending order (by value).
Default: ``False``.
stable : {None, bool}, optional
Sort stability. If ``True``, the returned array will maintain the
relative order of `a` values which compare as equal. The same
behavior applies when set to ``False`` or ``None``.
Internally, this option selects ``kind="stable"``.
Default: ``None``.
See Also
--------
:obj:`dpnp.sort` : Return a sorted copy of an array.
:obj:`dpnp.argsort` : Return the indices that would sort an array.
:obj:`dpnp.lexsort` : Indirect stable sort on multiple keys.
:obj:`dpnp.searchsorted` : Find elements in a sorted array.
:obj:`dpnp.partition` : Partial sort.
Examples
--------
>>> import dpnp as np
>>> a = np.array([3, 1, 2])
>>> a.argsort()
array([1, 2, 0])
>>> a = np.array([[0, 3], [2, 2]])
>>> a.argsort(axis=0)
array([[0, 1],
[1, 0]])
"""
return dpnp.argsort(
self, axis, kind, order, descending=descending, stable=stable
)
def asnumpy(self):
"""
Copy content of the array into :class:`numpy.ndarray` instance of
the same shape and data type.
Returns
-------
out : numpy.ndarray
An instance of :class:`numpy.ndarray` populated with the array
content.
"""
return dpt.asnumpy(self._array_obj)
def astype(
self,
dtype,
order="K",
casting="unsafe",
subok=True,
copy=True,
device=None,
):
"""
Copy the array with data type casting.
Refer to :obj:`dpnp.astype` for full documentation.
Parameters
----------
dtype : {None, str, dtype object}
Target data type.
order : {None, "C", "F", "A", "K"}, optional
Row-major (C-style) or column-major (Fortran-style) order.
When `order` is ``"A"``, it uses ``"F"`` if `a` is column-major and
uses ``"C"`` otherwise. And when `order` is ``"K"``, it keeps
strides as closely as possible.
Default: ``"K"``.
casting : {"no", "equiv", "safe", "same_kind", "unsafe"}, optional
Controls what kind of data casting may occur. Defaults to
``"unsafe"`` for backwards compatibility.
- "no" means the data types should not be cast at all.
- "equiv" means only byte-order changes are allowed.
- "safe" means only casts which can preserve values are allowed.
- "same_kind" means only safe casts or casts within a kind,
like float64 to float32, are allowed.
- "unsafe" means any data conversions may be done.
Default: ``"unsafe"``.
copy : bool, optional
Specifies whether to copy an array when the specified dtype matches
the data type of that array. If ``True``, a newly allocated array
must always be returned. If ``False`` and the specified dtype
matches the data type of that array, the self array must be
returned; otherwise, a newly allocated array must be returned.
Default: ``True``.
device : {None, string, SyclDevice, SyclQueue, Device}, optional
An array API concept of device where the output array is created.
`device` can be ``None``, a oneAPI filter selector string,
an instance of :class:`dpctl.SyclDevice` corresponding to
a non-partitioned SYCL device, an instance of
:class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object
returned by :attr:`dpnp.ndarray.device`.
If the value is ``None``, returned array is created on the same
device as that array.
Default: ``None``.
Returns
-------
out : dpnp.ndarray
An array having the specified data type.
Limitations
-----------
Parameter `subok` is supported with default value.
Otherwise ``NotImplementedError`` exception will be raised.
Examples
--------
>>> import dpnp as np
>>> x = np.array([1, 2, 2.5]); x
array([1. , 2. , 2.5])
>>> x.astype(int)
array([1, 2, 2])
"""
if subok is not True:
raise NotImplementedError(
f"subok={subok} is currently not supported"
)
return dpnp.astype(
self, dtype, order=order, casting=casting, copy=copy, device=device
)
# 'base',
# 'byteswap',
def choose(self, /, choices, out=None, mode="wrap"):
"""