Repository navigation
Expand file tree
/
Copy pathDelayedArray.py
More file actions
1138 lines (929 loc) · 44.3 KB
/
Copy pathDelayedArray.py
File metadata and controls
1138 lines (929 loc) · 44.3 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 typing import Sequence, Tuple, Union, Optional, List, Callable
import numpy
from numpy import dtype, ndarray, array2string
from collections import namedtuple
from .SparseNdarray import SparseNdarray
from .BinaryIsometricOp import BinaryIsometricOp
from .Cast import Cast
from .Combine import Combine, _simplify_combine
from .Round import Round
from .Subset import Subset, _simplify_subset
from .Transpose import Transpose, _simplify_transpose
from .UnaryIsometricOpSimple import UnaryIsometricOpSimple
from .UnaryIsometricOpWithArgs import UnaryIsometricOpWithArgs
from .extract_dense_array import extract_dense_array
from .to_dense_array import to_dense_array
from .extract_sparse_array import extract_sparse_array
from .apply_over_blocks import apply_over_blocks
from .create_dask_array import create_dask_array
from .chunk_grid import chunk_grid
from .is_sparse import is_sparse
from .is_masked import is_masked
from ._subset import _getitem_subset_preserves_dimensions, _getitem_subset_discards_dimensions, _repr_subset
from ._isometric import translate_ufunc_to_op_simple, translate_ufunc_to_op_with_args
from ._statistics import array_mean, array_var, array_sum, _create_offset_multipliers, array_any, array_all
__author__ = "ltla"
__copyright__ = "ltla"
__license__ = "MIT"
def _wrap_isometric_with_args(x, other, operation, right):
if hasattr(other, "shape") and other.shape == x.shape:
if right:
left = x
right = other
else:
left = other
right = x
return DelayedArray(
BinaryIsometricOp(_extract_seed(left), _extract_seed(right), operation)
)
return DelayedArray(
UnaryIsometricOpWithArgs(
_extract_seed(x),
value=other,
operation=operation,
right=right,
)
)
def _extract_seed(x):
if isinstance(x, DelayedArray):
return x._seed
else:
return x
class DelayedArray:
"""Array containing delayed operations. This is equivalent to the class of
the same name from the `R/Bioconductor package
<https://bioconductor.org/packages/DelayedArray>`_ of the same name. It
allows users to efficiently operate on large matrices without actually
evaluating the operation or creating new copies; instead, the operations
will transparently return another ``DelayedArray`` instance containing the
delayed operations, which can be realized by calling
:py:meth:`~numpy.array` or related methods.
Any object that satisfies the "seed contract" can be wrapped by a
``DelayedArray``. Specifically, a seed should have:
- The :py:attr:`~shape` and :py:attr:`~dtype` properties, which are of the
same type as the corresponding properties of NumPy arrays.
- A method for the
:py:meth:`~delayedarray.extract_dense_array.extract_dense_array` generic.
- A method for the :py:meth:`~delayedarray.is_masked.is_masked` generic.
- A method for the :py:meth:`~delayedarray.chunk_grid.chunk_grid` generic.
If the seed contains sparse data, it should also implement:
- A method for the :py:meth:`~delayedarray.is_sparse.is_sparse` generic.
- A method for the
:py:meth:`~delayedarray.extract_sparse_array.extract_sparse_array`
generic.
Optionally, a seed class may have:
- A method for the
:py:meth:`~delayedarray.create_dask_array.create_dask_array` generic,
if the seed is not already compatible with the **dask** package.
- a method for the `wrap()` generic, to create a ``DelayedArray``
subclass that is specific to this seed class.
"""
def __init__(self, seed):
"""Most users should use :py:meth:`~delayedarray.wrap.wrap`
instead, as this can be specialized by developers to construct
subclasses that are optimized for custom seed types.
Args:
seed: Any array-like object that satisfies the seed contract.
"""
self._seed = seed
@property
def shape(self) -> Tuple[int, ...]:
"""
Returns:
Tuple of integers specifying the extent of each dimension of the ``DelayedArray``.
"""
return self._seed.shape
@property
def dtype(self) -> dtype:
"""
Returns:
NumPy type of the elements in the ``DelayedArray``.
"""
return self._seed.dtype
@property
def seed(self):
"""
Returns:
The seed object.
"""
return self._seed
@property
def T(self) -> "DelayedArray":
"""
Returns:
A ``DelayedArray`` containing the delayed transpose.
"""
tout = Transpose(self._seed, perm=None)
tout = _simplify_transpose(tout)
return DelayedArray(tout)
def __repr__(self) -> str:
"""Pretty-print this ``DelayedArray``. This uses
:py:meth:`~numpy.array2string` and responds to all of its options.
Returns:
String containing a prettified display of the array contents.
"""
preamble = "<" + " x ".join([str(x) for x in self._seed.shape]) + ">"
if is_sparse(self._seed):
preamble += " sparse"
preamble += " " + type(self).__name__ + " object of type '" + self._seed.dtype.name + "'"
indices = _repr_subset(self._seed.shape)
bits_and_pieces = extract_dense_array(self._seed, indices)
converted = array2string(bits_and_pieces, separator=", ", threshold=0)
return preamble + "\n" + converted
# For NumPy:
def __array__(self, dtype: Optional[numpy.dtype] = None, copy: bool = True) -> ndarray:
"""Convert a ``DelayedArray`` to a NumPy array, to be used by
:py:meth:`~numpy.array`.
Args:
dtype:
The desired NumPy type of the output array. If None, the
type of the seed is used.
copy:
Currently ignored. The output is never a reference to the
underlying seed, even if the seed is another NumPy array.
Returns:
NumPy array of the same type as :py:attr:`~dtype` and shape as
:py:attr:`~shape`.
"""
if dtype is None or dtype == self.dtype:
return to_dense_array(self._seed)
else:
# Filling it chunk by chunk rather than doing a big coercion,
# to avoid creating an unnecessary intermediate full matrix.
output = numpy.ndarray(self.shape, dtype=dtype)
if is_masked(self._seed):
output = numpy.ma.array(output, mask=False)
def fill_output(job, part):
subsets = (*(slice(s, e) for s, e in job),)
output[subsets] = part
apply_over_blocks(self._seed, fill_output)
return output
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) -> "DelayedArray":
"""Interface with NumPy array methods. This is used to implement
mathematical operations like NumPy's :py:meth:`~numpy.log`, or to
override operations between NumPy class instances and ``DelayedArray``
objects where the former is on the left hand side.
Check out NumPy's ``__array_ufunc__`` `documentation
<https://numpy.org/doc/stable/reference/arrays.classes.html#numpy.class.__array_ufunc__>`_
for more details.
Returns:
A ``DelayedArray`` instance containing the requested delayed operation.
"""
if (
ufunc.__name__ in translate_ufunc_to_op_with_args
or ufunc.__name__ == "true_divide"
):
# This is required to support situations where the NumPy array is on
# the LHS, such that the ndarray method gets called first.
op = ufunc.__name__
if ufunc.__name__ == "true_divide":
op = "divide"
first_is_da = isinstance(inputs[0], DelayedArray)
da = inputs[1 - int(first_is_da)]
v = inputs[int(first_is_da)]
return _wrap_isometric_with_args(
_extract_seed(da), v, operation=op, right=first_is_da
)
elif ufunc.__name__ in translate_ufunc_to_op_simple:
return DelayedArray(
UnaryIsometricOpSimple(
_extract_seed(inputs[0]), operation=ufunc.__name__
)
)
elif ufunc.__name__ == "absolute":
return DelayedArray(
UnaryIsometricOpSimple(_extract_seed(inputs[0]), operation="abs")
)
elif ufunc.__name__ == "logical_not":
return DelayedArray(
UnaryIsometricOpSimple(_extract_seed(inputs[0]), operation="logical_not")
)
raise NotImplementedError(f"'{ufunc.__name__}' is not implemented!")
# Just get the array priority above that of the numpy MaskedArray so that
# we call DelayedArray's __array_ufunc__ override instead... annoyingly, it
# doesn't actually work (https://github.com/numpy/numpy/issues/15200).
__array_priority__ = numpy.ma.MaskedArray.__array_priority__ + 1
def __array_function__(self, func, types, args, kwargs) -> "DelayedArray":
"""Interface to NumPy's high-level array functions. This is used to
implement array operations like NumPy's :py:meth:`~numpy.concatenate`,
Check out NumPy's ``__array_function__`` `documentation
<https://numpy.org/doc/stable/reference/arrays.classes.html#numpy.class.__array_function__>`_
for more details.
Returns:
A ``DelayedArray`` instance containing the requested delayed operation.
"""
if func == numpy.concatenate:
seeds = []
for x in args[0]:
seeds.append(_extract_seed(x))
if "axis" in kwargs:
axis = kwargs["axis"]
else:
axis = 0
cout = Combine(seeds, along=axis)
cout = _simplify_combine(cout)
return DelayedArray(cout)
if func == numpy.transpose:
seed = _extract_seed(args[0])
if "axes" in kwargs:
axes = kwargs["axes"]
else:
axes = None
tout = Transpose(seed, perm=axes)
tout = _simplify_transpose(tout)
return DelayedArray(tout)
if func == numpy.round:
seed = _extract_seed(args[0])
if "decimals" in kwargs:
decimals = kwargs["decimals"]
else:
decimals = 0
return DelayedArray(Round(seed, decimals=decimals))
if func == numpy.mean:
return self.mean(**kwargs)
if func == numpy.sum:
return self.sum(**kwargs)
if func == numpy.var:
return self.var(**kwargs)
if func == numpy.any:
return self.any(**kwargs)
if func == numpy.all:
return self.all(**kwargs)
if func == numpy.shape:
return self.shape
raise NotImplementedError(f"'{func.__name__}' is not implemented!")
def astype(self, dtype, **kwargs):
"""See :py:meth:`~numpy.ndarray.astype` for details.
All keyword arguments are currently ignored.
"""
return DelayedArray(Cast(self._seed, dtype))
# Assorted dunder methods.
def __add__(self, other) -> "DelayedArray":
"""Add something to the right-hand-side of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed addition operation.
"""
return _wrap_isometric_with_args(self, other, operation="add", right=True)
def __radd__(self, other) -> "DelayedArray":
"""Add something to the left-hand-side of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed addition operation.
"""
return _wrap_isometric_with_args(self, other, operation="add", right=False)
def __sub__(self, other) -> "DelayedArray":
"""Subtract something from the right-hand-side of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed subtraction operation.
"""
return _wrap_isometric_with_args(self, other, operation="subtract", right=True)
def __rsub__(self, other):
"""Subtract a ``DelayedArray`` from something else.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed subtraction operation.
"""
return _wrap_isometric_with_args(self, other, operation="subtract", right=False)
def __mul__(self, other):
"""Multiply a ``DelayedArray`` with something on the right hand side.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed multiplication operation.
"""
return _wrap_isometric_with_args(self, other, operation="multiply", right=True)
def __rmul__(self, other):
"""Multiply a ``DelayedArray`` with something on the left hand side.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed multiplication operation.
"""
return _wrap_isometric_with_args(self, other, operation="multiply", right=False)
def __truediv__(self, other):
"""Divide a ``DelayedArray`` by something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed division operation.
"""
return _wrap_isometric_with_args(self, other, operation="divide", right=True)
def __rtruediv__(self, other):
"""Divide something by a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed division operation.
"""
return _wrap_isometric_with_args(self, other, operation="divide", right=False)
def __mod__(self, other):
"""Take the remainder after dividing a ``DelayedArray`` by something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` object of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed modulo operation.
"""
return _wrap_isometric_with_args(self, other, operation="remainder", right=True)
def __rmod__(self, other):
"""Take the remainder after dividing something by a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed modulo operation.
"""
return _wrap_isometric_with_args(
self, other, operation="remainder", right=False
)
def __floordiv__(self, other):
"""Divide a ``DelayedArray`` by something and take the floor.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed floor division operation.
"""
return _wrap_isometric_with_args(
self, other, operation="floor_divide", right=True
)
def __rfloordiv__(self, other):
"""Divide something by a ``DelayedArray`` and take the floor.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed floor division operation.
"""
return _wrap_isometric_with_args(
self, other, operation="floor_divide", right=False
)
def __pow__(self, other):
"""Raise a ``DelayedArray`` to the power of something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed power operation.
"""
return _wrap_isometric_with_args(self, other, operation="power", right=True)
def __rpow__(self, other):
"""Raise something to the power of the contents of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed power operation.
"""
return _wrap_isometric_with_args(self, other, operation="power", right=False)
def __eq__(self, other) -> "DelayedArray":
"""Check for equality between a ``DelayedArray`` and something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="equal", right=True)
def __req__(self, other) -> "DelayedArray":
"""Check for equality between something and a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="equal", right=False)
def __ne__(self, other) -> "DelayedArray":
"""Check for non-equality between a ``DelayedArray`` and something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="not_equal", right=True)
def __rne__(self, other) -> "DelayedArray":
"""Check for non-equality between something and a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(
self, other, operation="not_equal", right=False
)
def __ge__(self, other) -> "DelayedArray":
"""Check whether a ``DelayedArray`` is greater than or equal to something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(
self, other, operation="greater_equal", right=True
)
def __rge__(self, other) -> "DelayedArray":
"""Check whether something is greater than or equal to a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(
self, other, operation="greater_equal", right=False
)
def __le__(self, other) -> "DelayedArray":
"""Check whether a ``DelayedArray`` is less than or equal to something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(
self, other, operation="less_equal", right=True
)
def __rle__(self, other) -> "DelayedArray":
"""Check whether something is greater than or equal to a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(
self, other, operation="less_equal", right=False
)
def __gt__(self, other) -> "DelayedArray":
"""Check whether a ``DelayedArray`` is greater than something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="greater", right=True)
def __rgt__(self, other) -> "DelayedArray":
"""Check whether something is greater than a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="greater", right=False)
def __lt__(self, other) -> "DelayedArray":
"""Check whether a ``DelayedArray`` is less than something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="less", right=True)
def __rlt__(self, other) -> "DelayedArray":
"""Check whether something is less than a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed check.
"""
return _wrap_isometric_with_args(self, other, operation="less", right=False)
# Simple methods.
def __neg__(self) -> "DelayedArray":
"""Negate the contents of a ``DelayedArray``.
Returns:
A ``DelayedArray`` containing the delayed negation.
"""
return _wrap_isometric_with_args(self, 0, operation="subtract", right=False)
def __abs__(self) -> "DelayedArray":
"""Take the absolute value of the contents of a ``DelayedArray``.
Returns:
A ``DelayedArray`` containing the delayed absolute value operation.
"""
return DelayedArray(UnaryIsometricOpSimple(self._seed, operation="abs"))
def __or__(self, other) -> "DelayedArray":
"""Element-wise OR with something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed OR operation.
"""
return _wrap_isometric_with_args(self, other, operation="logical_or", right=True)
def __ror__(self, other) -> "DelayedArray":
"""Element-wise OR with the right-hand-side of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed OR operation.
"""
return _wrap_isometric_with_args(self, other, operation="logical_or", right=False)
def __and__(self, other) -> "DelayedArray":
"""Element-wise AND with something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed AND operation.
"""
return _wrap_isometric_with_args(self, other, operation="logical_and", right=True)
def __rand__(self, other) -> "DelayedArray":
"""Element-wise AND with the right-hand-side of a ``DelayedArray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or a ``DelayedArray`` of the same dimensions as :py:attr:`~shape`.
Returns:
A ``DelayedArray`` containing the delayed AND operation.
"""
return _wrap_isometric_with_args(self, other, operation="logical_and", right=False)
# Subsetting.
def __getitem__(self, subset) -> Union["DelayedArray", ndarray]:
"""Take a subset of this ``DelayedArray``. This follows the same logic as NumPy slicing and will generate a
:py:class:`~delayedarray.Subset.Subset` object when the subset operation preserves the dimensionality of the
seed, i.e., ``args`` is defined using the :py:meth:`~numpy.ix_` function.
Args:
subset:
A :py:class:`tuple` of length equal to the dimensionality of this ``DelayedArray``, or a single integer specifying an index on the first dimension.
We attempt to support most types of NumPy slicing; however, only subsets that preserve dimensionality will generate a delayed subset operation.
Returns:
If the dimensionality is preserved by ``subset``, a ``DelayedArray`` containing a delayed subset operation is returned.
Otherwise, a :py:class:`~numpy.ndarray` is returned containing the realized subset.
"""
if not isinstance(subset, Tuple):
replacement = [slice(None)] * len(self.shape)
replacement[0] = subset
subset = (*replacement,)
cleaned = _getitem_subset_preserves_dimensions(self.shape, subset)
if cleaned is not None:
sout = Subset(self._seed, cleaned)
sout = _simplify_subset(sout)
return DelayedArray(sout)
return _getitem_subset_discards_dimensions(self._seed, subset, extract_dense_array)
# For python-level compute.
def sum(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, buffer_size: Optional[int] = None) -> numpy.ndarray:
"""
Take the sum of values across the ``DelayedArray``, possibly over a
given axis or set of axes. If the seed has a ``sum()`` method, that
method is called directly with the supplied arguments.
Args:
axis:
A single integer specifying the axis over which to calculate
the sum. Alternatively, a tuple (multiple axes) or None (no
axes), see :py:func:`~numpy.sum` for details.
dtype:
NumPy type for the output array. If None, this is automatically
chosen based on the type of the ``DelayedArray``, see
:py:func:`~numpy.sum` for details.
buffer_size:
Buffer size in bytes to use for block processing.
Larger values generally improve speed at the cost of memory.
If ``None``, defaults to the value returned by :py:func:`~delayedarray.default_buffer_size.default_buffer_size`.
Returns:
A NumPy array containing the sums. If ``axis = None``, this will be
a NumPy scalar instead.
"""
if hasattr(self._seed, "sum"):
return self._seed.sum(axis=axis, dtype=dtype)
else:
return array_sum(
self,
axis=axis,
dtype=dtype,
reduce_over_x=lambda x, axes, op : _reduce(x, axes, op, buffer_size),
masked=is_masked(self),
)
def mean(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, buffer_size: Optional[int] = None) -> numpy.ndarray:
"""
Take the mean of values across the ``DelayedArray``, possibly over a
given axis or set of axes. If the seed has a ``mean()`` method, that
method is called directly with the supplied arguments.
Args:
axis:
A single integer specifying the axis over which to calculate
the mean. Alternatively, a tuple (multiple axes) or None (no
axes), see :py:func:`~numpy.mean` for details.
dtype:
NumPy type for the output array. If None, this is automatically
chosen based on the type of the ``DelayedArray``, see
:py:func:`~numpy.mean` for details.
buffer_size:
Buffer size in bytes to use for block processing.
Larger values generally improve speed at the cost of memory.
If ``None``, defaults to the value returned by :py:func:`~delayedarray.default_buffer_size.default_buffer_size`.
Returns:
A NumPy array containing the means. If ``axis = None``, this will
be a NumPy scalar instead.
"""
if hasattr(self._seed, "mean"):
return self._seed.mean(axis=axis, dtype=dtype)
else:
return array_mean(
self,
axis=axis,
dtype=dtype,
reduce_over_x=lambda x, axes, op : _reduce(x, axes, op, buffer_size),
masked=is_masked(self),
)
def var(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, ddof: int = 0, buffer_size: Optional[int] = None) -> numpy.ndarray:
"""
Take the variances of values across the ``DelayedArray``, possibly over
a given axis or set of axes. If the seed has a ``var()`` method, that
method is called directly with the supplied arguments.
Args:
axis:
A single integer specifying the axis over which to calculate
the variance. Alternatively, a tuple (multiple axes) or None
(no axes), see :py:func:`~numpy.var` for details.
dtype:
NumPy type for the output array. If None, this is automatically
chosen based on the type of the ``DelayedArray``, see
:py:func:`~numpy.var` for details.
ddof:
Delta in the degrees of freedom to subtract from the denominator.
Typically set to 1 to obtain the sample variance.
buffer_size:
Buffer size in bytes to use for block processing.
Larger values generally improve speed at the cost of memory.
If ``None``, defaults to the value returned by :py:func:`~delayedarray.default_buffer_size.default_buffer_size`.
Returns:
A NumPy array containing the variances. If ``axis = None``,
this will be a NumPy scalar instead.
"""
if hasattr(self._seed, "var"):
return self._seed.var(axis=axis, dtype=dtype, ddof=ddof)
else:
return array_var(
self,
axis=axis,
dtype=dtype,
ddof=ddof,
reduce_over_x=lambda x, axes, op : _reduce(x, axes, op, buffer_size),
masked=is_masked(self),
)
def any(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, buffer_size: Optional[int] = None) -> numpy.ndarray:
"""Test whether any array element along a given axis evaluates to True.
Compute this test across the ``DelayedArray``, possibly over a
given axis or set of axes. If the seed has a ``any()`` method, that
method is called directly with the supplied arguments.
Args:
axis:
A single integer specifying the axis over which to test
for any. Alternatively, a tuple (multiple axes) or None (no
axes), see :py:func:`~numpy.any` for details.
dtype:
NumPy type for the output array. If None, this is automatically
chosen based on the type of the ``DelayedArray``, see
:py:func:`~numpy.any` for details.
buffer_size:
Buffer size in bytes to use for block processing.
Larger values generally improve speed at the cost of memory.
If ``None``, defaults to the value returned by :py:func:`~delayedarray.default_buffer_size.default_buffer_size`.
Returns:
A NumPy array containing the boolean values. If ``axis = None``, this will
be a NumPy scalar instead.
"""
if hasattr(self._seed, "any"):
return self._seed.any(axis=axis).astype(dtype)
else:
return array_any(
self,
axis=axis,
dtype=dtype,
reduce_over_x=lambda x, axes, op : _reduce(x, axes, op, buffer_size),
masked=is_masked(self),
)
def all(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, buffer_size: Optional[int] = None) -> numpy.ndarray:
"""Test whether all array elements along a given axis evaluate to True.
Compute this test across the ``DelayedArray``, possibly over a
given axis or set of axes. If the seed has a ``all()`` method, that
method is called directly with the supplied arguments.
Args:
axis:
A single integer specifying the axis over which to test
for all. Alternatively, a tuple (multiple axes) or None (no
axes), see :py:func:`~numpy.all` for details.
dtype:
NumPy type for the output array. If None, this is automatically
chosen based on the type of the ``DelayedArray``, see
:py:func:`~numpy.all` for details.
buffer_size:
Buffer size in bytes to use for block processing.