-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy patharray.py
More file actions
4558 lines (3676 loc) · 133 KB
/
array.py
File metadata and controls
4558 lines (3676 loc) · 133 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 2021-2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import operator
import warnings
from functools import reduce, wraps
from inspect import signature
from typing import (
TYPE_CHECKING,
Any,
Callable,
Optional,
Sequence,
TypeVar,
Union,
cast,
)
import numpy as np
from legate.core import Array, Field
from legate.core.utils import OrderedSet
from numpy.core.multiarray import ( # type: ignore [attr-defined]
normalize_axis_index,
)
from numpy.core.numeric import ( # type: ignore [attr-defined]
normalize_axis_tuple,
)
from typing_extensions import ParamSpec
from .config import (
BinaryOpCode,
ConvertCode,
FFTDirection,
FFTNormalization,
FFTType,
ScanCode,
UnaryOpCode,
UnaryRedCode,
)
from .coverage import FALLBACK_WARNING, clone_class, is_implemented
from .runtime import runtime
from .types import NdShape
from .utils import (
calculate_volume,
deep_apply,
dot_modes,
to_core_dtype,
tuple_pop,
)
if TYPE_CHECKING:
from pathlib import Path
import numpy.typing as npt
from .thunk import NumPyThunk
from .types import (
BoundsMode,
CastingKind,
NdShapeLike,
OrderType,
SelectKind,
SortSide,
SortType,
)
from math import prod
R = TypeVar("R")
P = ParamSpec("P")
def add_boilerplate(
*array_params: str,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""
Adds required boilerplate to the wrapped cunumeric.ndarray or module-level
function.
Every time the wrapped function is called, this wrapper will:
* Convert all specified array-like parameters, plus the special "out"
parameter (if present), to cuNumeric ndarrays.
* Convert the special "where" parameter (if present) to a valid predicate.
"""
keys = OrderedSet(array_params)
assert len(keys) == len(array_params)
def decorator(func: Callable[P, R]) -> Callable[P, R]:
assert not hasattr(
func, "__wrapped__"
), "this decorator must be the innermost"
# For each parameter specified by name, also consider the case where
# it's passed as a positional parameter.
indices: OrderedSet[int] = OrderedSet()
where_idx: Optional[int] = None
out_idx: Optional[int] = None
params = signature(func).parameters
extra = keys - OrderedSet(params)
assert len(extra) == 0, f"unknown parameter(s): {extra}"
for idx, param in enumerate(params):
if param == "where":
where_idx = idx
elif param == "out":
out_idx = idx
elif param in keys:
indices.add(idx)
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> R:
assert (where_idx is None or len(args) <= where_idx) and (
out_idx is None or len(args) <= out_idx
), "'where' and 'out' should be passed as keyword arguments"
# Convert relevant arguments to cuNumeric ndarrays
args = tuple(
convert_to_cunumeric_ndarray(arg)
if idx in indices and arg is not None
else arg
for (idx, arg) in enumerate(args)
)
for k, v in kwargs.items():
if v is None:
continue
elif k == "out":
kwargs[k] = convert_to_cunumeric_ndarray(v, share=True)
if not kwargs[k].flags.writeable:
raise ValueError("out is not writeable")
elif (k in keys) or (k == "where"):
kwargs[k] = convert_to_cunumeric_ndarray(v)
return func(*args, **kwargs)
return wrapper
return decorator
def convert_to_cunumeric_ndarray(obj: Any, share: bool = False) -> ndarray:
# If this is an instance of one of our ndarrays then we're done
if isinstance(obj, ndarray):
return obj
# Ask the runtime to make a numpy thunk for this object
thunk = runtime.get_numpy_thunk(obj, share=share)
writeable = (
obj.flags.writeable if isinstance(obj, np.ndarray) and share else True
)
return ndarray(shape=None, thunk=thunk, writeable=writeable)
def maybe_convert_to_np_ndarray(obj: Any) -> Any:
"""
Converts cuNumeric arrays into NumPy arrays, otherwise has no effect.
"""
from .ma import MaskedArray
if isinstance(obj, (ndarray, MaskedArray)):
return obj.__array__()
return obj
def check_writeable(arr: Union[ndarray, tuple[ndarray, ...], None]) -> None:
"""
Check if the current array is writeable
This check needs to be manually inserted
with consideration on the behavior of the corresponding method
"""
if arr is None:
return
check_list = (arr,) if not isinstance(arr, tuple) else arr
if any(not arr.flags.writeable for arr in check_list):
raise ValueError("array is not writeable")
def broadcast_where(
where: Union[ndarray, None], shape: NdShape
) -> Union[ndarray, None]:
if where is not None and where.shape != shape:
from .module import broadcast_to
where = broadcast_to(where, shape)
return where
class flagsobj:
"""
Information about the memory layout of the array.
These flags don't reflect the properties of the cuNumeric array, but
rather the NumPy array that will be produced if the cuNumeric array is
materialized on a single node.
"""
def __init__(self, array: ndarray) -> None:
# prevent infinite __setattr__ recursion
object.__setattr__(self, "_array", array)
def __repr__(self) -> str:
return f"""\
C_CONTIGUOUS : {self["C"]}
F_CONTIGUOUS : {self["F"]}
OWNDATA : {self["O"]}
WRITEABLE : {self["W"]}
ALIGNED : {self["A"]}
WRITEBACKIFCOPY : {self["X"]}
"""
def __eq__(self, other: Any) -> bool:
flags = ("C", "F", "O", "W", "A", "X")
if not isinstance(other, (flagsobj, np.core.multiarray.flagsobj)):
return False
return all(self[f] == other[f] for f in flags) # type: ignore [index]
def __getattr__(self, name: str) -> Any:
if name == "writeable":
return self._array._writeable
flags = self._array.__array__().flags
return getattr(flags, name)
def __setattr__(self, name: str, value: Any) -> None:
if name == "writeable":
self._check_writeable(value)
self._array._writeable = bool(value)
else:
flags = self._array.__array__().flags
setattr(flags, name, value)
def __getitem__(self, key: Any) -> bool:
if key == "W":
return self._array._writeable
flags = self._array.__array__().flags
return flags[key]
def __setitem__(self, key: str, value: Any) -> None:
if key == "W":
self._check_writeable(value)
self._array._writeable = bool(value)
else:
flags = self._array.__array__().flags
flags[key] = value
def _check_writeable(self, value: Any) -> None:
if value and not self._array._writeable:
raise ValueError(
"non-writeable cunumeric arrays cannot be made writeable"
)
NDARRAY_INTERNAL = {
"__array_finalize__",
"__array_function__",
"__array_interface__",
"__array_prepare__",
"__array_priority__",
"__array_struct__",
"__array_ufunc__",
"__array_wrap__",
}
@clone_class(np.ndarray, NDARRAY_INTERNAL, maybe_convert_to_np_ndarray)
class ndarray:
def __init__(
self,
shape: Any,
dtype: npt.DTypeLike = np.float64,
buffer: Union[Any, None] = None,
offset: int = 0,
strides: Union[tuple[int], None] = None,
order: Union[OrderType, None] = None,
thunk: Union[NumPyThunk, None] = None,
inputs: Union[Any, None] = None,
writeable: bool = True,
) -> None:
# `inputs` being a cuNumeric ndarray is definitely a bug
assert not isinstance(inputs, ndarray)
if thunk is None:
assert shape is not None
sanitized_shape = self._sanitize_shape(shape)
if not isinstance(dtype, np.dtype):
dtype = np.dtype(dtype)
if buffer is not None:
# Make a normal numpy array for this buffer
np_array: npt.NDArray[Any] = np.ndarray(
shape=sanitized_shape,
dtype=dtype,
buffer=buffer,
offset=offset,
strides=strides,
order=order,
)
self._thunk = runtime.find_or_create_array_thunk(
np_array, share=False
)
else:
# Filter the inputs if necessary
if inputs is not None:
inputs = [
inp._thunk
for inp in inputs
if isinstance(inp, ndarray)
]
core_dtype = to_core_dtype(dtype)
self._thunk = runtime.create_empty_thunk(
sanitized_shape, core_dtype, inputs
)
else:
self._thunk = thunk
self._legate_data: Union[dict[str, Any], None] = None
self._writeable = writeable
@staticmethod
def _sanitize_shape(
shape: Union[NdShapeLike, Sequence[Any], npt.NDArray[Any], ndarray]
) -> NdShape:
seq: tuple[Any, ...]
if isinstance(shape, (ndarray, np.ndarray)):
if shape.ndim == 0:
seq = (shape.__array__().item(),)
else:
seq = tuple(shape.__array__())
elif np.isscalar(shape):
seq = (shape,)
else:
seq = tuple(cast(NdShape, shape))
try:
# Unfortunately, we can't do this check using
# 'isinstance(value, int)', as the values in a NumPy ndarray
# don't satisfy the predicate (they have numpy value types,
# such as numpy.int64).
result = tuple(operator.index(value) for value in seq)
except TypeError:
raise TypeError(
"expected a sequence of integers or a single integer, "
f"got {shape!r}"
)
return result
# Support for the Legate data interface
@property
def __legate_data_interface__(self) -> dict[str, Any]:
if self._legate_data is None:
# If the thunk is an eager array, we need to convert it to a
# deferred array so we can extract a legate store
deferred_thunk = runtime.to_deferred_array(self._thunk)
# We don't have nullable data for the moment
# until we support masked arrays
dtype = deferred_thunk.base.type
array = Array(dtype, [None, deferred_thunk.base])
self._legate_data = dict()
self._legate_data["version"] = 1
field = Field("cuNumeric Array", dtype)
self._legate_data["data"] = {field: array}
return self._legate_data
# Properties for ndarray
# Disable these since they seem to cause problems
# when our arrays do not last long enough, instead
# users will go through the __array__ method
# @property
# def __array_interface__(self):
# return self.__array__().__array_interface__
# @property
# def __array_priority__(self):
# return self.__array__().__array_priority__
# @property
# def __array_struct__(self):
# return self.__array__().__array_struct__
def __array_function__(
self, func: Any, types: Any, args: tuple[Any], kwargs: dict[str, Any]
) -> Any:
import cunumeric as cn
what = func.__name__
for t in types:
# Be strict about which types we support. Accept superclasses
# (for basic subclassing support) and NumPy.
if not issubclass(type(self), t) and t is not np.ndarray:
return NotImplemented
# We are wrapping all NumPy modules, so we can expect to find every
# NumPy API call in cuNumeric, even if just an "unimplemented" stub.
module = reduce(getattr, func.__module__.split(".")[1:], cn)
cn_func = getattr(module, func.__name__)
# We can't immediately forward to the corresponding cuNumeric
# entrypoint. Say that we reached this point because the user code
# invoked `np.foo(x, bar=True)` where `x` is a `cunumeric.ndarray`. If
# our implementation of `foo` is not complete, and cannot handle
# `bar=True`, then forwarding this call to `cn.foo` would fail. This
# goes against the semantics of `__array_function__`, which shouldn't
# fail if the custom implementation cannot handle the provided
# arguments. Conversely, if the user calls `cn.foo(x, bar=True)`
# directly, that means they requested the cuNumeric implementation
# specifically, and the `NotImplementedError` should not be hidden.
if is_implemented(cn_func):
try:
return cn_func(*args, **kwargs)
except NotImplementedError:
# Inform the user that we support the requested API in general,
# but not this specific combination of arguments.
what = f"the requested combination of arguments to {what}"
# We cannot handle this call, so we will fall back to NumPy.
warnings.warn(
FALLBACK_WARNING.format(what=what),
category=RuntimeWarning,
stacklevel=4,
)
args = deep_apply(args, maybe_convert_to_np_ndarray)
kwargs = deep_apply(kwargs, maybe_convert_to_np_ndarray)
return func(*args, **kwargs)
def __array_ufunc__(
self, ufunc: Any, method: str, *inputs: Any, **kwargs: Any
) -> Any:
from . import _ufunc
# Check whether we should handle the arguments
array_args = inputs
array_args += kwargs.get("out", ())
if (where := kwargs.get("where", True)) is not True:
array_args += (where,)
for arg in array_args:
if not hasattr(arg, "__array_ufunc__"):
continue
t = type(arg)
# Reject arguments we do not know (see __array_function__)
if not issubclass(type(self), t) and t is not np.ndarray:
return NotImplemented
# TODO: The logic below should be moved to a "clone_ufunc" wrapper.
what = f"{ufunc.__name__}.{method}"
if hasattr(_ufunc, ufunc.__name__):
cn_ufunc = getattr(_ufunc, ufunc.__name__)
if hasattr(cn_ufunc, method):
cn_method = getattr(cn_ufunc, method)
# Similar to __array_function__, we need to gracefully fall
# back to NumPy if we can't handle the provided combination of
# arguments.
try:
return cn_method(*inputs, **kwargs)
except NotImplementedError:
what = f"the requested combination of arguments to {what}"
# We cannot handle this ufunc call, so we will fall back to NumPy.
warnings.warn(
FALLBACK_WARNING.format(what=what),
category=RuntimeWarning,
stacklevel=3,
)
inputs = deep_apply(inputs, maybe_convert_to_np_ndarray)
kwargs = deep_apply(kwargs, maybe_convert_to_np_ndarray)
return getattr(ufunc, method)(*inputs, **kwargs)
@property
def T(self) -> ndarray:
"""
The transposed array.
Same as ``self.transpose()``.
See Also
--------
cunumeric.transpose
ndarray.transpose
"""
return self.transpose()
@property
def base(self) -> Union[npt.NDArray[Any], None]:
"""
Returns dtype for the base element of the subarrays,
regardless of their dimension or shape.
See Also
--------
numpy.dtype.subdtype
"""
return self.__array__().base
@property
def data(self) -> memoryview:
"""
Python buffer object pointing to the start of the array's data.
"""
return self.__array__().data
@property
def dtype(self) -> np.dtype[Any]:
"""
Data-type of the array's elements.
See Also
--------
astype : Cast the values contained in the array to a new data-type.
view : Create a view of the same data but a different data-type.
numpy.dtype
"""
return self._thunk.dtype
@property
def flags(self) -> Any:
"""
Information about the memory layout of the array.
These flags don't reflect the properties of the cuNumeric array, but
rather the NumPy array that will be produced if the cuNumeric array is
materialized on a single node.
Attributes
----------
C_CONTIGUOUS (C)
The data is in a single, C-style contiguous segment.
F_CONTIGUOUS (F)
The data is in a single, Fortran-style contiguous segment.
OWNDATA (O)
The array owns the memory it uses or borrows it from another
object.
WRITEABLE (W)
The data area can be written to. Setting this to False locks
the data, making it read-only. A view (slice, etc.) inherits
WRITEABLE from its base array at creation time, but a view of a
writeable array may be subsequently locked while the base array
remains writeable. (The opposite is not true, in that a view of a
locked array may not be made writeable. However, currently,
locking a base object does not lock any views that already
reference it, so under that circumstance it is possible to alter
the contents of a locked array via a previously created writeable
view onto it.) Attempting to change a non-writeable array raises
a RuntimeError exception.
ALIGNED (A)
The data and all elements are aligned appropriately for the
hardware.
WRITEBACKIFCOPY (X)
This array is a copy of some other array. The C-API function
PyArray_ResolveWritebackIfCopy must be called before deallocating
to the base array will be updated with the contents of this array.
FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
BEHAVED (B)
ALIGNED and WRITEABLE.
CARRAY (CA)
BEHAVED and C_CONTIGUOUS.
FARRAY (FA)
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
Notes
-----
The `flags` object can be accessed dictionary-like (as in
``a.flags['WRITEABLE']``), or by using lowercased attribute names (as
in ``a.flags.writeable``). Short flag names are only supported in
dictionary access.
Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
changed by the user, via direct assignment to the attribute or
dictionary entry, or by calling `ndarray.setflags`.
The array flags cannot be set arbitrarily:
- WRITEBACKIFCOPY can only be set ``False``.
- ALIGNED can only be set ``True`` if the data is truly aligned.
- WRITEABLE can only be set ``True`` if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer
interface or is a string.
Arrays can be both C-style and Fortran-style contiguous
simultaneously. This is clear for 1-dimensional arrays, but can also
be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension
``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
or the array has no elements.
It does not generally hold that ``self.strides[-1] == self.itemsize``
for C-style contiguous arrays or ``self.strides[0] == self.itemsize``
for Fortran-style contiguous arrays is true.
"""
return flagsobj(self)
@property
def flat(self) -> np.flatiter[npt.NDArray[Any]]:
"""
A 1-D iterator over the array.
See Also
--------
flatten : Return a copy of the array collapsed into one dimension.
Availability
--------
Single CPU
"""
return self.__array__().flat
@property
def imag(self) -> ndarray:
"""
The imaginary part of the array.
"""
if self.dtype.kind == "c":
return ndarray(shape=self.shape, thunk=self._thunk.imag())
else:
result = ndarray(self.shape, self.dtype)
result.fill(0)
return result
@property
def ndim(self) -> int:
"""
Number of array dimensions.
"""
return self._thunk.ndim
@property
def real(self) -> ndarray:
"""
The real part of the array.
"""
if self.dtype.kind == "c":
return ndarray(shape=self.shape, thunk=self._thunk.real())
else:
return self
@property
def shape(self) -> NdShape:
"""
Tuple of array dimensions.
See Also
--------
shape : Equivalent getter function.
reshape : Function forsetting ``shape``.
ndarray.reshape : Method for setting ``shape``.
"""
return self._thunk.shape
@property
def size(self) -> int:
"""
Number of elements in the array.
Equal to ``np.prod(a.shape)``, i.e., the product of the array's
dimensions.
Notes
-----
`a.size` returns a standard arbitrary precision Python integer. This
may not be the case with other methods of obtaining the same value
(like the suggested ``np.prod(a.shape)``, which returns an instance
of ``np.int_``), and may be relevant if the value is used further in
calculations that may overflow a fixed size integer type.
"""
s = 1
if self.ndim == 0:
return s
for p in self.shape:
s *= p
return s
@property
def itemsize(self) -> int:
"""
The element size of this data-type object.
For 18 of the 21 types this number is fixed by the data-type.
For the flexible data-types, this number can be anything.
"""
return self._thunk.dtype.itemsize
@property
def nbytes(self) -> int:
"""
Total bytes consumed by the elements of the array.
Notes
-----
Does not include memory consumed by non-element attributes of the
array object.
"""
return self.itemsize * self.size
@property
def strides(self) -> tuple[int, ...]:
"""
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array
`a` is::
offset = sum(np.array(i) * a.strides)
A more detailed explanation of strides can be found in the
"ndarray.rst" file in the NumPy reference guide.
Notes
-----
Imagine an array of 32-bit integers (each 4 bytes)::
x = np.array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other
(known as a contiguous block of memory). The strides of an array tell
us how many bytes we have to skip in memory to move to the next
position along a certain axis. For example, we have to skip 4 bytes
(1 value) to move to the next column, but 20 bytes (5 values) to get
to the same position in the next row. As such, the strides for the
array `x` will be ``(20, 4)``.
"""
return self.__array__().strides
@property
def ctypes(self) -> Any:
"""
An object to simplify the interaction of the array with the ctypes
module.
This attribute creates an object that makes it easier to use arrays
when calling shared libraries with the ctypes module. The returned
object has, among others, data, shape, and strides attributes (see
:external+numpy:attr:`numpy.ndarray.ctypes` for details) which
themselves return ctypes objects that can be used as arguments to a
shared library.
Parameters
----------
None
Returns
-------
c : object
Possessing attributes data, shape, strides, etc.
"""
return self.__array__().ctypes
# Methods for ndarray
def __abs__(self) -> ndarray:
"""a.__abs__(/)
Return ``abs(self)``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
# Handle the nice case of it being unsigned
from ._ufunc import absolute
return absolute(self)
def __add__(self, rhs: Any) -> ndarray:
"""a.__add__(value, /)
Return ``self+value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
from ._ufunc import add
return add(self, rhs)
def __and__(self, rhs: Any) -> ndarray:
"""a.__and__(value, /)
Return ``self&value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
from ._ufunc import bitwise_and
return bitwise_and(self, rhs)
def __array__(
self, dtype: Union[np.dtype[Any], None] = None
) -> npt.NDArray[Any]:
"""a.__array__([dtype], /)
Returns either a new reference to self if dtype is not given or a new
array of provided data type if dtype is different from the current
dtype of the array.
"""
numpy_array = self._thunk.__numpy_array__()
if numpy_array.flags.writeable and not self._writeable:
numpy_array.flags.writeable = False
if dtype is not None:
numpy_array = numpy_array.astype(dtype)
return numpy_array
# def __array_prepare__(self, *args, **kwargs):
# return self.__array__().__array_prepare__(*args, **kwargs)
# def __array_wrap__(self, *args, **kwargs):
# return self.__array__().__array_wrap__(*args, **kwargs)
def __bool__(self) -> bool:
"""a.__bool__(/)
Return ``self!=0``
"""
return bool(self.__array__())
def __complex__(self) -> complex:
"""a.__complex__(/)"""
return complex(self.__array__())
def __contains__(self, item: Any) -> ndarray:
"""a.__contains__(key, /)
Return ``key in self``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if isinstance(item, np.ndarray):
args = (item.astype(self.dtype),)
else: # Otherwise convert it to a scalar numpy array of our type
args = (np.array(item, dtype=self.dtype),)
if args[0].size != 1:
raise ValueError("contains needs scalar item")
return self._perform_unary_reduction(
UnaryRedCode.CONTAINS,
self,
axis=None,
res_dtype=bool,
args=args,
)
def __copy__(self) -> ndarray:
"""a.__copy__()
Used if :func:`copy.copy` is called on an array. Returns a copy
of the array.
Equivalent to ``a.copy(order='K')``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
result = ndarray(self.shape, self.dtype, inputs=(self,))
result._thunk.copy(self._thunk, deep=False)
return result
def __deepcopy__(self, memo: Union[Any, None] = None) -> ndarray:
"""a.__deepcopy__(memo, /)
Deep copy of array.
Used if :func:`copy.deepcopy` is called on an array.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
result = ndarray(self.shape, self.dtype, inputs=(self,))
result._thunk.copy(self._thunk, deep=True)
return result
def __div__(self, rhs: Any) -> ndarray:
"""a.__div__(value, /)
Return ``self/value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
return self.__truediv__(rhs)
def __divmod__(self, rhs: Any) -> ndarray:
"""a.__divmod__(value, /)
Return ``divmod(self, value)``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
raise NotImplementedError(
"cunumeric.ndarray doesn't support __divmod__ yet"
)
def __eq__(self, rhs: object) -> ndarray: # type: ignore [override]
"""a.__eq__(value, /)
Return ``self==value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
from ._ufunc import equal
return equal(self, rhs)
def __float__(self) -> float:
"""a.__float__(/)
Return ``float(self)``.
"""
return float(self.__array__())
def __floordiv__(self, rhs: Any) -> ndarray:
"""a.__floordiv__(value, /)
Return ``self//value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
from ._ufunc import floor_divide
return floor_divide(self, rhs)
def __format__(self, *args: Any, **kwargs: Any) -> str:
return self.__array__().__format__(*args, **kwargs)
def __ge__(self, rhs: Any) -> ndarray:
"""a.__ge__(value, /)
Return ``self>=value``.
Availability
--------
Multiple GPUs, Multiple CPUs
"""
from ._ufunc import greater_equal
return greater_equal(self, rhs)
# __getattribute__