forked from inaos/iron-array-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiarray_container.py
More file actions
2836 lines (2361 loc) · 92.4 KB
/
Copy pathiarray_container.py
File metadata and controls
2836 lines (2361 loc) · 92.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
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 ironArray SL 2021.
#
# All rights reserved.
#
# This software is the confidential and proprietary information of ironArray SL
# ("Confidential Information"). You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of the license agreement.
###########################################################################################
from __future__ import annotations
import iarray as ia
from iarray import iarray_ext as ext
import numpy as np
from typing import (
Any,
Literal,
Optional,
Sequence,
Tuple,
Union,
)
from .dtypes import (
_all_dtypes,
_boolean_dtypes,
_integer_dtypes,
_integer_or_boolean_dtypes,
_floating_dtypes,
_numeric_dtypes,
_dtype_categories,
)
from enum import IntEnum
import ndindex
from .info import InfoReporter
PyCapsule = Any
Device = Literal["cpu"]
class OIndex:
def __init__(self, array):
self.array = array
def __getitem__(self, selection):
return self.array.get_orthogonal_selection(selection)
def __setitem__(self, selection, value):
return self.array.set_orthogonal_selection(selection, value)
def process_selection(selection, shape):
mask = tuple(True if isinstance(s, int) else False for s in selection)
new_selection = []
for s, n in zip(selection, shape):
if isinstance(s, slice):
si = np.array([i for i in range(*s.indices(n))])
elif isinstance(s, int):
si = np.array([s % n])
else:
si = np.array([i % n for i in s])
new_selection.append(si)
return new_selection
def process_key(key, shape):
key = ndindex.ndindex(key).expand(shape).raw
mask = tuple(True if isinstance(k, int) else False for k in key)
key = tuple(k if isinstance(k, slice) else slice(k, k + 1, None) for k in key)
return key, mask
def is_documented_by(original):
def wrapper(target):
target.__doc__ = original.__doc__
return target
return wrapper
# For avoiding a warning in PyCharm in method signatures
IArray = None
class IArray(ext.Container):
"""The ironArray data container.
This is not meant to be called from user space.
"""
@classmethod
def cast(cls, cont):
cont.__class__ = cls
assert isinstance(cont, IArray)
return cont
@property
def info(self):
"""
Print information about this array.
"""
return InfoReporter(self)
@property
def info_items(self):
items = []
items += [("type", self.__class__.__name__)]
items += [("shape", self.shape)]
items += [("chunks", self.chunks)]
items += [("blocks", self.blocks)]
items += [("cratio", f"{self.cratio:.2f}")]
return items
@property
def data(self):
"""
Get a ndarray with array data.
Returns
-------
out: `np.ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`_
"""
return ia.iarray2numpy(self)
@property
def attrs(self):
return ia.Attributes(self)
@property
def oindex(self):
return OIndex(self)
def split(self):
"""Split the array in a list of one-chunk array.
Returns
-------
A list with one-chunk arrays.
"""
with ia.config() as cfg:
return ext.split(cfg, self)
def slice_chunk_index(self, shape: Sequence, chunk_index: list):
"""Slice the array using chunk indexes.
Parameters
----------
shape: Sequence
The shape of the result.
chunk_index: lsit
The indexes of the chunks that will create the slice.
Returns
-------
:ref:`IArray`
A new array containing the chunk that are specified.
"""
with ia.config() as cfg:
return ext.from_chunk_index(cfg, self, shape, chunk_index)
@property
def device(self) -> Device:
"""
Hardware device where the array data resides on.
"""
return "cpu"
@property
def mT(self) -> IArray:
raise NotImplementedError("IArray.mT is not supported yet")
@property
def size(self) -> int:
"""
Number of elements in the array.
"""
return int(np.prod(self.shape))
def _check_allowed_dtypes(
self, value: bool | int | float | IArray, dtype_category: str, op: str
) -> IArray:
if self.dtype not in _dtype_categories[dtype_category]:
raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}")
if isinstance(value, IArray):
if value.dtype not in _dtype_categories[dtype_category]:
raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}")
elif not isinstance(value, (int, float, bool, ia.LazyExpr)):
raise RuntimeError("Expected bool, int, float, LazyExpr or IArray instance")
def copy(self, cfg=None, **kwargs) -> IArray:
"""Return a copy of the array.
Parameters
----------
cfg : :class:`Config`
The configuration for this operation. If None (default), the
configuration from self will be used instead of that of the current configuration.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config`
dataclass that should override the configuration.
By default, this function deactivates btune unless it is specified.
Returns
-------
:ref:`IArray`
The copy.
"""
if cfg is None:
cfg = self.cfg
# the urlpath should not be copied
cfg.urlpath = None
# Generally we don't want btune to optimize, except if specified
btune = False
if "favor" in kwargs and "btune" not in kwargs:
btune = True
if "btune" in kwargs:
btune = kwargs["btune"]
kwargs.pop("btune")
with ia.config(shape=self.shape, cfg=cfg, btune=btune, **kwargs) as cfg:
return ext.copy(cfg, self)
def copyto(self, dest):
"""Copy array contents to `dest`.
Parameters
----------
dest : Any
The destination container. It can be any object that supports
multidimensional assignment (NumPy, Zarr, HDF5...). It should have the same
shape than `self`.
"""
if tuple(dest.shape) != self.shape:
raise IndexError("Incompatible destination shape")
for info, block in self.iter_read_block():
dest[info.slice] = block[:]
def resize(self, newshape, start=None):
"""Change the shape of the array by growing or shrinking one or more dimensions.
Parameters
----------
newshape : tuple or list
The new shape of the array container. It should have the same dimensions
as `self`.
start: tuple, list or None, optional.
The position from where the array will be extended or shrunk according to
:paramref:`newshape`. If given, it should have the same dimensions
as `self`. If None (the default), the appended or deleted chunks will happen
at the end of the array.
Notes
-----
The array values corresponding to the added positions are not initialized.
Thus, the user is in charge of initializing them.
Furthermore, the :paramref:`start` has to fulfill the same conditions than in
:func:`insert`, :func:`append` and :func:`delete`.
See Also
--------
insert
append
delete
"""
ext.resize(self, new_shape=newshape, start=start)
return self.shape
def insert(self, data, axis=0, start=None):
"""Insert data in a position by extending the :paramref:`axis`.
Parameters
----------
data: object supporting the PyBuffer protocol
The object containing the data.
axis: int, optional
The axis along the data contained by :paramref:`data` will be inserted.
Default is 0.
start: int, optional
The position in the array axis from where to start inserting the data.
If None (default), it will be appended at the end.
Notes
-----
If :paramref:`start` is not at the end of the array, it must be a multiple of `chunks[axis]`.
Furthermore, if `start != shape[axis]` the number of elements of :paramref:`data`
must be a multiple of `chunks[axis] * shape[in the other axis]` and
if `start = shape[axis]` (or `None`) the number of elements of :paramref:`data`
must be a multiple of `shape[in the other axis]`.
For example, let’s suppose that we have an array of `shape = [20, 20]` and `chunks = [7,7]`,
and we would like to insert data in the `axis = 0`. Then, if `start = 0`
which is different from `shape[axis]` and multiple of `chunks[axis]`,
the number of elements of :paramref:`data` must be a multiple of `7 * 20`.
If `start = 20 = shape[axis]` (or None), the number of elements of :paramref:`data`
can be `anything * 20`.
See Also
--------
append
delete
resize
"""
if type(data) is np.ndarray:
if data.dtype.itemsize != np.dtype(self.dtype).itemsize:
data = np.array(data, dtype=self.dtype)
elif data.dtype.str[0] == ">":
data = data.byteswap()
ext.insert(self, data, axis, start)
return self.shape
def append(self, data, axis=0):
"""Append data at the end by extending the :paramref:`axis`.
Parameters
----------
data: object supporting the PyBuffer protocol
The object containing the data.
axis: int, optional
Axis along which to append.
Default is 0.
Notes
-----
The number of elements of :paramref:`data` must be a multiple of the array shape in all its axis
excluding the :paramref:`axis`.
For example, let’s suppose that we have an array of `shape = [20, 20]`, and `chunks = [7, 7]`.
Then number of elements of :paramref:`data` can be `anything * 20` and the new shape would be
`[20 + anything, 20]`.
See Also
--------
insert
delete
resize
"""
if type(data) is np.ndarray:
if data.dtype.itemsize != np.dtype(self.dtype).itemsize:
data = np.array(data, dtype=self.dtype)
elif data.dtype.str[0] == ">":
data = data.byteswap()
ext.append(self, data, axis)
return self.shape
def delete(self, delete_len, axis=0, start=None):
"""Delete :paramref:`delete_len` positions along the :paramref:`axis` from the
:paramref:`start`.
Parameters
----------
delete_len: int
The number of elements to delete in the `array.shape[axis]`.
axis: int, optional
The axis that will be shrunk.
Default is 0.
start: int, None, optional
The starting point for deleting the elements. If None (default)
the deleted elements will be at the end of the array.
Notes
-----
If :paramref:`delete_len` is not a multiple of `chunks[axis]`,
:paramref:`start` must be either None or `shape[axis] - delete_len` (which are equivalent).
Otherwise, :paramref:`start` must also be a multiple of `chunks[axis]`.
For example, let’s suppose that we have an array with `shape = [20, 20]` and `chunks = [7, 7]`.
If `delete_len = 5` and `axis = 0`, because :paramref:`delete_len`
is not a multiple of `chunks[axis]`, :paramref:`start`
must be `None` or `shape[axis] - delete_len = 15`. In both cases, the deleted elements
will be the same (those at the end) and the new shape will be `[15, 20]`.
If we would like to delete some elements
in the middle of the array, :paramref:`start` and :paramref:`delete_len` both must be a multiple
of `chunks[axis]`. So the only possibilities is this particular case would be
`start = 0` and `delete_len = 7` or `delete_len = 14` which would give an array with
shape `[13, 20]` or `[6, 20]`. Or `start = 7` and
`delete_len = 7` which would give an array with shape `[13, 20]`.
See Also
--------
resize
insert
append
"""
ext.delete(self, axis=axis, start=start, delete_len=delete_len)
return self.shape
def iter_read_block(self, iterblock: tuple = None):
if iterblock is None:
if self.chunks is not None:
iterblock = self.chunks
else:
iterblock, _ = ia.partition_advice(self.shape)
return ext.ReadBlockIter(self, iterblock)
def iter_write_block(self, iterblock=None):
if iterblock is None:
if self.chunks:
iterblock = self.chunks
else:
iterblock, _ = ia.partition_advice(self.shape)
return ext.WriteBlockIter(self, iterblock)
def __getitem__(
self, key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], IArray], /
) -> IArray:
if key == () and self.ndim == 0:
return self.data[()]
if isinstance(key, ia.LazyExpr):
return key.update_expr(new_op=(self, f"[]", key))
# Massage the key a bit so that it is compatible with self.shape
key, mask = process_key(key, self.shape)
start = [sl.start for sl in key]
stop = [sl.stop for sl in key]
return super().__getitem__([start, stop, mask])
def __setitem__(
self,
key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], IArray],
value: Union[int, float, bool, IArray],
/,
) -> None:
key, mask = process_key(key, self.shape)
start = [sl.start for sl in key]
stop = [sl.stop for sl in key]
shape = [sp - st for sp, st in zip(stop, start)]
if isinstance(value, (float, int, bool)):
value = np.full(shape, value, dtype=self.dtype)
elif isinstance(value, ia.IArray):
if self.np_dtype is None:
value = value.data
else:
value = value.data
value = value.astype(dtype=self.dtype)
elif self.np_dtype is not None:
value = np.full(shape, value, dtype=self.dtype)
with ia.config(cfg=self.cfg) as cfg:
ext.set_slice(cfg, self, start, stop, value)
def set_orthogonal_selection(self, selection, value):
"""Modify data via a selection for each dimension of the array.
Parameters
----------
selection: int, slice or integer array.
The selection for each dimension of the array.
value: value or `np.ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`_.
Value to be stored into the array.
Returns
-------
None
Notes
-----
This function can also be replaced by `self.oindex[selection]`.
See Also
--------
get_orthogonal_selection
"""
selection = process_selection(selection, self.shape)
if type(value) == list:
value = np.array(value)
elif isinstance(value, (int, float)):
shape = [len(s) for s in selection]
value = np.full(shape, value, self.dtype)
with ia.config(cfg=self.cfg) as cfg:
return ext.set_orthogonal_selection(cfg, self, selection, value)
def get_orthogonal_selection(self, selection):
"""Retrieve data by making a selection for each dimension of the array.
Parameters
----------
selection: list
The selection for each dimension. It can be either
an integer (indexing a single item), a slice or an array of integers.
Returns
-------
out: `np.ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`_
Notes
-----
This function can also be replaced by `self.oindex[selection]`.
See Also
--------
set_orthogonal_selection
"""
selection = process_selection(selection, self.shape)
shape = tuple(len(s) for s in selection)
with ia.config(cfg=self.cfg) as cfg:
dst = np.ones(shape, dtype=self.dtype)
return ext.get_orthogonal_selection(cfg, self, dst, selection)
def __iter__(self):
return self.iter_read_block()
def __str__(self):
return f"<IArray {self.shape} np.{str(np.dtype(self.dtype))}>"
def __repr__(self):
return str(self)
def __matmul__(self, value: IArray, /) -> IArray:
self._check_allowed_dtypes(value, "numeric", "__matmul__")
a = self
return ia.matmul(a, value)
def __rmatmul__(self, value: IArray, /) -> IArray:
self._check_allowed_dtypes(value, "numeric", "__rmatmul__")
a = self
return ia.matmul(value, a)
def __add__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__add__")
return ia.LazyExpr(new_op=(self, "+", value))
def __radd__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__radd__")
return ia.LazyExpr(new_op=(value, "+", self))
def __iadd__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__iadd__ is not supported yet")
def __sub__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__sub__")
return ia.LazyExpr(new_op=(self, "-", value))
def __rsub__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__rsub__")
return ia.LazyExpr(new_op=(value, "-", self))
def __isub__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__isub__ is not supported yet")
def __array_namespace__(self, *, api_version: Optional[str] = None) -> Any:
if api_version is not None and not api_version.startswith("2021."):
raise ValueError(f"Unrecognized array API version: {api_version!r}")
return ia
def __mul__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__mul__")
return ia.LazyExpr(new_op=(self, "*", value))
def __rmul__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__rmul__")
return ia.LazyExpr(new_op=(value, "*", self))
def __imul__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__imul__ is not supported yet")
def __truediv__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__truediv__")
return ia.LazyExpr(new_op=(self, "/", value))
def __rtruediv__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__rtruediv__")
return ia.LazyExpr(new_op=(value, "/", self))
def __itruediv__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__itruediv__ is not supported yet")
def __lt__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__lt__")
return ia.LazyExpr(new_op=(self, "<", value))
def __le__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__le__")
return ia.LazyExpr(new_op=(self, "<=", value))
def __gt__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__gt__")
return ia.LazyExpr(new_op=(self, ">", value))
def __ge__(self, value: Union[int, float, IArray], /):
self._check_allowed_dtypes(value, "numeric", "__ge__")
return ia.LazyExpr(new_op=(self, ">=", value))
def __eq__(self, value: Union[int, float, bool, IArray], /):
self._check_allowed_dtypes(value, "all", "__eq__")
if ia._disable_overloaded_equal:
return self is value
return ia.LazyExpr(new_op=(self, "==", value))
def __ne__(self, value: Union[int, float, bool, IArray], /):
self._check_allowed_dtypes(value, "all", "__ne__")
return ia.LazyExpr(new_op=(self, "!=", value))
def __pos__(self) -> IArray:
if self.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in __pos__")
return self.copy()
# def __array_function__(self, func, types, args, kwargs):
# if not all(issubclass(t, np.ndarray) for t in types):
# # Defer to any non-subclasses that implement __array_function__
# return NotImplemented
#
# # Use NumPy's private implementation without __array_function__
# # dispatching
# return func._implementation(*args, **kwargs)
# def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
# print("method:", method)
@property
def T(self):
"""
Transpose of the array.
See :meth:`transpose`.
"""
return self.transpose()
def transpose(self, **kwargs):
"""Transpose the array.
Parameters
----------
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config`
dataclass that should override the current configuration.
Returns
-------
:ref:`IArray`
The transposed array.
"""
return ia.matrix_transpose(self, **kwargs)
def __abs__(self):
"""
Absolute value, element-wise.
See :func:`abs`.
"""
if self.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in __abs__")
return ia.LazyExpr(new_op=(self, "abs", None))
def __neg__(self):
"""
Numerical negative, element-wise.
See :func:`negative`.
"""
if self.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in __neg__")
return ia.LazyExpr(new_op=(self, "negate", None))
def __pow__(self, iarr2: Union[int, float, IArray], /):
"""
First array elements raised to powers from second array, element-wise.
See :func:`pow`.
"""
self._check_allowed_dtypes(iarr2, "numeric", "__pow__")
return ia.LazyExpr(new_op=(self, "pow", iarr2))
def __rpow__(self, iarr2: Union[int, float, IArray], /):
self._check_allowed_dtypes(iarr2, "numeric", "__pow__")
return ia.LazyExpr(new_op=(iarr2, "pow", self))
@attrs.setter
def attrs(self, value):
self._attrs = value
# Not supported methods
def __and__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__and__ is not supported yet")
def __rand__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__rand__ is not supported yet")
def __iand__(self, value: Union[int, bool, IArray], /):
raise NotImplementedError("self.__iand__ is not supported yet")
def __bool__(self) -> bool:
if self.ndim != 0:
raise AttributeError(
"Cannot convert a non zero dimensional array into a Python scalar"
)
return bool(self.data)
def __dlpack__(self, *, stream: Optional[Union[int, Any]] = None) -> PyCapsule:
raise NotImplementedError("DLPack is not supported yet")
def __dlpack_device__(self: IArray, /) -> Tuple[IntEnum, int]:
raise NotImplementedError("DLPack is not supported yet")
def __float__(self) -> float:
if self.ndim != 0:
raise AttributeError(
"Cannot convert a non zero dimensional array into a Python scalar"
)
return float(self.data)
def __floordiv__(self, value: Union[int, float, IArray], /) -> IArray:
raise NotImplementedError("self.__floordiv__ is not supported yet")
def __rfloordiv__(self, value: Union[int, float, IArray], /) -> IArray:
raise NotImplementedError("self.__rfloordiv__ is not supported yet")
def __ifloordiv__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__ifloordiv__ is not supported yet")
def __index__(self) -> int:
return self.__int__()
def __int__(self) -> int:
if self.ndim != 0:
raise AttributeError(
"Cannot convert a non zero dimensional array into a Python scalar"
)
return int(self.data)
def __invert__(self) -> IArray:
raise NotImplementedError("self.__invert__ is not supported yet")
def __lshift__(self, value: Union[int, IArray], /) -> IArray:
raise NotImplementedError("self.__lshift__ is not supported yet")
def __rlshift__(self, value: Union[int, IArray], /) -> IArray:
raise NotImplementedError("self.__rlshift__ is not supported yet")
def __ilshift__(self, value: Union[int, IArray], /):
raise NotImplementedError("self.__ilshift__ is not supported yet")
def __mod__(self, value: Union[int, float, IArray], /) -> IArray:
raise NotImplementedError("self.__mod__ is not supported yet")
def __rmod__(self, value: Union[int, float, IArray], /) -> IArray:
raise NotImplementedError("self.__rmod__ is not supported yet")
def __imod__(self, value: Union[int, float, IArray], /):
raise NotImplementedError("self.__imod__ is not supported yet")
def __or__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__or__ is not supported yet")
def __ror__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__ror__ is not supported yet")
def __ior__(self, value: Union[int, bool, IArray], /):
raise NotImplementedError("self.__ior__ is not supported yet")
def __rshift__(self, value: Union[int, IArray], /) -> IArray:
raise NotImplementedError("self.__rshift__ is not supported yet")
def __rrshift__(self, value: Union[int, IArray], /) -> IArray:
raise NotImplementedError("self.__rrshift__ is not supported yet")
def __irshift__(self, value: Union[int, IArray], /):
raise NotImplementedError("self.__irshift__ is not supported yet")
def __xor__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__xor__ is not supported yet")
def __rxor__(self, value: Union[int, bool, IArray], /) -> IArray:
raise NotImplementedError("self.__rxor__ is not supported yet")
def __ixor__(self, value: Union[int, bool, IArray], /):
raise NotImplementedError("self.__ixor__ is not supported yet")
def to_device(self, device: device, /, *, stream: Optional[Union[int, Any]] = None) -> IArray:
raise NotImplementedError("self.to_device is not supported yet")
def astype(x: IArray, view_dtype, /, *, copy: bool = False) -> IArray:
"""
Cast the array into a view of a specified type.
Parameters
----------
x: :ref:`IArray`
The array to cast.
view_dtype: (float64, float32, int64, int32, int16, int8, uint64, uint32, uint16,
uint8, bool)
The dtype in which the array will be casted. Only upcasting is supported
unless :paramref:`copy` is `True`.
copy: bool
Whether to copy the array or do a view instead. Default is False.
Returns
-------
:ref:`IArray`
The new view or array as a normal :ref:`IArray`.
"""
if copy:
return x.copy(dtype=view_dtype)
view_dtypesize = np.dtype(view_dtype).itemsize
src_dtypesize = np.dtype(x.dtype).itemsize
if view_dtypesize < src_dtypesize:
raise OverflowError("`view_dtype` itemsize must be greater or equal than `self.dtype`")
return ext.get_type_view(x.cfg, x, view_dtype)
def abs(iarr: IArray, /):
"""
Absolute value, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Input array. Should have a numeric data type.
Returns
-------
abs: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the
absolute value of each element in :paramref:`iarr`.
References
----------
`np.absolute <https://numpy.org/doc/stable/reference/generated/numpy.absolute.html>`_
"""
return iarr.__abs__()
def acos(iarr: IArray, /):
"""
Trigonometric inverse cosine, element-wise.
The inverse of :py:obj:`cos` so that, if :math:`y = \\cos(x)`, then :math:`x = \\arccos(y)`.
Parameters
----------
iarr: :ref:`IArray`
x-coordinate on the unit circle. For real arguments, the domain is :math:`\\left [ -1, 1 \\right]`.
Should have a floating-point data type.
Returns
-------
angle: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the
angle of the ray intersecting the unit circle at the given x-coordinate in radians
:math:`[0, \\pi]`.
Notes
-----
:py:obj:`acos` is a multivalued function: for each :math:`x` there are infinitely many numbers :math:`z`
such that :math:`\\cos(z) = x`. The convention is to return the angle :math:`z` whose real part lies in
:math:`\\left [ 0, \\pi \\right]`.
References
----------
`np.acos <https://numpy.org/doc/stable/reference/generated/numpy.acos.html>`_
"""
if iarr.dtype not in _floating_dtypes:
raise TypeError("Only floating dtypes are allowed in acos")
return ia.LazyExpr(new_op=(iarr, "acos", None))
def add(iarr1: IArray, iarr2: IArray, /):
"""
Add arguments element-wise.
Parameters
----------
iarr1: :ref:`IArray`
First input array. Should have a numeric data type.
iarr2: :ref:`IArray`
Second input array. Should have a numeric data type.
Returns
-------
add: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute
the sum of :paramref:`iarr1` and :paramref:`iarr2`, element-wise.
"""
return iarr1 + iarr2
def asin(iarr: IArray, /):
"""
Trigonometric inverse sine, element-wise.
The inverse of :py:obj:`sin` so that, if :math:`y = \\sin(x)`, then :math:`x = \\arcsin(y)`.
Parameters
----------
iarr: :ref:`IArray`
y-coordinate on the unit circle. Should have a floating-point data type.
Returns
-------
angle: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the inverse
sine of each element in :math:`x`, in radians and in the closed interval
:math:`\\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right]`.
Notes
-----
:py:obj:`asin` is a multivalued function: for each :math:`x` there are infinitely many numbers :math:`z`
such that :math:`\\sin(z) = x`. The convention is to return the angle :math:`z` whose real part lies in
:math:`\\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right]`.
References
----------
`np.asin <https://numpy.org/doc/stable/reference/generated/numpy.asin.html>`_
"""
if iarr.dtype not in _floating_dtypes:
raise TypeError("Only floating dtypes are allowed in asin")
return ia.LazyExpr(new_op=(iarr, "asin", None))
def atan(iarr: IArray, /):
"""
Trigonometric inverse tangent, element-wise.
The inverse of :py:obj:`tan` so that, if :math:`y = \\tan(x)`, then :math:`x = \\arctan(y)`.
Parameters
----------
iarr: :ref:`IArray`
Input array. Should have a floating-point data type.
Returns
-------
angle: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the
angles in radians, in the range :math:`\\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right]`.
Notes
-----
:py:obj:`atan` is a multi-valued function: for each x there are infinitely many numbers :math:`z`
such that :math:`\\tan(z) = x`. The convention is to return the angle :math:`z` whose real part lies in
:math:`\\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right]`.
References
----------
`np.atan <https://numpy.org/doc/stable/reference/generated/numpy.atan.html>`_
"""
if iarr.dtype not in _floating_dtypes:
raise TypeError("Only floating dtypes are allowed in atan")
return ia.LazyExpr(new_op=(iarr, "atan", None))
def atan2(iarr1: IArray, iarr2: IArray, /):
"""
Element-wise arc tangent of :math:`\\frac{iarr_1}{iarr_2}` choosing the quadrant correctly.
Parameters
----------
iarr1: :ref:`IArray`
y-coordinates. Should have a floating-point data type.
iarr2: :ref:`IArray`
x-coordinates. Should have a floating-point data type.
Returns
-------
angle: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the
angles in radians, in the range :math:`[-\\pi, \\pi]`.
References
----------
`np.atan2 <https://numpy.org/doc/stable/reference/generated/numpy.atan2.html>`_
"""
iarr1._check_allowed_dtypes(iarr2, "floating-point", "atan2")
return ia.LazyExpr(new_op=(iarr1, "atan2", iarr2))
def ceil(iarr: IArray, /):
"""
Return the ceiling of the input, element-wise. It is often denoted as :math:`\\lceil x \\rceil`.
Parameters
----------
iarr: :ref:`IArray`
Input array. Should have a numeric data type.
Returns
-------
out: :ref:`iarray.Expr`
A lazy expression that must be evaluated via `out.eval()`, which will compute the
ceiling of each element in :math:`x`.
References
----------
`np.ceil <https://numpy.org/doc/stable/reference/generated/numpy.ceil.html>`_
"""
if iarr.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in ceil")
return ia.LazyExpr(new_op=(iarr, "ceil", None))
def cos(iarr: IArray, /):
"""