-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy patharray_object.py
More file actions
1105 lines (885 loc) · 37.7 KB
/
array_object.py
File metadata and controls
1105 lines (885 loc) · 37.7 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
from __future__ import annotations
import array as py_array
import ctypes
import enum
import warnings
from dataclasses import dataclass
from typing import Any, List, Optional, Tuple, Union
# TODO replace imports from original lib with refactored ones
from arrayfire import backend, safe_call
from arrayfire.algorithm import count
from arrayfire.array import _get_indices, _in_display_dims_limit
from .device import PointerSource
from .dtypes import CShape, Dtype
from .dtypes import bool as af_bool
from .dtypes import c_dim_t
from .dtypes import complex64 as af_complex64
from .dtypes import complex128 as af_complex128
from .dtypes import float32 as af_float32
from .dtypes import float64 as af_float64
from .dtypes import int64 as af_int64
from .dtypes import supported_dtypes
from .dtypes import uint64 as af_uint64
ShapeType = Tuple[int, ...]
# HACK, TODO replace for actual bcast_var after refactoring ~ https://github.com/arrayfire/arrayfire/pull/2871
_bcast_var = False
# TODO use int | float in operators -> remove bool | complex support
@dataclass
class _ArrayBuffer:
address: Optional[int] = None
length: int = 0
class Array:
def __init__(
self, x: Union[None, Array, py_array.array, int, ctypes.c_void_p, List[Union[int, float]]] = None,
dtype: Union[None, Dtype, str] = None, shape: Optional[ShapeType] = None,
pointer_source: PointerSource = PointerSource.host, offset: Optional[ctypes._SimpleCData[int]] = None,
strides: Optional[ShapeType] = None) -> None:
_no_initial_dtype = False # HACK, FIXME
warnings.warn(
"Initialisation with __init__ constructor is not a part of array-api specification"
" and about to be replaced with asarray() method.",
DeprecationWarning, stacklevel=2)
# Initialise array object
self.arr = ctypes.c_void_p(0)
if isinstance(dtype, str):
dtype = _str_to_dtype(dtype) # type: ignore[arg-type]
if dtype is None:
_no_initial_dtype = True
dtype = af_float32
if x is None:
if not shape: # shape is None or empty tuple
safe_call(backend.get().af_create_handle(
ctypes.pointer(self.arr), 0, ctypes.pointer(CShape().c_array), dtype.c_api_value))
return
# NOTE: applies inplace changes for self.arr
safe_call(backend.get().af_create_handle(
ctypes.pointer(self.arr), len(shape), ctypes.pointer(CShape(*shape).c_array), dtype.c_api_value))
return
if isinstance(x, Array):
safe_call(backend.get().af_retain_array(ctypes.pointer(self.arr), x.arr))
return
if isinstance(x, py_array.array):
_type_char = x.typecode
_array_buffer = _ArrayBuffer(*x.buffer_info())
elif isinstance(x, list):
_array = py_array.array("f", x) # BUG [True, False] -> dtype: f32 # TODO add int and float
_type_char = _array.typecode
_array_buffer = _ArrayBuffer(*_array.buffer_info())
elif isinstance(x, int) or isinstance(x, ctypes.c_void_p): # TODO
_array_buffer = _ArrayBuffer(x if not isinstance(x, ctypes.c_void_p) else x.value)
if not shape:
raise TypeError("Expected to receive the initial shape due to the x being a data pointer.")
if _no_initial_dtype:
raise TypeError("Expected to receive the initial dtype due to the x being a data pointer.")
_type_char = dtype.typecode # type: ignore[assignment] # FIXME
else:
raise TypeError("Passed object x is an object of unsupported class.")
_cshape = _get_cshape(shape, _array_buffer.length)
if not _no_initial_dtype and dtype.typecode != _type_char:
raise TypeError("Can not create array of requested type from input data type")
if not (offset or strides):
if pointer_source == PointerSource.host:
safe_call(backend.get().af_create_array(
ctypes.pointer(self.arr), ctypes.c_void_p(_array_buffer.address), _cshape.original_shape,
ctypes.pointer(_cshape.c_array), dtype.c_api_value))
return
safe_call(backend.get().af_device_array(
ctypes.pointer(self.arr), ctypes.c_void_p(_array_buffer.address), _cshape.original_shape,
ctypes.pointer(_cshape.c_array), dtype.c_api_value))
return
if offset is None:
offset = c_dim_t(0)
if strides is None:
strides = (1, _cshape[0], _cshape[0]*_cshape[1], _cshape[0]*_cshape[1]*_cshape[2])
if len(strides) < 4:
strides += (strides[-1], ) * (4 - len(strides))
strides_cshape = CShape(*strides).c_array
safe_call(backend.get().af_create_strided_array(
ctypes.pointer(self.arr), ctypes.c_void_p(_array_buffer.address), offset, _cshape.original_shape,
ctypes.pointer(_cshape.c_array), ctypes.pointer(strides_cshape), dtype.c_api_value,
pointer_source.value))
# Arithmetic Operators
def __pos__(self) -> Array:
"""
Evaluates +self_i for each element of an array instance.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
Returns
-------
out : Array
An array containing the evaluated result for each element. The returned array must have the same data type
as self.
"""
return self
def __neg__(self) -> Array:
"""
Evaluates +self_i for each element of an array instance.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
Returns
-------
out : Array
An array containing the evaluated result for each element in self. The returned array must have a data type
determined by Type Promotion Rules.
"""
return 0 - self # type: ignore[no-any-return, operator] # FIXME
def __add__(self, other: Union[int, float, Array], /) -> Array:
"""
Calculates the sum for each element of an array instance with the respective element of the array other.
Parameters
----------
self : Array
Array instance (augend array). Should have a numeric data type.
other: Union[int, float, Array]
Addend array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise sums. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_add)
def __sub__(self, other: Union[int, float, Array], /) -> Array:
"""
Calculates the difference for each element of an array instance with the respective element of the array other.
The result of self_i - other_i must be the same as self_i + (-other_i) and must be governed by the same
floating-point rules as addition (see array.__add__()).
Parameters
----------
self : Array
Array instance (minuend array). Should have a numeric data type.
other: Union[int, float, Array]
Subtrahend array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise differences. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_sub)
def __mul__(self, other: Union[int, float, Array], /) -> Array:
"""
Calculates the product for each element of an array instance with the respective element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise products. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_mul)
def __truediv__(self, other: Union[int, float, Array], /) -> Array:
"""
Evaluates self_i / other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array should have a floating-point data type
determined by Type Promotion Rules.
Note
----
- If one or both of self and other have integer data types, the result is implementation-dependent, as type
promotion between data type “kinds” (e.g., integer versus floating-point) is unspecified.
Specification-compliant libraries may choose to raise an error or return an array containing the element-wise
results. If an array is returned, the array must have a real-valued floating-point data type.
"""
return _process_c_function(self, other, backend.get().af_div)
def __floordiv__(self, other: Union[int, float, Array], /) -> Array:
# TODO
return NotImplemented
def __mod__(self, other: Union[int, float, Array], /) -> Array:
"""
Evaluates self_i % other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a real-valued data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a real-valued data type.
Returns
-------
out : Array
An array containing the element-wise results. Each element-wise result must have the same sign as the
respective element other_i. The returned array must have a real-valued floating-point data type determined
by Type Promotion Rules.
Note
----
- For input arrays which promote to an integer data type, the result of division by zero is unspecified and
thus implementation-defined.
"""
return _process_c_function(self, other, backend.get().af_mod)
def __pow__(self, other: Union[int, float, Array], /) -> Array:
"""
Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of
an array instance to the power of other_i (the exponent), where other_i is the corresponding element of the
array other.
Parameters
----------
self : Array
Array instance whose elements correspond to the exponentiation base. Should have a numeric data type.
other: Union[int, float, Array]
Other array whose elements correspond to the exponentiation exponent. Must be compatible with self
(see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_pow)
# Array Operators
def __matmul__(self, other: Array, /) -> Array:
# TODO get from blas - make vanilla version and not copy af.matmul as is
return NotImplemented
# Bitwise Operators
def __invert__(self) -> Array:
"""
Evaluates ~self_i for each element of an array instance.
Parameters
----------
self : Array
Array instance. Should have an integer or boolean data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have the same data type as self.
"""
out = Array()
safe_call(backend.get().af_bitnot(ctypes.pointer(out.arr), self.arr))
return out
def __and__(self, other: Union[int, bool, Array], /) -> Array:
"""
Evaluates self_i & other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, bool, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_bitand)
def __or__(self, other: Union[int, bool, Array], /) -> Array:
"""
Evaluates self_i | other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, bool, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_bitor)
def __xor__(self, other: Union[int, bool, Array], /) -> Array:
"""
Evaluates self_i ^ other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, bool, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type determined
by Type Promotion Rules.
"""
return _process_c_function(self, other, backend.get().af_bitxor)
def __lshift__(self, other: Union[int, Array], /) -> Array:
"""
Evaluates self_i << other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Each element must be greater than or equal to 0.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have the same data type as self.
"""
return _process_c_function(self, other, backend.get().af_bitshiftl)
def __rshift__(self, other: Union[int, Array], /) -> Array:
"""
Evaluates self_i >> other_i for each element of an array instance with the respective element of the
array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a numeric data type.
Each element must be greater than or equal to 0.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have the same data type as self.
"""
return _process_c_function(self, other, backend.get().af_bitshiftr)
# Comparison Operators
def __lt__(self, other: Union[int, float, Array], /) -> Array:
"""
Computes the truth value of self_i < other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a real-valued data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_lt)
def __le__(self, other: Union[int, float, Array], /) -> Array:
"""
Computes the truth value of self_i <= other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a real-valued data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_le)
def __gt__(self, other: Union[int, float, Array], /) -> Array:
"""
Computes the truth value of self_i > other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a real-valued data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_gt)
def __ge__(self, other: Union[int, float, Array], /) -> Array:
"""
Computes the truth value of self_i >= other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, Array]
Other array. Must be compatible with self (see Broadcasting). Should have a real-valued data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_ge)
def __eq__(self, other: Union[int, float, bool, Array], /) -> Array: # type: ignore[override] # FIXME
"""
Computes the truth value of self_i == other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, bool, Array]
Other array. Must be compatible with self (see Broadcasting). May have any data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_eq)
def __ne__(self, other: Union[int, float, bool, Array], /) -> Array: # type: ignore[override] # FIXME
"""
Computes the truth value of self_i != other_i for each element of an array instance with the respective
element of the array other.
Parameters
----------
self : Array
Array instance. Should have a numeric data type.
other: Union[int, float, bool, Array]
Other array. Must be compatible with self (see Broadcasting). May have any data type.
Returns
-------
out : Array
An array containing the element-wise results. The returned array must have a data type of bool.
"""
return _process_c_function(self, other, backend.get().af_neq)
# Reflected Arithmetic Operators
def __radd__(self, other: Array, /) -> Array:
"""
Return other + self.
"""
return _process_c_function(other, self, backend.get().af_add)
def __rsub__(self, other: Array, /) -> Array:
"""
Return other - self.
"""
return _process_c_function(other, self, backend.get().af_sub)
def __rmul__(self, other: Array, /) -> Array:
"""
Return other * self.
"""
return _process_c_function(other, self, backend.get().af_mul)
def __rtruediv__(self, other: Array, /) -> Array:
"""
Return other / self.
"""
return _process_c_function(other, self, backend.get().af_div)
def __rfloordiv__(self, other: Array, /) -> Array:
# TODO
return NotImplemented
def __rmod__(self, other: Array, /) -> Array:
"""
Return other % self.
"""
return _process_c_function(other, self, backend.get().af_mod)
def __rpow__(self, other: Array, /) -> Array:
"""
Return other ** self.
"""
return _process_c_function(other, self, backend.get().af_pow)
# Reflected Array Operators
def __rmatmul__(self, other: Array, /) -> Array:
# TODO
return NotImplemented
# Reflected Bitwise Operators
def __rand__(self, other: Array, /) -> Array:
"""
Return other & self.
"""
return _process_c_function(other, self, backend.get().af_bitand)
def __ror__(self, other: Array, /) -> Array:
"""
Return other | self.
"""
return _process_c_function(other, self, backend.get().af_bitor)
def __rxor__(self, other: Array, /) -> Array:
"""
Return other ^ self.
"""
return _process_c_function(other, self, backend.get().af_bitxor)
def __rlshift__(self, other: Array, /) -> Array:
"""
Return other << self.
"""
return _process_c_function(other, self, backend.get().af_bitshiftl)
def __rrshift__(self, other: Array, /) -> Array:
"""
Return other >> self.
"""
return _process_c_function(other, self, backend.get().af_bitshiftr)
# In-place Arithmetic Operators
def __iadd__(self, other: Union[int, float, Array], /) -> Array:
# TODO discuss either we need to support complex and bool as other input type
"""
Return self += other.
"""
return _process_c_function(self, other, backend.get().af_add)
def __isub__(self, other: Union[int, float, Array], /) -> Array:
"""
Return self -= other.
"""
return _process_c_function(self, other, backend.get().af_sub)
def __imul__(self, other: Union[int, float, Array], /) -> Array:
"""
Return self *= other.
"""
return _process_c_function(self, other, backend.get().af_mul)
def __itruediv__(self, other: Union[int, float, Array], /) -> Array:
"""
Return self /= other.
"""
return _process_c_function(self, other, backend.get().af_div)
def __ifloordiv__(self, other: Union[int, float, Array], /) -> Array:
# TODO
return NotImplemented
def __imod__(self, other: Union[int, float, Array], /) -> Array:
"""
Return self %= other.
"""
return _process_c_function(self, other, backend.get().af_mod)
def __ipow__(self, other: Union[int, float, Array], /) -> Array:
"""
Return self **= other.
"""
return _process_c_function(self, other, backend.get().af_pow)
# In-place Array Operators
def __imatmul__(self, other: Array, /) -> Array:
# TODO
return NotImplemented
# In-place Bitwise Operators
def __iand__(self, other: Union[int, bool, Array], /) -> Array:
"""
Return self &= other.
"""
return _process_c_function(self, other, backend.get().af_bitand)
def __ior__(self, other: Union[int, bool, Array], /) -> Array:
"""
Return self |= other.
"""
return _process_c_function(self, other, backend.get().af_bitor)
def __ixor__(self, other: Union[int, bool, Array], /) -> Array:
"""
Return self ^= other.
"""
return _process_c_function(self, other, backend.get().af_bitxor)
def __ilshift__(self, other: Union[int, Array], /) -> Array:
"""
Return self <<= other.
"""
return _process_c_function(self, other, backend.get().af_bitshiftl)
def __irshift__(self, other: Union[int, Array], /) -> Array:
"""
Return self >>= other.
"""
return _process_c_function(self, other, backend.get().af_bitshiftr)
# Methods
def __abs__(self) -> Array:
# TODO
return NotImplemented
def __array_namespace__(self, *, api_version: Optional[str] = None) -> Any:
# TODO
return NotImplemented
def __bool__(self) -> bool:
# TODO consider using scalar() and is_scalar()
return NotImplemented
def __complex__(self) -> complex:
# TODO
return NotImplemented
def __dlpack__(self, *, stream: Union[None, int, Any] = None): # type: ignore[no-untyped-def]
# TODO implementation and expected return type -> PyCapsule
return NotImplemented
def __dlpack_device__(self) -> Tuple[enum.Enum, int]:
# TODO
return NotImplemented
def __float__(self) -> float:
# TODO
return NotImplemented
def __getitem__(self, key: Union[int, slice, Tuple[Union[int, slice, ], ...], Array], /) -> Array:
"""
Returns self[key].
Parameters
----------
self : Array
Array instance.
key : Union[int, slice, Tuple[Union[int, slice, ], ...], Array]
Index key.
Returns
-------
out : Array
An array containing the accessed value(s). The returned array must have the same data type as self.
"""
# TODO
# API Specification - key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array].
# consider using af.span to replace ellipsis during refactoring
out = Array()
ndims = self.ndim
if isinstance(key, Array) and key == af_bool.c_api_value:
ndims = 1
if count(key) == 0:
return out
safe_call(backend.get().af_index_gen(
ctypes.pointer(out.arr), self.arr, c_dim_t(ndims), _get_indices(key).pointer))
return out
def __index__(self) -> int:
# TODO
return NotImplemented
def __int__(self) -> int:
# TODO
return NotImplemented
def __len__(self) -> int:
# NOTE not a part of the array-api spec
return self.shape[0] if self.shape else 0
def __setitem__(
self, key: Union[int, slice, Tuple[Union[int, slice, ], ...], Array],
value: Union[int, float, bool, Array], /) -> None:
# TODO
return NotImplemented # type: ignore[return-value] # FIXME
def __str__(self) -> str:
# NOTE not a part of the array-api spec
# TODO change the look of array str. E.g., like np.array
if not _in_display_dims_limit(self.shape):
return _metadata_string(self.dtype, self.shape)
return _metadata_string(self.dtype) + _array_as_str(self)
def __repr__(self) -> str:
# NOTE not a part of the array-api spec
# return _metadata_string(self.dtype, self.shape)
# TODO change the look of array representation. E.g., like np.array
return _array_as_str(self)
def to_device(self, device: Any, /, *, stream: Union[int, Any] = None) -> Array:
# TODO implementation and change device type from Any to Device
return NotImplemented
# Attributes
@property
def dtype(self) -> Dtype:
"""
Data type of the array elements.
Returns
-------
out : Dtype
Array data type.
"""
out = ctypes.c_int()
safe_call(backend.get().af_get_type(ctypes.pointer(out), self.arr))
return _c_api_value_to_dtype(out.value)
@property
def device(self) -> Any:
# TODO
return NotImplemented
@property
def mT(self) -> Array:
# TODO
return NotImplemented
@property
def T(self) -> Array:
"""
Transpose of the array.
Returns
-------
out : Array
Two-dimensional array whose first and last dimensions (axes) are permuted in reverse order relative to
original array. The returned array must have the same data type as the original array.
Note
----
- The array instance must be two-dimensional. If the array instance is not two-dimensional, an error
should be raised.
"""
if self.ndim < 2:
raise TypeError(f"Array should be at least 2-dimensional. Got {self.ndim}-dimensional array")
# TODO add check if out.dtype == self.dtype
out = Array()
safe_call(backend.get().af_transpose(ctypes.pointer(out.arr), self.arr, False))
return out
@property
def size(self) -> int:
"""
Number of elements in an array.
Returns
-------
out : int
Number of elements in an array
Note
----
- This must equal the product of the array's dimensions.
"""
# NOTE previously - elements()
out = c_dim_t(0)
safe_call(backend.get().af_get_elements(ctypes.pointer(out), self.arr))
return out.value
@property
def ndim(self) -> int:
"""
Number of array dimensions (axes).
out : int
Number of array dimensions (axes).
"""
out = ctypes.c_uint(0)
safe_call(backend.get().af_get_numdims(ctypes.pointer(out), self.arr))
return out.value
@property
def shape(self) -> ShapeType:
"""
Array dimensions.
Returns
-------
out : tuple[int, ...]
Array dimensions.
"""
# TODO refactor
d0 = c_dim_t(0)
d1 = c_dim_t(0)
d2 = c_dim_t(0)
d3 = c_dim_t(0)
safe_call(backend.get().af_get_dims(
ctypes.pointer(d0), ctypes.pointer(d1), ctypes.pointer(d2), ctypes.pointer(d3), self.arr))
return (d0.value, d1.value, d2.value, d3.value)[:self.ndim] # Skip passing None values
def scalar(self) -> Union[None, int, float, bool, complex]:
"""
Return the first element of the array
"""
# NOTE not a part of the array-api spec
# TODO change the logic of this method
if self.is_empty():
return None
out = self.dtype.c_type()
safe_call(backend.get().af_get_scalar(ctypes.pointer(out), self.arr))
return out.value # type: ignore[no-any-return] # FIXME
def is_empty(self) -> bool:
"""
Check if the array is empty i.e. it has no elements.
"""
# NOTE not a part of the array-api spec
out = ctypes.c_bool()
safe_call(backend.get().af_is_empty(ctypes.pointer(out), self.arr))
return out.value
def to_list(self, row_major: bool = False) -> List[Union[None, int, float, bool, complex]]:
# NOTE not a part of the array-api spec
if self.is_empty():
return []
array = _reorder(self) if row_major else self
ctypes_array = _get_ctypes_array(array)
if array.ndim == 1:
return list(ctypes_array)
out = []
for i in range(array.size):
idx = i
sub_list = []
for j in range(array.ndim):
div = array.shape[j]
sub_list.append(idx % div)
idx //= div
out.append(ctypes_array[sub_list[::-1]]) # type: ignore[call-overload] # FIXME
return out
def to_ctype_array(self, row_major: bool = False) -> ctypes.Array:
# NOTE not a part of the array-api spec
if self.is_empty():
raise RuntimeError("Can not convert an empty array to ctype.")
array = _reorder(self) if row_major else self
return _get_ctypes_array(array)
def _get_ctypes_array(array: Array) -> ctypes.Array:
c_shape = array.dtype.c_type * array.size
ctypes_array = c_shape()
safe_call(backend.get().af_get_data_ptr(ctypes.pointer(ctypes_array), array.arr))
return ctypes_array
def _reorder(array: Array) -> Array:
"""
Returns a reordered array to help interoperate with row major formats.
"""
if array.ndim == 1:
return array
out = Array()
c_shape = CShape(*(tuple(reversed(range(array.ndim))) + tuple(range(array.ndim, 4))))
safe_call(backend.get().af_reorder(ctypes.pointer(out.arr), array.arr, *c_shape))
return out
def _array_as_str(array: Array) -> str:
arr_str = ctypes.c_char_p(0)
# FIXME add description to passed arguments
safe_call(backend.get().af_array_to_string(ctypes.pointer(arr_str), "", array.arr, 4, True))
py_str = _to_str(arr_str)
safe_call(backend.get().af_free_host(arr_str))
return py_str
def _metadata_string(dtype: Dtype, dims: Optional[ShapeType] = None) -> str:
return (
"arrayfire.Array()\n"
f"Type: {dtype.typename}\n"
f"Dims: {str(dims) if dims else ''}")
def _get_cshape(shape: Optional[ShapeType], buffer_length: int) -> CShape:
if shape:
return CShape(*shape)