Repository navigation
Expand file tree
/
Copy pathSparseNdarray.py
More file actions
1905 lines (1541 loc) · 72.5 KB
/
Copy pathSparseNdarray.py
File metadata and controls
1905 lines (1541 loc) · 72.5 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 bisect import bisect_left
from typing import Callable, List, Optional, Sequence, Tuple, Union
from collections import namedtuple
import numpy
import copy
from ._isometric import translate_ufunc_to_op_simple, translate_ufunc_to_op_with_args, ISOMETRIC_OP_WITH_ARGS, _choose_operator, _infer_along_with_args
from ._subset import _spawn_indices, _getitem_subset_preserves_dimensions, _getitem_subset_discards_dimensions, _repr_subset
from ._mask import (
_allocate_unmasked_ndarray,
_allocate_maybe_masked_ndarray,
_convert_to_unmasked_1darray,
_convert_to_maybe_masked_1darray,
_concatenate_unmasked_ndarrays,
_concatenate_maybe_masked_ndarrays
)
from ._statistics import array_mean, array_var, array_sum, _create_offset_multipliers, array_all, array_any
__author__ = "ltla"
__copyright__ = "ltla"
__license__ = "MIT"
class SparseNdarray:
"""
The ``SparseNdarray``, as its name suggests, is a sparse n-dimensional
array. It is inspired by the ``SVT_Array`` class from the `DelayedArray
R/Bioconductor package <https://bioconductor.org/packages/DelayedArray>`_.
Internally, the ``SparseNdarray`` is represented as a nested list where
each nesting level corresponds to a dimension in reverse order, i.e., the
outer-most list corresponds to elements of the last dimension in ``shape``.
The list at each level has length equal to the extent of its dimension,
where each entry contains another list representing the contents of the
corresponding element of that dimension. This recursion continues until the
second dimension (i.e., the penultimate nesting level), where each entry
instead contains ``(index, value)`` tuples. In effect, this is a tree where
the non-leaf nodes are lists and the leaf nodes are tuples.
Each ``(index, value)`` tuple represents a sparse vector for the
corresponding element of the first dimension of the ``SparseNdarray``.
``index`` should be a :py:class:`~numpy.ndarray` of integers where entries
are strictly increasing and less than the extent of the first dimension.
All ``index`` objects in the same ``SparseNdarray`` should have the same
``dtype`` (defined by the ``index_dtype`` property). ``value`` may be any
numeric/boolean :py:class:`~numpy.ndarray` but the ``dtype`` should be
consistent across all ``value`` objects in the ``SparseNdarray``. If the
array contains masked values, all ``value`` objects should be a
``MaskedArray``, otherwise they should be regular NumPy arrays.
Any entry of any (nested) list may also be None, indicating that the
corresponding element of the dimension contains no non-zero values. In
fact, the entire tree may be None, indicating that there are no non-zero
values in the entire array.
For 1-dimensional arrays, the contents should be a single ``(index,
value)`` tuple containing the sparse contents. This may also be None if
there are no non-zero values in the array.
"""
def __init__(
self,
shape: Tuple[int, ...],
contents,
dtype: Optional[numpy.dtype] = None,
index_dtype: Optional[numpy.dtype] = None,
is_masked: Optional[bool] = None,
check: bool = True,
):
"""
Args:
shape:
Tuple specifying the dimensions of the array.
contents:
For ``n``-dimensional arrays where ``n`` > 1, a nested list representing a
tree where each leaf node is a tuple containing a sparse vector (or None).
For 1-dimensional arrays, a tuple containing a sparse vector.
Alternatively None, if the array is empty.
dtype:
NumPy type of the array values.
If None, this is inferred from ``contents``.
index_dtype:
NumPy type of the array indices.
If None, this is inferred from ``contents``.
is_masked:
Whether ``contents`` contains masked values.
If None, this is inferred from ``contents``.
check:
Whether to check the consistency of the ``contents`` during construction.
This can be set to False for speed.
"""
self._shape = shape
self._contents = contents
ndim = len(shape)
if dtype is None or index_dtype is None or is_masked is None:
if contents is not None:
if ndim > 1:
info = _peek(contents, dim=ndim-1)
if info is not None:
index_dtype0 = info[0]
dtype0 = info[1]
is_masked0 = info[2]
else:
dtype0 = None
index_dtype0 = None
is_masked0 = False
else:
index_dtype0 = contents[0].dtype
dtype0 = contents[1].dtype
is_masked0 = numpy.ma.isMaskedArray(contents[1])
if dtype is None:
dtype = dtype0
if index_dtype is None:
index_dtype = index_dtype0
if is_masked is None:
is_masked = is_masked0
if dtype is None:
raise ValueError("cannot infer 'dtype' from 'contents'")
if index_dtype is None:
raise ValueError("cannot infer 'index_dtype' from 'contents'")
if is_masked is None:
is_masked = False
# Sometimes people put the numpy data class instead of the dtype.
# It's a common enough mistake that we ought to catch it here.
if not isinstance(dtype, numpy.dtype):
dtype = numpy.dtype(dtype)
if not isinstance(index_dtype, numpy.dtype):
index_dtype = numpy.dtype(index_dtype)
self._dtype = dtype
self._index_dtype = index_dtype
self._is_masked = is_masked
if check is True and contents is not None:
payload = _CheckPayload(dtype=self._dtype, index_dtype=self._index_dtype, is_masked=self._is_masked, max_index=self._shape[0])
if len(shape) > 1:
_recursive_check(self._contents, self._shape, payload=payload, dim=ndim-1)
else:
_check_sparse_tuple(self._contents[0], self._contents[1], payload=payload)
@property
def shape(self) -> Tuple[int, ...]:
"""
Returns:
Tuple of integers specifying the extent of each dimension.
"""
return self._shape
@property
def dtype(self) -> numpy.dtype:
"""
Returns:
NumPy type of the values.
"""
return self._dtype
@property
def index_dtype(self) -> numpy.dtype:
"""
Returns:
NumPy type of the indices.
"""
return self._index_dtype
@property
def is_masked(self) -> bool:
"""
Returns:
Whether the values are masked.
"""
return self._is_masked
@property
def contents(self):
"""Contents of the array. This is intended to be read-only and
should only be modified if you really know what you're doing.
Returns:
A nested list, for a n-dimensional array where n > 1.
A tuple containing a sparse vector (i.e., indices and values), for a 1-dimensional array.
Alternatively None, if the array contains no non-zero elements.
"""
return self._contents
def __repr__(self) -> str:
"""
Pretty-print this ``SparseNdarray``. This uses
:py:func:`~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._shape]) + ">"
preamble += " " + type(self).__name__ + " object of type '" + self._dtype.name + "'"
indices = _repr_subset(self._shape)
bits_and_pieces = _extract_dense_array_from_SparseNdarray(self, indices)
converted = numpy.array2string(bits_and_pieces, separator=", ", threshold=0)
return preamble + "\n" + converted
# For NumPy:
def __array__(self, dtype: Optional[numpy.dtype] = None, copy: bool = True) -> numpy.ndarray:
"""Convert a ``SparseNdarray`` to a 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:
Dense array of the same type as :py:attr:`~dtype` and shape as
:py:attr:`~shape`.
"""
indices = _spawn_indices(self._shape)
return _extract_dense_array_from_SparseNdarray(self, indices, dtype=dtype)
# Assorted dunder methods.
def __add__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Add something to the right-hand-side of a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the addition.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="add", right=True)
def __radd__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Add something to the left-hand-side of a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the addition.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="add", right=False)
def __sub__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Subtract something from the right-hand-side of a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the subtraction.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="subtract", right=True)
def __rsub__(self, other):
"""Subtract a ``SparseNdarray`` from something else.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the subtraction.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="subtract", right=False)
def __mul__(self, other):
"""Multiply a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the multiplication.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="multiply", right=True)
def __rmul__(self, other):
"""Multiply a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the multiplication.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="multiply", right=False)
def __truediv__(self, other):
"""Divide a ``SparseNdarray`` by something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the division.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="divide", right=True)
def __rtruediv__(self, other):
"""Divide something by a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the division.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="divide", right=False)
def __mod__(self, other):
"""Take the remainder after dividing a ``SparseNdarray`` by something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the modulo.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="remainder", right=True)
def __rmod__(self, other):
"""Take the remainder after dividing something by a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the modulo.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="remainder", right=False
)
def __floordiv__(self, other):
"""Divide a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the floor division.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="floor_divide", right=True
)
def __rfloordiv__(self, other):
"""Divide something by a ``SparseNdarray`` and take the floor.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the floor division.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="floor_divide", right=False
)
def __pow__(self, other):
"""Raise a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the power operation.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="power", right=True)
def __rpow__(self, other):
"""Raise something to the power of the contents of a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the power operation.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="power", right=False)
def __eq__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check for equality between a ``SparseNdarray`` and something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="equal", right=True)
def __req__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check for equality between something and a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="equal", right=False)
def __ne__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check for non-equality between a ``SparseNdarray`` and something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="not_equal", right=True)
def __rne__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check for non-equality between something and a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="not_equal", right=False)
def __ge__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="greater_equal", right=True)
def __rge__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether something is greater than or equal to a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="greater_equal", right=False
)
def __le__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether a ``SparseNdarray`` 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 any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="less_equal", right=True
)
def __rle__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether something is greater than or equal to a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(
self, other, operation="less_equal", right=False
)
def __gt__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether a ``SparseNdarray`` is greater than something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="greater", right=True)
def __rgt__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether something is greater than a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="greater", right=False)
def __lt__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether a ``SparseNdarray`` is less than something.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="less", right=True)
def __rlt__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""Check whether something is less than a ``SparseNdarray``.
Args:
other:
A numeric scalar;
or a NumPy array with dimensions as described in
:py:class:`~delayedarray.UnaryIsometricOpWithArgs.UnaryIsometricOpWithArgs`;
or any seed object of the same dimensions as :py:attr:`~shape`.
Returns:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="less", right=False)
# Simple methods.
def __neg__(self):
"""Negate the contents of a ``SparseNdarray``.
Returns:
A ``SparseNdarray`` containing the delayed negation.
"""
return _transform_sparse_array_from_SparseNdarray(self, lambda l, i, v : (i, -v), self._dtype)
def __abs__(self):
"""Take the absolute value of the contents of a ``SparseNdarray``.
Returns:
A ``SparseNdarray`` containing the delayed absolute value operation.
"""
return _transform_sparse_array_from_SparseNdarray(self, lambda l, i, v : (i, abs(v)), self._dtype)
def __or__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""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:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="logical_or", right=True)
def __ror__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""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:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="logical_or", right=False)
def __and__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""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:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="logical_and", right=True)
def __rand__(self, other) -> Union["SparseNdarray", numpy.ndarray]:
"""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:
Array containing the result of the check.
This may or may not be sparse depending on ``other``.
"""
return _operate_with_args_on_SparseNdarray(self, other, operation="logical_and", right=False)
# Subsetting.
def __getitem__(self, subset) -> Union["SparseNdarray", numpy.ndarray]:
"""Take a subset of this ``SparseNdarray``. 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 ``SparseNdarray``, or a single integer specfying an index on the first dimension.
We attempt to support most types of NumPy slicing; however, only subsets that preserve dimensionality will generate a ``SparseNdarray``.
Raises:
ValueError: If ``args`` contain more dimensions than the shape of the array.
Returns:
If the dimensionality is preserved by ``subset``, a ``SparseNdarray`` containing the specified subset 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:
# No need to sanitize here, as the extractors can take unsorted subsets.
return _extract_sparse_array_from_SparseNdarray(self, cleaned)
return _getitem_subset_discards_dimensions(self, subset, _extract_dense_array_from_SparseNdarray)
# NumPy methods.
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) -> "SparseNdarray":
"""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 ``SparseNdarray``
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 ``SparseNdarray`` 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 numpy.ndarray method gets called first.
op = ufunc.__name__
if ufunc.__name__ == "true_divide":
op = "divide"
first_is_da = isinstance(inputs[0], SparseNdarray)
da = inputs[1 - int(first_is_da)]
v = inputs[int(first_is_da)]
return _operate_with_args_on_SparseNdarray(self, v, op, right=False)
elif ufunc.__name__ in translate_ufunc_to_op_simple:
dummy = ufunc(numpy.zeros(1, dtype=self._dtype))
if dummy[0] == 0:
return _transform_sparse_array_from_SparseNdarray(self, lambda l, i, v : (i, ufunc(v)), dummy.dtype)
else:
return ufunc(self.__array__())
elif ufunc.__name__ == "absolute":
return self.__abs__()
raise NotImplementedError(f"'{ufunc.__name__}' is not implemented!")
def __array_function__(self, func, types, args, kwargs) -> "SparseNdarray":
"""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 ``SparseNdarray`` instance containing the requested operation.
"""
if func == numpy.concatenate:
if "axis" in kwargs:
axis = kwargs["axis"]
else:
axis = 0
return _concatenate_SparseNdarrays(args[0], along=axis)
if func == numpy.transpose:
if "axes" in kwargs:
axes = kwargs["axes"]
else:
axes = list(range(len(self._shape) - 1, -1, -1))
return _transpose_SparseNdarray(self, axes)
if func == numpy.round:
return _transform_sparse_array_from_SparseNdarray(self, lambda l, i, v : (i, func(v, **kwargs)), self._dtype)
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)
raise NotImplementedError(f"'{func.__name__}' is not implemented!")
def astype(self, dtype: numpy.dtype, **kwargs) -> "SparseNdarray":
"""See :py:meth:`~numpy.ndarray.astype` for details.
All keyword arguments are currently ignored.
"""
return _transform_sparse_array_from_SparseNdarray(self, lambda l, i, v : (i, v.astype(dtype)), dtype)
@property
def T(self) -> "SparseNdarray":
"""
Returns:
A ``SparseNdarray`` containing the transposed contents.
"""
axes = list(range(len(self._shape) - 1, -1, -1))
return _transpose_SparseNdarray(self, axes)
def sum(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None) -> numpy.ndarray:
"""
Take the sum of values across the ``SparseNdarray``, possibly over a
given axis or set of axes.
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 ``SparseNdarray``, see
:py:func:`~numpy.sum` for details.
Returns:
A NumPy array containing the summed values. If ``axis = None``,
this will be a NumPy scalar instead.
"""
return array_sum(
self,
axis=axis,
dtype=dtype,
reduce_over_x=_reduce_SparseNdarray,
masked=self._is_masked,
)
def mean(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None) -> numpy.ndarray:
"""
Take the mean of values across the ``SparseNdarray``, possibly over a
given axis or set of axes.
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 ``SparseNdarray``, see
:py:func:`~numpy.mean` for details.
Returns:
A NumPy array containing the mean values. If ``axis = None``,
this will be a NumPy scalar instead.
"""
return array_mean(
self,
axis=axis,
dtype=dtype,
reduce_over_x=_reduce_SparseNdarray,
masked=self._is_masked,
)
def var(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None, ddof: int = 0) -> numpy.ndarray:
"""
Take the variances of values across the ``SparseNdarray``, possibly
over a given axis or set of axes.
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 ``SparseNdarray``, 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.
Returns:
A NumPy array containing the variances. If ``axis = None``,
this will be a NumPy scalar instead.
"""
return array_var(
self,
axis=axis,
dtype=dtype,
ddof=ddof,
reduce_over_x=_reduce_SparseNdarray,
masked=self._is_masked,
)
def any(self, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[numpy.dtype] = None) -> numpy.ndarray:
"""Test whether any array element along a given axis evaluates to True.
Compute this test across the ``SparseNdarray``, 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 ``SparseNdarray``, see
:py:func:`~numpy.any` for details.
Returns:
A NumPy array containing the variances. If ``axis = None``,
this will be a NumPy scalar instead.
"""
return array_any(
self,
axis=axis,
dtype=dtype,