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
1229 lines (973 loc) · 36 KB
/
Copy pathiarray_container.py
File metadata and controls
1229 lines (973 loc) · 36 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 INAOS GmbH, Thalwil, 2018.
# Copyright Francesc Alted, 2018.
#
# All rights reserved.
#
# This software is the confidential and proprietary information of INAOS GmbH
# and Francesc Alted ("Confidential Information"). You shall not disclose such Confidential
# Information and shall use it only in accordance with the terms of the license agreement.
###########################################################################################
import iarray as ia
from iarray import iarray_ext as ext
import numpy as np
from typing import Union
import ndindex
from .info import InfoReporter
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.
"""
@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)
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 deactives 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):
"""Change the shape of the array by growing one or more dimensions.
Parameters
----------
newshape : tuple or list
The new shape of the array container. It should have the same dimensions
as `self`.
Notes
-----
The array values corresponding to the added positions are not initialized.
Thus, the user is in charge of initializing them.
"""
ext.resize(self, newshape)
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):
# 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, value):
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)):
value = np.full(shape, value, dtype=self.dtype)
elif isinstance(value, ia.IArray):
value = value.data
with ia.config(cfg=self.cfg) as cfg:
return ext.set_slice(cfg, self, start, stop, value)
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):
a = self
return ia.matmul(a, value)
def __add__(self, value):
return ia.LazyExpr(new_op=(self, "+", value))
def __radd__(self, value):
return ia.LazyExpr(new_op=(value, "+", self))
def __sub__(self, value):
return ia.LazyExpr(new_op=(self, "-", value))
def __rsub__(self, value):
return ia.LazyExpr(new_op=(value, "-", self))
def __mul__(self, value):
return ia.LazyExpr(new_op=(self, "*", value))
def __rmul__(self, value):
return ia.LazyExpr(new_op=(value, "*", self))
def __truediv__(self, value):
return ia.LazyExpr(new_op=(self, "/", value))
def __rtruediv__(self, value):
return ia.LazyExpr(new_op=(value, "/", self))
# 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):
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.transpose(self, **kwargs)
def abs(self):
"""
Absolute value, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
abs: :ref:`IArray`
An array containing the absolute value of each element in x.
References
----------
`np.absolute <https://numpy.org/doc/stable/reference/generated/numpy.absolute.html>`_
"""
return ia.LazyExpr(new_op=(self, "abs", None))
def arccos(self):
"""
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]`.
Returns
-------
angle: :ref:`IArray`
The angle of the ray intersecting the unit circle at the given x-coordinate in radians
:math:`[0, \\pi]`.
Notes
-----
:py:obj:`arccos` 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.arccos <https://numpy.org/doc/stable/reference/generated/numpy.arccos.html>`_
"""
return ia.LazyExpr(new_op=(self, "acos", None))
def arcsin(self):
"""
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.
Returns
-------
angle: :ref:`IArray`
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:`arcsin` 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.arcsin <https://numpy.org/doc/stable/reference/generated/numpy.arcsin.html>`_
"""
return ia.LazyExpr(new_op=(self, "asin", None))
def arctan(self):
"""
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.
Returns
-------
angle: :ref:`IArray`
Array of angles in radians, in the range
:math:`\\left[-\\frac{\\pi}{2}, \\frac{\\pi}{2}\\right]`.
Notes
-----
:py:obj:`arctan` 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.arctan <https://numpy.org/doc/stable/reference/generated/numpy.arctan.html>`_
"""
return ia.LazyExpr(new_op=(self, "atan", None))
def arctan2(self, op2):
"""
Element-wise arc tangent of :math:`\\frac{iarr_1}{iarr_2}` choosing the quadrant correctly.
Parameters
----------
iarr1: :ref:`IArray`
y-coordinates.
iarr2: :ref:`IArray`
x-coordinates.
Returns
-------
angle: :ref:`IArray`
Array of angles in radians, in the range :math:`[-\\pi, \\pi]`.
References
----------
`np.arctan2 <https://numpy.org/doc/stable/reference/generated/numpy.arctan2.html>`_
"""
return ia.LazyExpr(new_op=(self, "atan2", op2))
def acos(self):
"""See :py:obj:`IArray.arccos`."""
return ia.LazyExpr(new_op=(self, "acos", None))
def asin(self):
"""See :py:obj:`IArray.arcsin`."""
return ia.LazyExpr(new_op=(self, "asin", None))
def atan(self):
"""See :py:obj:`IArray.arctan`."""
return ia.LazyExpr(new_op=(self, "atan", None))
def atan2(self, op2):
"""See :py:obj:`IArray.arctan2`."""
return ia.LazyExpr(new_op=(self, "atan2", op2))
def ceil(self):
"""
Return the ceiling of the input, element-wise. It is often denoted as :math:`\\lceil x \\rceil`.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
The ceiling of each element in :math:`x`.
References
----------
`np.ceil <https://numpy.org/doc/stable/reference/generated/numpy.ceil.html>`_
"""
return ia.LazyExpr(new_op=(self, "ceil", None))
def cos(self):
"""
Trigonometric cosine, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Angle, in radians.
Returns
-------
out: :ref:`IArray`
The corresponding cosine values.
References
----------
`np.cos <https://numpy.org/doc/stable/reference/generated/numpy.cos.html>`_
"""
return ia.LazyExpr(new_op=(self, "cos", None))
def cosh(self):
"""
Hyperbolic cosine, element-wise.
Equivalent to ``1/2 * (ia.exp(x) + ia.exp(-x))``.
Parameters
----------
iarr: :ref:`IArray`
Input data.
Returns
-------
out: :ref:`IArray`
The corresponding hyperbolic cosine values.
References
----------
`np.cosh <https://numpy.org/doc/stable/reference/generated/numpy.cosh.html>`_
"""
return ia.LazyExpr(new_op=(self, "cosh", None))
def exp(self):
"""
Calculate the exponential of all elements in the input array.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
Element-wise exponential of input data.
References
----------
`np.exp <https://numpy.org/doc/stable/reference/generated/numpy.exp.html>`_
"""
return ia.LazyExpr(new_op=(self, "exp", None))
def floor(self):
"""
Return the floor of the input, element-wise. It is often denoted as :math:`\\lfloor x \\rfloor`.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
The floor of each element in input data.
References
----------
`np.floor <https://numpy.org/doc/stable/reference/generated/numpy.floor.html>`_
"""
return ia.LazyExpr(new_op=(self, "floor", None))
def log(self):
"""
Natural logarithm, element-wise.
The natural logarithm log is the inverse of the exponential function, so that
:math:`\\log(\\exp(x)) = x`. The natural logarithm is logarithm in base :math:`e`.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
The natural logarithm of input data, element-wise.
References
----------
`np.log <https://numpy.org/doc/stable/reference/generated/numpy.log.html>`_
"""
return ia.LazyExpr(new_op=(self, "log", None))
def log10(self):
"""
Return the base 10 logarithm of the input array, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
The logarithm to the base 10 of input data, element-wise.
References
----------
`np.log10 <https://numpy.org/doc/stable/reference/generated/numpy.log10.html>`_
"""
return ia.LazyExpr(new_op=(self, "log10", None))
def negative(self):
"""
Numerical negative, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Input array.
Returns
-------
out: :ref:`IArray`
Returned array :math:`out = -iarr`.
References
----------
`np.negative <https://numpy.org/doc/stable/reference/generated/numpy.negative.html>`_
"""
return ia.LazyExpr(new_op=(self, "negate", None))
def power(self, op2):
"""
First array elements raised to powers from second array, element-wise.
Parameters
----------
iarr1: :ref:`IArray`
The bases.
iarr1: :ref:`IArray`
The exponents.
Returns
-------
out: :ref:`IArray`
The bases raised to the exponents.
References
----------
`np.power <https://numpy.org/doc/stable/reference/generated/numpy.power.html>`_
"""
return ia.LazyExpr(new_op=(self, "pow", op2))
def sin(self):
"""
Trigonometric sine, element-wise.
Parameters
----------
iarr: :ref:`IArray`
Angle, in radians.
Returns
-------
out: :ref:`IArray`
The corresponding sine values.
References
----------
`np.sin <https://numpy.org/doc/stable/reference/generated/numpy.sin.html>`_
"""
return ia.LazyExpr(new_op=(self, "sin", None))
def sinh(self):
"""
Hyperbolic sine, element-wise.
Equivalent to ``1/2 * (ia.exp(x) - ia.exp(-x))``.
Parameters
----------
iarr: :ref:`IArray`
Input data.
Returns
-------
out: :ref:`IArray`
The corresponding hyperbolic sine values.
References
----------
`np.sinh <https://numpy.org/doc/stable/reference/generated/numpy.sinh.html>`_
"""
return ia.LazyExpr(new_op=(self, "sinh", None))
def sqrt(self):
"""
Return the non-negative square-root of an array, element-wise.
Parameters
----------
iarr: :ref:`IArray`
The values whose square-roots are required.
Returns
-------
out: :ref:`IArray`
An array containing the positive square-root of each element in input data.
References
----------
`np.sqrt <https://numpy.org/doc/stable/reference/generated/numpy.sqrt.html>`_
"""
return ia.LazyExpr(new_op=(self, "sqrt", None))
def tan(self):
"""
Compute tangent element-wise.
Equivalent to ``ia.sin(x)/ia.cos(x)`` element-wise.
Parameters
----------
iarr: :ref:`IArray`
Input data.
Returns
-------
out: :ref:`IArray`
The corresponding tangent values.
References
----------
`np.tan <https://numpy.org/doc/stable/reference/generated/numpy.tan.html>`_
"""
return ia.LazyExpr(new_op=(self, "tan", None))
def tanh(self):
"""
Compute hyperbolic tangent element-wise.
Equivalent to ``ia.sinh(x)/ia.cosh(x)``.
Parameters
----------
iarr: :ref:`IArray`
Input data.
Returns
-------
out: :ref:`IArray`
The corresponding hyperbolic tangent values.
References
----------
`np.tanh <https://numpy.org/doc/stable/reference/generated/numpy.tanh.html>`_
"""
return ia.LazyExpr(new_op=(self, "tanh", None))
@is_documented_by(IArray.abs)
def abs(iarr: IArray):
return iarr.abs()
@is_documented_by(IArray.arccos)
def arccos(iarr: IArray):
return iarr.arccos()
@is_documented_by(IArray.arcsin)
def arcsin(iarr: IArray):
return iarr.arcsin()
@is_documented_by(IArray.arctan)
def arctan(iarr: IArray):
return iarr.arctan()
@is_documented_by(IArray.arctan2)
def arctan2(iarr1: IArray, iarr2: IArray):
return iarr1.arctan2(iarr2)
@is_documented_by(IArray.ceil)
def ceil(iarr: IArray):
return iarr.ceil()
@is_documented_by(IArray.cos)
def cos(iarr: IArray):
return iarr.cos()
@is_documented_by(IArray.cosh)
def cosh(iarr: IArray):
return iarr.cosh()
@is_documented_by(IArray.exp)
def exp(iarr: IArray):
return iarr.exp()
@is_documented_by(IArray.floor)
def floor(iarr: IArray):
return iarr.floor()
@is_documented_by(IArray.log)
def log(iarr: IArray):
return iarr.log()
@is_documented_by(IArray.log10)
def log10(iarr: IArray):
return iarr.log10()
@is_documented_by(IArray.negative)
def negative(iarr: IArray):
return iarr.negative()
@is_documented_by(IArray.power)
def power(iarr1: IArray, iarr2: IArray):
return iarr1.power(iarr2)
@is_documented_by(IArray.sin)
def sin(iarr: IArray):
return iarr.sin()
@is_documented_by(IArray.sinh)
def sinh(iarr: IArray):
return iarr.sinh()
@is_documented_by(IArray.sqrt)
def sqrt(iarr: IArray):
return iarr.sqrt()
@is_documented_by(IArray.tan)
def tan(iarr: IArray):
return iarr.tan()
@is_documented_by(IArray.tanh)
def tanh(iarr: IArray):
return iarr.tanh()
# Reductions
def reduce(
a: IArray, method: ia.Reduce, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs
):
if axis is None:
axis = range(a.ndim)
if isinstance(axis, int):
axis = (axis,)
shape = tuple([s for i, s in enumerate(a.shape) if i not in axis])
if cfg is None:
cfg = ia.get_config_defaults()
dtype = kwargs.get("dtype")
with ia.config(shape=shape, cfg=cfg, **kwargs) as cfg:
c = ext.reduce_multi(cfg, a, method, axis)
if dtype is not None and dtype != c.dtype:
raise RuntimeError("Cannot set the result's data type")
if c.ndim == 0:
c = c.dtype(ia.iarray2numpy(c))
return c
def max(a: IArray, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs):
"""
Return the maximum of an array or maximum along an axis.
Parameters
----------
a : :ref:`IArray`
Input data.
axis : None, int, tuple of ints, optional
Axis or axes along which the reduction is performed. The default (axis = None) is perform
the reduction over all dimensions of the input array.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single
axis or all the axes as default.
cfg : :class:`Config` or None
The configuration for this operation. If None (default), the current configuration will be
used.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config` dataclass that should
override the current configuration.
Returns
-------
max : :ref:`IArray` or float
Maximum of a. If axis is None, the result is a value. If axis is given, the result is
an array of dimension a.ndim - len(axis). The `dtype` is always the `dtype` of :paramref:`a`.
"""
return reduce(a, ia.Reduce.MAX, axis, cfg, **kwargs)
def min(a: IArray, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs):
"""
Return the minimum of an array or minimum along an axis.
Parameters
----------
a : :ref:`IArray`
Input data.
axis : None, int, tuple of ints, optional
Axis or axes along which the reduction is performed. The default (axis = None) is perform
the reduction over all dimensions of the input array.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single
axis or all the axes as default.
cfg : :class:`Config` or None
The configuration for this operation. If None (default), the current configuration will be
used.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config` dataclass that should
override the current configuration.
Returns
-------
min : :ref:`IArray` or float
Minimum of a. If axis is None, the result is a value. If axis is given, the result is
an array of dimension a.ndim - len(axis). The `dtype` is always the `dtype` of :paramref:`a`.
"""
return reduce(a, ia.Reduce.MIN, axis, cfg, **kwargs)
def sum(a: IArray, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs):
"""
Return the sum of array elements over a given axis.
Parameters
----------
a : :ref:`IArray`
Input data.
axis : None, int, tuple of ints, optional
Axis or axes along which the reduction is performed. The default (axis = None) is perform
the reduction over all dimensions of the input array.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single
axis or all the axes as default.
cfg : :class:`Config` or None
The configuration for this operation. If None (default), the current configuration will be
used.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config` dataclass that should
override the current configuration.
Returns
-------
sum : :ref:`IArray` or float
Sum of a. If axis is None, the result is a value. If axis is given, the result is
an array of dimension a.ndim - len(axis). Its `dtype` is `np.int64` for integers and bools,
`np.uint64` for unsigned integers and the `dtype` of :paramref:`a` otherwise.
"""
return reduce(a, ia.Reduce.SUM, axis, cfg, **kwargs)
def prod(a: IArray, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs):
"""
Return the product of array elements over a given axis.
Parameters
----------
a : :ref:`IArray`
Input data.
axis : None, int, tuple of ints, optional
Axis or axes along which the reduction is performed. The default (axis = None) is perform
the reduction over all dimensions of the input array.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single
axis or all the axes as default.
cfg : :class:`Config` or None
The configuration for this operation. If None (default), the current configuration will be
used.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config` dataclass that should
override the current configuration.
Returns
-------
prod : :ref:`IArray` or float
Product of a. If axis is None, the result is a value. If axis is given, the result is
an array of dimension a.ndim - len(axis). Its `dtype` is `np.int64` for integers and bools,
`np.uint64` for unsigned integers and the `dtype` of :paramref:`a` otherwise.
"""
return reduce(a, ia.Reduce.PROD, axis, cfg, **kwargs)
def mean(a: IArray, axis: Union[int, tuple] = None, cfg: ia.Config = None, **kwargs):
"""
Compute the arithmetic mean along the specified axis. Returns the average of the array elements.
Parameters
----------
a : :ref:`IArray`
Input data.
axis : None, int, tuple of ints, optional
Axis or axes along which the reduction is performed. The default (axis = None) is perform
the reduction over all dimensions of the input array.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single
axis or all the axes as default.
cfg : :class:`Config` or None
The configuration for this operation. If None (default), the current configuration will be
used.
kwargs : dict
A dictionary for setting some or all of the fields in the :class:`Config` dataclass that should
override the current configuration.
Returns
-------
mean : :ref:`IArray` or float
Mean of a. If axis is None, the result is a value. If axis is given, the result is
an array of dimension a.ndim - len(axis). Its `dtype` is `np.float32` when the `dtype` of
:paramref:`a` is `np.float32` and `np.float64` otherwise.
"""
return reduce(a, ia.Reduce.MEAN, axis, cfg, **kwargs)
# Linear Algebra
def opt_gemv(a: IArray, b: IArray, cfg=None, **kwargs):
shape = (a.shape[0], b.shape[1]) if b.ndim == 2 else (a.shape[0],)
if cfg is None:
cfg = ia.get_config_defaults()
with ia.config(shape=shape, cfg=cfg, **kwargs) as cfg:
return ext.opt_gemv(cfg, a, b)
def matmul_params(ashape, bshape, itemsize=8, l2_size=512 * 1024, chunk_size=128 * 1024 * 1024):
"""
Given a matrix multiplication of two arrays, it computes the chunks and the blocks of the operands
to use an optimized version of the matmul algorithm.
Parameters
----------
ashape: tuple or list
The shape of the operand a.
bshape: tuple or list
The shape of the operand b.
itemsize:
The size of each item.
l2_size: int
The size of the l2 cache. It is used to compute the size of the blocks.
chunk_size: int
The maximum chunksize allowed. It is used to compute the size of the chunks.
Returns
-------
params: tuple
A tuple specifying the chunks and the blocks of the matmul operands a and b
(achunks, ablocks, bchunks, bblocks).
"""
if len(ashape) != 2:
raise AttributeError("The dimension of a must be 2")
if len(bshape) != 1 and len(bshape) != 2:
raise AttributeError("The dimension of b must be 1 or 2")
if ashape[1] != bshape[0]:
raise AttributeError("ashape[1] must be equal to bshape[0]")
if len(bshape) == 1:
return matmul_gemv_params(ashape[0], ashape[1], itemsize, l2_size, chunk_size)
else:
return matmul_gemm_params(ashape[0], ashape[1], bshape[1], itemsize, l2_size, chunk_size)
def matmul_gemv_params(M, N, itemsize=8, l2_size=512 * 1024, chunk_size=128 * 1024 * 1024):